@fluidframework/tree-agent 2.81.0 → 2.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"methodBinding.js","sourceRoot":"","sources":["../src/methodBinding.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGhD,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AA2BtD;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAsB;IACtD,OAAO,CACN,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,MAAM;QAC/B,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,MAAM;QAC/B,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,KAAK;QAC9B,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,GAAG,CAC5B,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,WAA2B;IAI5D,OAAO,eAAe,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC;AAoCD;;GAEG;AACH,MAAM,OAAO,eAAe;IAQ3B,YACiB,IAAY,EACZ,WAA+B,EAC/B,IAAoB;IACpC,kDAAkD;IAClC,IAA2C,EAC3C,OAAuC;QALvC,SAAI,GAAJ,IAAI,CAAQ;QACZ,gBAAW,GAAX,WAAW,CAAoB;QAC/B,SAAI,GAAJ,IAAI,CAAgB;QAEpB,SAAI,GAAJ,IAAI,CAAuC;QAC3C,YAAO,GAAP,OAAO,CAAgC;IACrD,CAAC;CACJ;AAYD;;;GAGG;AACH,MAAM,UAAU,SAAS,CAKxB,GAA2D,EAC3D,GAAG,IAAU;IAEb,OAAO;QACN,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,IAAI;QACJ,IAAI,EAAE,GAAG,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All rights reserved.\n * Licensed under the MIT License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { TreeNodeSchema, TreeNodeSchemaClass } from \"@fluidframework/tree\";\nimport { NodeKind } from \"@fluidframework/tree\";\nimport type { z } from \"zod\";\n\nimport { instanceOf } from \"./renderZodTypeScript.js\";\nimport type { TypeFactoryType } from \"./treeAgentTypes.js\";\n\n/**\n * A utility type that extracts the method keys from a given type.\n * @alpha\n */\nexport type MethodKeys<T> = {\n\t[K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;\n};\n\n/**\n * A type that represents a constructor function.\n * @alpha\n */\nexport type Ctor<T = any> = new (...args: any[]) => T;\n\n/**\n * A type that represents an object schema class.\n * @alpha\n */\nexport type BindableSchema =\n\t| TreeNodeSchema<string, NodeKind.Object>\n\t| TreeNodeSchema<string, NodeKind.Record>\n\t| TreeNodeSchema<string, NodeKind.Array>\n\t| TreeNodeSchema<string, NodeKind.Map>;\n\n/**\n * A type guard to check if a schema is {@link BindableSchema | bindable}.\n */\nexport function isBindableSchema(schema: TreeNodeSchema): schema is BindableSchema {\n\treturn (\n\t\tschema.kind === NodeKind.Object ||\n\t\tschema.kind === NodeKind.Record ||\n\t\tschema.kind === NodeKind.Array ||\n\t\tschema.kind === NodeKind.Map\n\t);\n}\n\n/**\n * Get the exposed methods of a schema class.\n * @param schemaClass - The schema class to extract methods from.\n * @returns A record of method names and their corresponding Zod types.\n */\nexport function getExposedMethods(schemaClass: BindableSchema): {\n\tmethods: Record<string, FunctionWrapper>;\n\treferencedTypes: Set<TreeNodeSchema>;\n} {\n\treturn ExposedMethodsI.getExposedMethods(schemaClass);\n}\n\n/**\n * A type that represents a function argument.\n * @alpha\n */\nexport type Arg<T extends z.ZodTypeAny | TypeFactoryType = z.ZodTypeAny | TypeFactoryType> =\n\treadonly [name: string, type: T];\n\n/**\n * A function definition interface that describes the structure of a function.\n * @alpha\n */\nexport interface FunctionDef<\n\tArgs extends readonly Arg[],\n\tReturn extends z.ZodTypeAny | TypeFactoryType,\n\tRest extends z.ZodTypeAny | TypeFactoryType | null = null,\n> {\n\t/**\n\t * Optional description of the function.\n\t */\n\tdescription?: string;\n\t/**\n\t * The function's parameters.\n\t */\n\targs: Args;\n\t/**\n\t * Optional rest parameter type.\n\t */\n\trest?: Rest;\n\t/**\n\t * The function's return type.\n\t */\n\treturns: Return;\n}\n\n/**\n * A class that implements the FunctionDef interface.\n */\nexport class FunctionWrapper\n\timplements\n\t\tFunctionDef<\n\t\t\treadonly Arg[],\n\t\t\tz.ZodTypeAny | TypeFactoryType,\n\t\t\tz.ZodTypeAny | TypeFactoryType | null\n\t\t>\n{\n\tpublic constructor(\n\t\tpublic readonly name: string,\n\t\tpublic readonly description: string | undefined,\n\t\tpublic readonly args: readonly Arg[],\n\t\t// eslint-disable-next-line @rushstack/no-new-null\n\t\tpublic readonly rest: z.ZodTypeAny | TypeFactoryType | null,\n\t\tpublic readonly returns: z.ZodTypeAny | TypeFactoryType,\n\t) {}\n}\n\n/**\n * A utility type that extracts the argument types from a function definition.\n * @alpha\n */\nexport type ArgsTuple<T extends readonly Arg[]> = T extends readonly [infer Single extends Arg]\n\t? [Single[1]]\n\t: T extends readonly [infer Head extends Arg, ...infer Tail extends readonly Arg[]]\n\t\t? [Head[1], ...ArgsTuple<Tail>]\n\t\t: never;\n\n/**\n * A utility function to build a function definition.\n * @alpha\n */\nexport function buildFunc<\n\tconst Return extends z.ZodTypeAny | TypeFactoryType,\n\tconst Args extends readonly Arg[],\n\tconst Rest extends z.ZodTypeAny | TypeFactoryType | null = null,\n>(\n\tdef: { description?: string; returns: Return; rest?: Rest },\n\t...args: Args\n): FunctionDef<Args, Return, Rest> {\n\treturn {\n\t\tdescription: def.description,\n\t\treturns: def.returns,\n\t\targs,\n\t\trest: def.rest,\n\t};\n}\n\n/**\n * A utility type that extracts inferred parameter types from Zod args.\n * @alpha\n */\nexport type InferArgsZod<Args extends readonly Arg<z.ZodTypeAny>[]> = Args extends readonly [\n\tinfer Head extends Arg<z.ZodTypeAny>,\n\t...infer Tail extends readonly Arg<z.ZodTypeAny>[],\n]\n\t? [z.infer<Head[1]>, ...InferArgsZod<Tail>]\n\t: [];\n\n/**\n * A utility type that infers the function signature from a Zod function definition with strict type checking.\n * @alpha\n */\nexport type InferZod<T> = T extends FunctionDef<\n\tinfer Args extends readonly Arg<z.ZodTypeAny>[],\n\tinfer Return extends z.ZodTypeAny,\n\tany\n>\n\t? (...args: InferArgsZod<Args>) => z.infer<Return>\n\t: never;\n\n/**\n * A utility type that infers the function signature from a type factory function definition with relaxed type checking.\n * @alpha\n */\nexport type InferTypeFactory<T> = T extends FunctionDef<readonly Arg[], infer Return, any>\n\t? (...args: any[]) => any\n\t: never;\n\n/**\n * A utility type that infers the return type of a function definition.\n * @alpha\n * @remarks\n * For Zod types, provides strict compile-time type checking. For type factory types, returns `any`.\n * @deprecated Use InferZod or InferTypeFactory directly for better type safety.\n */\nexport type Infer<T> = T extends FunctionDef<readonly Arg[], infer Return, any>\n\t? Return extends z.ZodTypeAny\n\t\t? InferZod<T>\n\t\t: InferTypeFactory<T>\n\t: never;\n\n/**\n * An interface for exposing methods of schema classes to an agent.\n * @alpha\n */\nexport interface ExposedMethods {\n\t/**\n\t * Expose a method with Zod types (strict compile-time type checking).\n\t */\n\texpose<\n\t\tconst K extends string & keyof MethodKeys<InstanceType<S>>,\n\t\tS extends BindableSchema & Ctor<Record<K, InferZod<Z>>> & IExposedMethods,\n\t\tZ extends FunctionDef<readonly Arg<z.ZodTypeAny>[], z.ZodTypeAny, z.ZodTypeAny | null>,\n\t>(schema: S, methodName: K, zodFunction: Z): void;\n\n\t/**\n\t * Expose a method with type factory types (relaxed compile-time type checking).\n\t */\n\texpose<\n\t\tconst K extends string & keyof MethodKeys<InstanceType<S>>,\n\t\tS extends BindableSchema & Ctor & IExposedMethods,\n\t\tZ extends FunctionDef<\n\t\t\treadonly Arg<TypeFactoryType>[],\n\t\t\tTypeFactoryType,\n\t\t\tTypeFactoryType | null\n\t\t>,\n\t>(schema: S, methodName: K, tfFunction: Z): void;\n\n\t/**\n\t * Create a Zod schema for a SharedTree schema class.\n\t * @remarks\n\t * Use it to \"wrap\" schema types that are referenced as arguments or return types when exposing methods with {@link ExposedMethods}.\n\t */\n\tinstanceOf<T extends TreeNodeSchemaClass>(\n\t\tschema: T,\n\t): z.ZodType<InstanceType<T>, z.ZodTypeDef, InstanceType<T>>;\n}\n\n/**\n * A symbol used to expose methods to the LLM.\n * @alpha\n */\nexport const exposeMethodsSymbol: unique symbol = Symbol(\"run\");\n\n/**\n * An interface that SharedTree schema classes should implement to expose their methods to the LLM.\n *\n * @remarks\n * The `getExposedMethods` free function will cause the method here to be called on the class passed to it.\n *\n * @privateremarks\n * Implementing this interface correctly seems tricky?\n * To actually implement it in a way that satisfies TypeScript,\n * classes need to declare both a static version and an instance version of the method\n * (the instance one can just delegate to the static one).\n *\n * @alpha\n */\nexport interface IExposedMethods {\n\t/**\n\t * Static method that exposes methods of this schema class to an agent.\n\t */\n\t[exposeMethodsSymbol](methods: ExposedMethods): void;\n}\n\nclass ExposedMethodsI implements ExposedMethods {\n\tprivate readonly methods: Record<string, FunctionWrapper> = {};\n\tprivate readonly referencedTypes = new Set<TreeNodeSchema>();\n\n\tpublic constructor(private readonly schemaClass: BindableSchema) {}\n\n\tpublic expose<\n\t\tconst K extends string & keyof MethodKeys<InstanceType<S>>,\n\t\tS extends BindableSchema & Ctor & IExposedMethods,\n\t\tZ extends FunctionDef<\n\t\t\treadonly Arg[],\n\t\t\tz.ZodTypeAny | TypeFactoryType,\n\t\t\tz.ZodTypeAny | TypeFactoryType | null\n\t\t>,\n\t>(schema: S, methodName: K, functionDef: Z): void {\n\t\tif (schema !== this.schemaClass) {\n\t\t\tthrow new Error('Must expose methods on the \"this\" object');\n\t\t}\n\t\tthis.methods[methodName] = new FunctionWrapper(\n\t\t\tmethodName,\n\t\t\tfunctionDef.description,\n\t\t\tfunctionDef.args,\n\t\t\t// eslint-disable-next-line unicorn/no-null\n\t\t\tfunctionDef.rest ?? null,\n\t\t\tfunctionDef.returns,\n\t\t);\n\t}\n\n\tpublic instanceOf<T extends TreeNodeSchemaClass>(\n\t\tschema: T,\n\t): z.ZodType<InstanceType<T>, z.ZodTypeDef, InstanceType<T>> {\n\t\tthis.referencedTypes.add(schema);\n\t\treturn instanceOf(schema);\n\t}\n\n\tpublic static getExposedMethods(schemaClass: BindableSchema): {\n\t\tmethods: Record<string, FunctionWrapper>;\n\t\treferencedTypes: Set<TreeNodeSchema>;\n\t} {\n\t\tconst exposedMethods = new ExposedMethodsI(schemaClass);\n\t\tconst extractable = schemaClass as unknown as IExposedMethods;\n\t\tif (extractable[exposeMethodsSymbol] !== undefined) {\n\t\t\textractable[exposeMethodsSymbol](exposedMethods);\n\t\t}\n\t\treturn {\n\t\t\tmethods: exposedMethods.methods,\n\t\t\treferencedTypes: exposedMethods.referencedTypes,\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"methodBinding.js","sourceRoot":"","sources":["../src/methodBinding.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGhD,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AA2BtD;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAsB;IACtD,OAAO,CACN,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,MAAM;QAC/B,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,MAAM;QAC/B,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,KAAK;QAC9B,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,GAAG,CAC5B,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,WAA2B;IAI5D,OAAO,eAAe,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC;AAoCD;;GAEG;AACH,MAAM,OAAO,eAAe;IAQ3B,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MAAM,CAAC,CAAC;IAC3B,CAAC;IAEM,MAAM,CAAC,iBAAiB,CAAC,WAA2B;QAI1D,MAAM,cAAc,GAAG,IAAI,eAAe,CAAC,WAAW,CAAC,CAAC;QACxD,MAAM,WAAW,GAAG,WAAyC,CAAC;QAC9D,IAAI,WAAW,CAAC,mBAAmB,CAAC,KAAK,SAAS,EAAE,CAAC;YACpD,WAAW,CAAC,mBAAmB,CAAC,CAAC,cAAc,CAAC,CAAC;QAClD,CAAC;QACD,OAAO;YACN,OAAO,EAAE,cAAc,CAAC,OAAO;YAC/B,eAAe,EAAE,cAAc,CAAC,eAAe;SAC/C,CAAC;IACH,CAAC;CACD","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { TreeNodeSchema, TreeNodeSchemaClass } from \"@fluidframework/tree\";\nimport { NodeKind } from \"@fluidframework/tree\";\nimport type { z } from \"zod\";\n\nimport { instanceOf } from \"./renderZodTypeScript.js\";\nimport type { TypeFactoryType } from \"./treeAgentTypes.js\";\n\n/**\n * A utility type that extracts the method keys from a given type.\n * @alpha\n */\nexport type MethodKeys<T> = {\n\t[K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;\n};\n\n/**\n * A type that represents a constructor function.\n * @alpha\n */\nexport type Ctor<T = any> = new (...args: any[]) => T;\n\n/**\n * A type that represents an object schema class.\n * @alpha\n */\nexport type BindableSchema =\n\t| TreeNodeSchema<string, NodeKind.Object>\n\t| TreeNodeSchema<string, NodeKind.Record>\n\t| TreeNodeSchema<string, NodeKind.Array>\n\t| TreeNodeSchema<string, NodeKind.Map>;\n\n/**\n * A type guard to check if a schema is {@link BindableSchema | bindable}.\n */\nexport function isBindableSchema(schema: TreeNodeSchema): schema is BindableSchema {\n\treturn (\n\t\tschema.kind === NodeKind.Object ||\n\t\tschema.kind === NodeKind.Record ||\n\t\tschema.kind === NodeKind.Array ||\n\t\tschema.kind === NodeKind.Map\n\t);\n}\n\n/**\n * Get the exposed methods of a schema class.\n * @param schemaClass - The schema class to extract methods from.\n * @returns A record of method names and their corresponding Zod types.\n */\nexport function getExposedMethods(schemaClass: BindableSchema): {\n\tmethods: Record<string, FunctionWrapper>;\n\treferencedTypes: Set<TreeNodeSchema>;\n} {\n\treturn ExposedMethodsI.getExposedMethods(schemaClass);\n}\n\n/**\n * A type that represents a function argument.\n * @alpha\n */\nexport type Arg<T extends z.ZodTypeAny | TypeFactoryType = z.ZodTypeAny | TypeFactoryType> =\n\treadonly [name: string, type: T];\n\n/**\n * A function definition interface that describes the structure of a function.\n * @alpha\n */\nexport interface FunctionDef<\n\tArgs extends readonly Arg[],\n\tReturn extends z.ZodTypeAny | TypeFactoryType,\n\tRest extends z.ZodTypeAny | TypeFactoryType | null = null,\n> {\n\t/**\n\t * Optional description of the function.\n\t */\n\tdescription?: string;\n\t/**\n\t * The function's parameters.\n\t */\n\targs: Args;\n\t/**\n\t * Optional rest parameter type.\n\t */\n\trest?: Rest;\n\t/**\n\t * The function's return type.\n\t */\n\treturns: Return;\n}\n\n/**\n * A class that implements the FunctionDef interface.\n */\nexport class FunctionWrapper\n\timplements\n\t\tFunctionDef<\n\t\t\treadonly Arg[],\n\t\t\tz.ZodTypeAny | TypeFactoryType,\n\t\t\tz.ZodTypeAny | TypeFactoryType | null\n\t\t>\n{\n\tpublic constructor(\n\t\tpublic readonly name: string,\n\t\tpublic readonly description: string | undefined,\n\t\tpublic readonly args: readonly Arg[],\n\t\t// eslint-disable-next-line @rushstack/no-new-null\n\t\tpublic readonly rest: z.ZodTypeAny | TypeFactoryType | null,\n\t\tpublic readonly returns: z.ZodTypeAny | TypeFactoryType,\n\t) {}\n}\n\n/**\n * A utility type that extracts the argument types from a function definition.\n * @alpha\n */\nexport type ArgsTuple<T extends readonly Arg[]> = T extends readonly [infer Single extends Arg]\n\t? [Single[1]]\n\t: T extends readonly [infer Head extends Arg, ...infer Tail extends readonly Arg[]]\n\t\t? [Head[1], ...ArgsTuple<Tail>]\n\t\t: never;\n\n/**\n * A utility function to build a function definition.\n * @alpha\n */\nexport function buildFunc<\n\tconst Return extends z.ZodTypeAny | TypeFactoryType,\n\tconst Args extends readonly Arg[],\n\tconst Rest extends z.ZodTypeAny | TypeFactoryType | null = null,\n>(\n\tdef: { description?: string; returns: Return; rest?: Rest },\n\t...args: Args\n): FunctionDef<Args, Return, Rest> {\n\treturn {\n\t\tdescription: def.description,\n\t\treturns: def.returns,\n\t\targs,\n\t\trest: def.rest,\n\t};\n}\n\n/**\n * A utility type that extracts inferred parameter types from Zod args.\n * @alpha\n */\nexport type InferArgsZod<Args extends readonly Arg<z.ZodTypeAny>[]> = Args extends readonly [\n\tinfer Head extends Arg<z.ZodTypeAny>,\n\t...infer Tail extends readonly Arg<z.ZodTypeAny>[],\n]\n\t? [z.infer<Head[1]>, ...InferArgsZod<Tail>]\n\t: [];\n\n/**\n * A utility type that infers the function signature from a Zod function definition with strict type checking.\n * @alpha\n */\nexport type InferZod<T> =\n\tT extends FunctionDef<\n\t\tinfer Args extends readonly Arg<z.ZodTypeAny>[],\n\t\tinfer Return extends z.ZodTypeAny,\n\t\tany\n\t>\n\t\t? (...args: InferArgsZod<Args>) => z.infer<Return>\n\t\t: never;\n\n/**\n * A utility type that infers the function signature from a type factory function definition with relaxed type checking.\n * @alpha\n */\nexport type InferTypeFactory<T> =\n\tT extends FunctionDef<readonly Arg[], infer Return, any> ? (...args: any[]) => any : never;\n\n/**\n * A utility type that infers the return type of a function definition.\n * @alpha\n * @remarks\n * For Zod types, provides strict compile-time type checking. For type factory types, returns `any`.\n * @deprecated Use InferZod or InferTypeFactory directly for better type safety.\n */\nexport type Infer<T> =\n\tT extends FunctionDef<readonly Arg[], infer Return, any>\n\t\t? Return extends z.ZodTypeAny\n\t\t\t? InferZod<T>\n\t\t\t: InferTypeFactory<T>\n\t\t: never;\n\n/**\n * An interface for exposing methods of schema classes to an agent.\n * @alpha\n */\nexport interface ExposedMethods {\n\t/**\n\t * Expose a method with Zod types (strict compile-time type checking).\n\t */\n\texpose<\n\t\tconst K extends string & keyof MethodKeys<InstanceType<S>>,\n\t\tS extends BindableSchema & Ctor<Record<K, InferZod<Z>>> & IExposedMethods,\n\t\tZ extends FunctionDef<readonly Arg<z.ZodTypeAny>[], z.ZodTypeAny, z.ZodTypeAny | null>,\n\t>(schema: S, methodName: K, zodFunction: Z): void;\n\n\t/**\n\t * Expose a method with type factory types (relaxed compile-time type checking).\n\t */\n\texpose<\n\t\tconst K extends string & keyof MethodKeys<InstanceType<S>>,\n\t\tS extends BindableSchema & Ctor & IExposedMethods,\n\t\tZ extends FunctionDef<\n\t\t\treadonly Arg<TypeFactoryType>[],\n\t\t\tTypeFactoryType,\n\t\t\tTypeFactoryType | null\n\t\t>,\n\t>(schema: S, methodName: K, tfFunction: Z): void;\n\n\t/**\n\t * Create a Zod schema for a SharedTree schema class.\n\t * @remarks\n\t * Use it to \"wrap\" schema types that are referenced as arguments or return types when exposing methods with {@link ExposedMethods}.\n\t */\n\tinstanceOf<T extends TreeNodeSchemaClass>(\n\t\tschema: T,\n\t): z.ZodType<InstanceType<T>, z.ZodTypeDef, InstanceType<T>>;\n}\n\n/**\n * A symbol used to expose methods to the LLM.\n * @alpha\n */\nexport const exposeMethodsSymbol: unique symbol = Symbol(\"run\");\n\n/**\n * An interface that SharedTree schema classes should implement to expose their methods to the LLM.\n *\n * @remarks\n * The `getExposedMethods` free function will cause the method here to be called on the class passed to it.\n *\n * @privateremarks\n * Implementing this interface correctly seems tricky?\n * To actually implement it in a way that satisfies TypeScript,\n * classes need to declare both a static version and an instance version of the method\n * (the instance one can just delegate to the static one).\n *\n * @alpha\n */\nexport interface IExposedMethods {\n\t/**\n\t * Static method that exposes methods of this schema class to an agent.\n\t */\n\t[exposeMethodsSymbol](methods: ExposedMethods): void;\n}\n\nclass ExposedMethodsI implements ExposedMethods {\n\tprivate readonly methods: Record<string, FunctionWrapper> = {};\n\tprivate readonly referencedTypes = new Set<TreeNodeSchema>();\n\n\tpublic constructor(private readonly schemaClass: BindableSchema) {}\n\n\tpublic expose<\n\t\tconst K extends string & keyof MethodKeys<InstanceType<S>>,\n\t\tS extends BindableSchema & Ctor & IExposedMethods,\n\t\tZ extends FunctionDef<\n\t\t\treadonly Arg[],\n\t\t\tz.ZodTypeAny | TypeFactoryType,\n\t\t\tz.ZodTypeAny | TypeFactoryType | null\n\t\t>,\n\t>(schema: S, methodName: K, functionDef: Z): void {\n\t\tif (schema !== this.schemaClass) {\n\t\t\tthrow new Error('Must expose methods on the \"this\" object');\n\t\t}\n\t\tthis.methods[methodName] = new FunctionWrapper(\n\t\t\tmethodName,\n\t\t\tfunctionDef.description,\n\t\t\tfunctionDef.args,\n\t\t\t// eslint-disable-next-line unicorn/no-null\n\t\t\tfunctionDef.rest ?? null,\n\t\t\tfunctionDef.returns,\n\t\t);\n\t}\n\n\tpublic instanceOf<T extends TreeNodeSchemaClass>(\n\t\tschema: T,\n\t): z.ZodType<InstanceType<T>, z.ZodTypeDef, InstanceType<T>> {\n\t\tthis.referencedTypes.add(schema);\n\t\treturn instanceOf(schema);\n\t}\n\n\tpublic static getExposedMethods(schemaClass: BindableSchema): {\n\t\tmethods: Record<string, FunctionWrapper>;\n\t\treferencedTypes: Set<TreeNodeSchema>;\n\t} {\n\t\tconst exposedMethods = new ExposedMethodsI(schemaClass);\n\t\tconst extractable = schemaClass as unknown as IExposedMethods;\n\t\tif (extractable[exposeMethodsSymbol] !== undefined) {\n\t\t\textractable[exposeMethodsSymbol](exposedMethods);\n\t\t}\n\t\treturn {\n\t\t\tmethods: exposedMethods.methods,\n\t\t\treferencedTypes: exposedMethods.referencedTypes,\n\t\t};\n\t}\n}\n"]}
package/lib/prompt.d.ts CHANGED
@@ -5,6 +5,10 @@
5
5
  import type { ImplicitFieldSchema } from "@fluidframework/tree";
6
6
  import type { ReadableField } from "@fluidframework/tree/alpha";
7
7
  import type { Subtree } from "./subtree.js";
8
+ /**
9
+ * The type name used for handles in generated TypeScript.
10
+ */
11
+ export declare const fluidHandleTypeName = "_OpaqueHandle";
8
12
  /**
9
13
  * Produces a "system" prompt for the tree agent, based on the provided subtree.
10
14
  */
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAC;AAC7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAIhE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAI5C;;GAEG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE;IAC/B,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,CAAC;IAChE,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,MAAM,CAgRT;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,aAAa,CAAC,mBAAmB,CAAC,GAAG,MAAM,CA8C9E"}
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAC;AAC7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAIhE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAI5C;;GAEG;AACH,eAAO,MAAM,mBAAmB,kBAAkB,CAAC;AAEnD;;GAEG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE;IAC/B,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,CAAC;IAChE,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,MAAM,CA8RT;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,aAAa,CAAC,mBAAmB,CAAC,GAAG,MAAM,CA8C9E"}
package/lib/prompt.js CHANGED
@@ -5,9 +5,13 @@
5
5
  import { oob } from "@fluidframework/core-utils/internal";
6
6
  import { NodeKind, Tree, TreeNode } from "@fluidframework/tree";
7
7
  import { getSimpleSchema } from "@fluidframework/tree/alpha";
8
- import { normalizeFieldSchema } from "@fluidframework/tree/internal";
8
+ import { normalizeFieldSchema, ValueSchema } from "@fluidframework/tree/internal";
9
9
  import { generateEditTypesForPrompt } from "./typeGeneration.js";
10
10
  import { getFriendlyName, communize, findSchemas } from "./utils.js";
11
+ /**
12
+ * The type name used for handles in generated TypeScript.
13
+ */
14
+ export const fluidHandleTypeName = "_OpaqueHandle";
11
15
  /**
12
16
  * Produces a "system" prompt for the tree agent, based on the provided subtree.
13
17
  */
@@ -22,6 +26,7 @@ export function getPrompt(args) {
22
26
  let nodeTypeUnion;
23
27
  let hasArrays = false;
24
28
  let hasMaps = false;
29
+ let hasFluidHandles = false;
25
30
  let exampleObjectName;
26
31
  for (const s of findSchemas(schema)) {
27
32
  if (s.kind !== NodeKind.Leaf) {
@@ -43,11 +48,24 @@ export function getPrompt(args) {
43
48
  exampleObjectName ??= getFriendlyName(s);
44
49
  break;
45
50
  }
51
+ case NodeKind.Leaf: {
52
+ hasFluidHandles ||= s.info === ValueSchema.FluidHandle;
53
+ break;
54
+ }
46
55
  // No default
47
56
  }
48
57
  }
49
58
  const stringified = stringifyTree(field);
50
59
  const { schemaText: typescriptSchemaTypes, hasHelperMethods } = generateEditTypesForPrompt(schema, getSimpleSchema(schema));
60
+ const fluidHandleType = hasFluidHandles
61
+ ? `/**
62
+ * Opaque handle type representing a reference to a Fluid object.
63
+ * This type should not be constructed by generated code.
64
+ */
65
+ type ${fluidHandleTypeName} = unknown;
66
+
67
+ `
68
+ : "";
51
69
  const exampleTypeName = nodeTypeUnion === undefined
52
70
  ? undefined
53
71
  : nodeTypeUnion
@@ -241,7 +259,7 @@ Finally, double check that the edits would accomplish the user's request (if it
241
259
  The JSON tree adheres to the following Typescript schema:
242
260
 
243
261
  \`\`\`typescript
244
- ${typescriptSchemaTypes}
262
+ ${fluidHandleType}${typescriptSchemaTypes}
245
263
  \`\`\`
246
264
 
247
265
  If the user asks you a question about the tree, you should inspect the state of the tree and answer the question.
package/lib/prompt.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,qCAAqC,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGhE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAGrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAErE;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,IAIzB;IACA,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAClC,MAAM,kBAAkB,GAAG,WAAW,CAAC;IACvC,MAAM,gBAAgB,GAAG,SAAS,CAAC;IACnC,6IAA6I;IAC7I,MAAM,SAAS,GAAG,CAAC,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,cAAc,CAAC,CAAC;IACnE,MAAM,aAAa,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eA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C,CAAC,CAAC;oBACT,OAAO;wBACN,CAAC,mBAAmB,CAAC,EAAE,KAAK;wBAC5B,GAAG,IAAI;qBACP,CAAC;gBACH,CAAC;YACF,CAAC;QACF,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC,EACD,CAAC,CACD,CAAC;IAEF,OAAO,WAAW;SAChB,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,kBAAkB,IAAI,EAAE,GAAG,CAAC,EAAE,UAAU,CAAC;SAChE,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,mBAAmB,IAAI,EAAE,GAAG,CAAC,EAAE,WAAW,CAAC;SAClE,OAAO,CACP,IAAI,MAAM,CAAC,IAAI,iBAAiB,OAAO,EAAE,GAAG,CAAC,EAC7C,4HAA4H,CAC5H,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,6BAA6B,CAAC,QAAgB;IACtD,OAAO;mBACW,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qEA0E0C,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAiDhE,QAAQ;;EAEnB,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,2BAA2B,CAAC,QAAgB;IACpD,OAAO;;;mBAGW,QAAQ;;;;;;;;kFAQuD,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDxF,CAAC;AACH,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { oob } from \"@fluidframework/core-utils/internal\";\nimport { NodeKind, Tree, TreeNode } from \"@fluidframework/tree\";\nimport type { ImplicitFieldSchema, TreeMapNode } from \"@fluidframework/tree\";\nimport type { ReadableField } from \"@fluidframework/tree/alpha\";\nimport { getSimpleSchema } from \"@fluidframework/tree/alpha\";\nimport { normalizeFieldSchema } from \"@fluidframework/tree/internal\";\n\nimport type { Subtree } from \"./subtree.js\";\nimport { generateEditTypesForPrompt } from \"./typeGeneration.js\";\nimport { getFriendlyName, communize, findSchemas } from \"./utils.js\";\n\n/**\n * Produces a \"system\" prompt for the tree agent, based on the provided subtree.\n */\nexport function getPrompt(args: {\n\tsubtree: Pick<Subtree<ImplicitFieldSchema>, \"schema\" | \"field\">;\n\teditToolName: string | undefined;\n\tdomainHints?: string;\n}): string {\n\tconst { subtree, editToolName, domainHints } = args;\n\tconst { field, schema } = subtree;\n\tconst arrayInterfaceName = \"TreeArray\";\n\tconst mapInterfaceName = \"TreeMap\";\n\t// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.\n\tconst rootTypes = [...normalizeFieldSchema(schema).allowedTypeSet];\n\tconst rootTypeUnion = `${rootTypes.map((t) => getFriendlyName(t)).join(\" | \")}`;\n\tlet nodeTypeUnion: string | undefined;\n\tlet hasArrays = false;\n\tlet hasMaps = false;\n\tlet exampleObjectName: string | undefined;\n\tfor (const s of findSchemas(schema)) {\n\t\tif (s.kind !== NodeKind.Leaf) {\n\t\t\tnodeTypeUnion =\n\t\t\t\tnodeTypeUnion === undefined\n\t\t\t\t\t? getFriendlyName(s)\n\t\t\t\t\t: `${nodeTypeUnion} | ${getFriendlyName(s)}`;\n\t\t}\n\n\t\tswitch (s.kind) {\n\t\t\tcase NodeKind.Array: {\n\t\t\t\thasArrays = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\thasMaps = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Object: {\n\t\t\t\texampleObjectName ??= getFriendlyName(s);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tconst stringified = stringifyTree(field);\n\tconst { schemaText: typescriptSchemaTypes, hasHelperMethods } = generateEditTypesForPrompt(\n\t\tschema,\n\t\tgetSimpleSchema(schema),\n\t);\n\tconst exampleTypeName =\n\t\tnodeTypeUnion === undefined\n\t\t\t? undefined\n\t\t\t: nodeTypeUnion\n\t\t\t\t\t.split(\"|\")\n\t\t\t\t\t.map((part) => part.trim())\n\t\t\t\t\t.find((part) => part.length > 0);\n\n\tconst createDocs =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `\\n\t/**\n\t * A collection of builder functions for creating new tree nodes.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to create a new node of that type.\n\t * Always use these builder functions when creating new nodes rather than plain JavaScript objects.\n\t *\n\t * For example:\n\t *\n\t * \\`\\`\\`javascript\n\t * // This creates a new ${exampleObjectName} object:\n\t * const ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ ...properties });\n\t * // Don't do this:\n\t * // const ${communize(exampleObjectName)} = { ...properties };\n\t * \\`\\`\\`\n\t */\n\tcreate: Record<string, <T extends TreeData>(input: T) => T>;\\n`;\n\n\tconst isDocs =\n\t\texampleTypeName === undefined\n\t\t\t? \"\"\n\t\t\t: `\\n\t/**\n\t * A collection of type-guard functions for data in the tree.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to check if a node is of that specific type.\n\t * This is useful when working with nodes that could be one of multiple types.\n\t *\n\t * ${`Example: Check if a node is a ${exampleTypeName} with \\`if (context.is.${exampleTypeName}(node)) {}\\``}\n\t */\n\tis: Record<string, <T extends TreeData>(data: unknown) => data is T>;\n\n\t/**\n\t * Checks if the provided data is an array.\n\t * @remarks\n\t * DO NOT use \\`Array.isArray\\` to check if tree data is an array - use this function instead.\n\t *\n\t * This function will also work for native JavaScript arrays.\n\t *\n\t * ${`Example: \\`if (context.isArray(node)) {}\\``}\n\t */\n\tisArray(data: any): boolean;\n\n\t/**\n\t * Checks if the provided data is a map.\n\t * @remarks\n\t * DO NOT use \\`instanceof Map\\` to check if tree data is a map - use this function instead.\n\t *\n\t * This function will also work for native JavaScript Map instances.\n\t *\n\t * ${`Example: \\`if (context.isMap(node)) {}\\``}\n\t */\n\tisMap(data: any): boolean;\\n`;\n\n\tconst context = `\\`\\`\\`typescript\n\t${nodeTypeUnion === undefined ? \"\" : `type TreeData = ${nodeTypeUnion};\\n\\n`}\t/**\n\t * An object available to generated code which provides read and write access to the tree as well as utilities for creating and inspecting data in the tree.\n\t * @remarks This object is available as a variable named \\`context\\` in the scope of the generated JavaScript snippet.\n\t */\n\tinterface Context<TSchema extends ImplicitFieldSchema> {\n\t/**\n\t * The root of the tree that can be read or mutated.\n\t * @remarks\n\t * You can read properties and navigate through the tree starting from this root.\n\t * You can also assign a new value to this property to replace the entire tree, as long as the new value is one of the types allowed at the root.\n\t *\n\t * Example: Read the current root with \\`const currentRoot = context.root;\\`\n\t *${rootTypes.length > 0 ? ` Example: Replace the entire root with \\`context.root = context.create.${getFriendlyName(rootTypes[0] ?? oob())}({ });\\`\\n\t *` : \"\"}/\n\troot: ReadableField<TSchema>;\n\t${createDocs}\n\t${isDocs}\n\t/**\n\t * Returns the parent object/array/map of the given object/array/map, if there is one.\n\t * @returns The parent node, or \\`undefined\\` if the node is the root or is not in the tree.\n\t * @remarks\n\t * Example: Get the parent with \\`const parent = context.parent(child);\\`\n\t */\n\tparent(child: TreeData): TreeData | undefined;\n\n\t/**\n\t * Returns the property key or index of the given object/array/map within its parent.\n\t * @returns A string key if the child is in an object or map, or a numeric index if the child is in an array.\n\t *\n\t * Example: \\`const key = context.key(child);\\`\n\t */\n\tkey(child: TreeData): string | number;\n}\n\\`\\`\\``;\n\n\tconst helperMethodExplanation = hasHelperMethods\n\t\t? `Manipulating the data using the APIs described below is allowed, but when possible ALWAYS prefer to use any application helper methods exposed on the schema TypeScript types if the goal can be accomplished that way.\nIt will often not be possible to fully accomplish the goal using those helpers. When this is the case, mutate the objects as normal, taking into account the following guidance.`\n\t\t: \"\";\n\n\tconst reinsertionExplanation = `Once non-primitive data has been removed from the tree (e.g. replaced via assignment, or removed from an array), that data cannot be re-inserted into the tree.\nInstead, it must be deep cloned and recreated.\n${\n\texampleObjectName === undefined\n\t\t? \"\"\n\t\t: `For example:\n\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst ${communize(exampleObjectName)} = parent.${communize(exampleObjectName)};\nparent.${communize(exampleObjectName)} = undefined;\n// \\`${communize(exampleObjectName)}\\` cannot be directly re-inserted into the tree - this will throw an error:\n// parent.${communize(exampleObjectName)} = ${communize(exampleObjectName)}; // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nparent.${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /*... deep clone all properties from \\`${communize(exampleObjectName)}\\` */ });\n\\`\\`\\`${\n\t\t\t\thasArrays\n\t\t\t\t\t? `\\n\\nThe same applies when using arrays:\\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst item = arrayOf${exampleObjectName}[0];\narrayOf${exampleObjectName}.removeAt(0);\n// \\`item\\` cannot be directly re-inserted into the tree - this will throw an error:\narrayOf${exampleObjectName}.insertAt(0, item); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\narrayOf${exampleObjectName}.insertAt(0, context.create.${exampleObjectName}({ /*... deep clone all properties from \\`item\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}${\n\t\t\t\thasMaps\n\t\t\t\t\t? `\\n\\nThe same applies when using maps:\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst value = mapOf${exampleObjectName}.get(\"someKey\");\nmapOf${exampleObjectName}.delete(\"someKey\");\n// \\`value\\` cannot be directly re-inserted into the tree - this will throw an error:\nmapOf${exampleObjectName}.set(\"someKey\", value); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nmapOf${exampleObjectName}.set(\"someKey\", context.create.${exampleObjectName}({ /*... deep clone all properties from \\`value\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}`\n}`;\n\n\tconst arrayEditing = `#### Editing Arrays\n\nThe arrays in the tree are somewhat different than normal JavaScript \\`Array\\`s.\nRead-only operations are generally the same - you can create them, read via index, and call non-mutating methods like \\`concat\\`, \\`map\\`, \\`filter\\`, \\`find\\`, \\`forEach\\`, \\`indexOf\\`, \\`slice\\`, \\`join\\`, etc.\nHowever, write operations (e.g. index assignment, \\`push\\`, \\`pop\\`, \\`splice\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the array:\n\n\\`\\`\\`typescript\n${getTreeArrayNodeDocumentation(arrayInterfaceName)}\n\\`\\`\\`\n\nWhen possible, ensure that the edits preserve the identity of objects already in the tree.\nFor example, prefer \\`array.moveToIndex\\` over \\`array.removeAt\\` + \\`array.insertAt\\` and prefer \\`array.moveRangeToIndex\\` over \\`array.removeRange\\` + \\`array.insertAt\\`.\n\n`;\n\n\tconst mapEditing = `#### Editing Maps\n\nThe maps in the tree are somewhat different than normal JavaScript \\`Map\\`s.\nMap keys are always strings.\nRead-only operations are generally the same - you can create them, read via \\`get\\`, and call non-mutating methods like \\`has\\`, \\`forEach\\`, \\`entries\\`, \\`keys\\`, \\`values\\`, etc. (note the subtle differences around return values and iteration order).\nHowever, write operations (e.g. \\`set\\`, \\`delete\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the map:\n\n\\`\\`\\`typescript\n${getTreeMapNodeDocumentation(mapInterfaceName)}\n\\`\\`\\`\n\n`;\n\n\tconst editing = `If the user asks you to edit the tree, you should author a snippet of JavaScript code to accomplish the user-specified goal, following the instructions for editing detailed below.\nYou must use the \"${editToolName}\" tool to run the generated code.\nAfter editing the tree, review the latest state of the tree to see if it satisfies the user's request.\nIf it does not, or if you receive an error, you may try again with a different approach.\nOnce the tree is in the desired state, you should inform the user that the request has been completed.\n\n### Editing\n\nIf the user asks you to edit the document, you will write a snippet of JavaScript code that mutates the data in-place to achieve the user's goal.\nThe snippet may be synchronous or asynchronous (i.e. it may \\`await\\` functions if necessary).\nThe snippet has a \\`context\\` variable in its scope.\nThis \\`context\\` variable holds the current state of the tree in the \\`root\\` property.\nYou may mutate any part of this tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? \" and\" : \"\"}` : \"\"}${hasMaps ? \" maps\" : \"\"} detailed below.\nYou may also set the \\`root\\` property of the context to be an entirely new value as long as it is one of the types allowed at the root of the tree (\\`${rootTypeUnion}\\`).\nYou should also use the \\`context\\` object to create new data to insert into the tree, using the builder functions available on the \\`create\\` property.\nThere are other additional helper functions available on the \\`context\\` object to help you analyze the tree.\nHere is the definition of the \\`Context\\` interface:\n${context}\n${helperMethodExplanation}\n${hasArrays ? arrayEditing : \"\"}${hasMaps ? mapEditing : \"\"}#### Additional Notes\n\nBefore outputting the edit function, you should check that it is valid according to both the application tree's schema and any restrictions of the editing APIs described above.\n\n${reinsertionExplanation}\n\nFinally, double check that the edits would accomplish the user's request (if it is possible).\n\n`;\n\n\tconst prompt = `You are a helpful assistant collaborating with the user on a document. The document state is a JSON tree, and you are able to analyze and edit it.\nThe JSON tree adheres to the following Typescript schema:\n\n\\`\\`\\`typescript\n${typescriptSchemaTypes}\n\\`\\`\\`\n\nIf the user asks you a question about the tree, you should inspect the state of the tree and answer the question.\nWhen answering such a question, DO NOT answer with information that is not part of the document unless requested to do so.\n\n${editToolName === undefined ? \"\" : editing}### Application data\n\n${\n\tdomainHints === undefined\n\t\t? \"\"\n\t\t: `\\nThe application supplied the following additional instructions: ${domainHints}`\n}\nThe current state of \\`context.root\\` (a \\`${field === undefined ? \"undefined\" : getFriendlyName(Tree.schema(field))}\\`) is:\n\n\\`\\`\\`JSON\n${stringified}\n\\`\\`\\``;\n\treturn prompt;\n}\n\n/**\n * Serializes tree data e.g. to include in a prompt or message.\n * @remarks This includes some extra metadata to make it easier to understand the structure of the tree.\n */\nexport function stringifyTree(tree: ReadableField<ImplicitFieldSchema>): string {\n\tconst typeReplacementKey = \"_e944da5a5fd04ea2b8b2eb6109e089ed\";\n\tconst indexReplacementKey = \"_27bb216b474d45e6aaee14d1ec267b96\";\n\tconst mapReplacementKey = \"_a0d98d22a1c644539f07828d3f064d71\";\n\tconst stringified = JSON.stringify(\n\t\ttree,\n\t\t(_, node: unknown) => {\n\t\t\tif (node instanceof TreeNode) {\n\t\t\t\tconst key = Tree.key(node);\n\t\t\t\tconst index = typeof key === \"number\" ? key : undefined;\n\t\t\t\tconst schema = Tree.schema(node);\n\t\t\t\tswitch (schema.kind) {\n\t\t\t\t\tcase NodeKind.Object: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[typeReplacementKey]: getFriendlyName(schema),\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcase NodeKind.Map: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t[mapReplacementKey]: \"\",\n\t\t\t\t\t\t\t...Object.fromEntries(node as TreeMapNode),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn node;\n\t\t},\n\t\t2,\n\t);\n\n\treturn stringified\n\t\t.replace(new RegExp(`\"${typeReplacementKey}\":`, \"g\"), `// Type:`)\n\t\t.replace(new RegExp(`\"${indexReplacementKey}\":`, \"g\"), `// Index:`)\n\t\t.replace(\n\t\t\tnew RegExp(`\"${mapReplacementKey}\": \"\"`, \"g\"),\n\t\t\t`// Note: This is a map that has been serialized to JSON. It is not a key-value object/record but is being printed as such.`,\n\t\t);\n}\n\n/**\n * Retrieves the documentation for the `TreeArrayNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeArrayNode` docs if/when those docs change?\n */\nfunction getTreeArrayNodeDocumentation(typeName: string): string {\n\treturn `/** A special type of array which implements 'readonly T[]' (i.e. it supports all read-only JS array methods) and provides custom array mutation APIs. */\nexport interface ${typeName}<T> extends ReadonlyArray<T> {\n\t/**\n\t * Inserts new item(s) at a specified location.\n\t * @param index - The index at which to insert \\`value\\`.\n\t * @param value - The content to insert.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tinsertAt(index: number, ...value: readonly T[]): void;\n\n\t/**\n\t * Removes the item at the specified location.\n\t * @param index - The index at which to remove the item.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tremoveAt(index: number): void;\n\n\t/**\n\t * Removes all items between the specified indices.\n\t * @param start - The starting index of the range to remove (inclusive). Defaults to the start of the array.\n\t * @param end - The ending index of the range to remove (exclusive). Defaults to \\`array.length\\`.\n\t * @throws Throws if \\`start\\` is not in the range [0, \\`array.length\\`].\n\t * @throws Throws if \\`end\\` is less than \\`start\\`.\n\t * If \\`end\\` is not supplied or is greater than the length of the array, all items after \\`start\\` are removed.\n\t *\n\t * @remarks\n\t * The default values for start and end are computed when this is called,\n\t * and thus the behavior is the same as providing them explicitly, even with respect to merge resolution with concurrent edits.\n\t * For example, two concurrent transactions both emptying the array with \\`node.removeRange()\\` then inserting an item,\n\t * will merge to result in the array having both inserted items.\n\t */\n\tremoveRange(start?: number, end?: number): void;\n\n\t/**\n\t * Moves the specified item to the desired location in the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceIndex - The index of the item to move.\n\t * @param source - The optional source array to move the item out of (defaults to this array).\n\t * @throws Throws if any of the source index is not in the range [0, \\`array.length\\`),\n\t * or if the index is not in the range [0, \\`array.length\\`].\n\t */\n\tmoveToIndex(destinationGap: number, sourceIndex: number, source?: ${typeName}<T>): void;\n\n\t/**\n\t * Moves the specified items to the desired location within the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceStart - The starting index of the range to move (inclusive).\n\t * @param sourceEnd - The ending index of the range to move (exclusive)\n\t * @param source - The optional source array to move items out of (defaults to this array).\n\t * @throws Throws if the types of any of the items being moved are not allowed in the destination array,\n\t * if any of the input indices are not in the range [0, \\`array.length\\`], or if \\`sourceStart\\` is greater than \\`sourceEnd\\`.\n\t */\n\tmoveRangeToIndex(\n\t\tdestinationGap: number,\n\t\tsourceStart: number,\n\t\tsourceEnd: number,\n\t\tsource?: ${typeName}<T>,\n\t): void;\n}`;\n}\n\n/**\n * Retrieves the documentation for the `TreeMapNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeMapNode` docs if/when those docs change?\n */\nfunction getTreeMapNodeDocumentation(typeName: string): string {\n\treturn `/**\n * A map of string keys to tree objects.\n */\nexport interface ${typeName}<T> extends ReadonlyMap<string, T> {\n\t/**\n\t * Adds or updates an entry in the map with a specified \\`key\\` and a \\`value\\`.\n\t *\n\t * @param key - The key of the element to add to the map.\n\t * @param value - The value of the element to add to the map.\n\t *\n\t * @remarks\n\t * Setting the value at a key to \\`undefined\\` is equivalent to calling {@link ${typeName}.delete} with that key.\n\t */\n\tset(key: string, value: T | undefined): void;\n\n\t/**\n\t * Removes the specified element from this map by its \\`key\\`.\n\t *\n\t * @remarks\n\t * Note: unlike JavaScript's Map API, this method does not return a flag indicating whether or not the value was\n\t * deleted.\n\t *\n\t * @param key - The key of the element to remove from the map.\n\t */\n\tdelete(key: string): void;\n\n\t/**\n\t * Returns an iterable of keys in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the keys returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tkeys(): IterableIterator<string>;\n\n\t/**\n\t * Returns an iterable of values in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the values returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tvalues(): IterableIterator<T>;\n\n\t/**\n\t * Returns an iterable of key/value pairs for every entry in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the entries returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tentries(): IterableIterator<[string, T]>;\n\n\t/**\n\t * Executes the provided function once per each key/value pair in this map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order in which the function is called with respect to the map's entries.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tforEach(\n\t\tcallbackfn: (\n\t\t\tvalue: T,\n\t\t\tkey: string,\n\t\t\tmap: ReadonlyMap<string, T>,\n\t\t) => void,\n\t\tthisArg?: any,\n\t): void;\n}`;\n}\n"]}
1
+ {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,qCAAqC,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGhE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAGlF,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAErE;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAEnD;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,IAIzB;IACA,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAClC,MAAM,kBAAkB,GAAG,WAAW,CAAC;IACvC,MAAM,gBAAgB,GAAG,SAAS,CAAC;IACnC,6IAA6I;IAC7I,MAAM,SAAS,GAAG,CAAC,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,cAAc,CAAC,CAAC;IACnE,MAAM,aAAa,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CA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*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { oob } from \"@fluidframework/core-utils/internal\";\nimport { NodeKind, Tree, TreeNode } from \"@fluidframework/tree\";\nimport type { ImplicitFieldSchema, TreeMapNode } from \"@fluidframework/tree\";\nimport type { ReadableField } from \"@fluidframework/tree/alpha\";\nimport { getSimpleSchema } from \"@fluidframework/tree/alpha\";\nimport { normalizeFieldSchema, ValueSchema } from \"@fluidframework/tree/internal\";\n\nimport type { Subtree } from \"./subtree.js\";\nimport { generateEditTypesForPrompt } from \"./typeGeneration.js\";\nimport { getFriendlyName, communize, findSchemas } from \"./utils.js\";\n\n/**\n * The type name used for handles in generated TypeScript.\n */\nexport const fluidHandleTypeName = \"_OpaqueHandle\";\n\n/**\n * Produces a \"system\" prompt for the tree agent, based on the provided subtree.\n */\nexport function getPrompt(args: {\n\tsubtree: Pick<Subtree<ImplicitFieldSchema>, \"schema\" | \"field\">;\n\teditToolName: string | undefined;\n\tdomainHints?: string;\n}): string {\n\tconst { subtree, editToolName, domainHints } = args;\n\tconst { field, schema } = subtree;\n\tconst arrayInterfaceName = \"TreeArray\";\n\tconst mapInterfaceName = \"TreeMap\";\n\t// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.\n\tconst rootTypes = [...normalizeFieldSchema(schema).allowedTypeSet];\n\tconst rootTypeUnion = `${rootTypes.map((t) => getFriendlyName(t)).join(\" | \")}`;\n\tlet nodeTypeUnion: string | undefined;\n\tlet hasArrays = false;\n\tlet hasMaps = false;\n\tlet hasFluidHandles = false;\n\tlet exampleObjectName: string | undefined;\n\tfor (const s of findSchemas(schema)) {\n\t\tif (s.kind !== NodeKind.Leaf) {\n\t\t\tnodeTypeUnion =\n\t\t\t\tnodeTypeUnion === undefined\n\t\t\t\t\t? getFriendlyName(s)\n\t\t\t\t\t: `${nodeTypeUnion} | ${getFriendlyName(s)}`;\n\t\t}\n\n\t\tswitch (s.kind) {\n\t\t\tcase NodeKind.Array: {\n\t\t\t\thasArrays = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\thasMaps = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Object: {\n\t\t\t\texampleObjectName ??= getFriendlyName(s);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase NodeKind.Leaf: {\n\t\t\t\thasFluidHandles ||= s.info === ValueSchema.FluidHandle;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tconst stringified = stringifyTree(field);\n\tconst { schemaText: typescriptSchemaTypes, hasHelperMethods } = generateEditTypesForPrompt(\n\t\tschema,\n\t\tgetSimpleSchema(schema),\n\t);\n\tconst fluidHandleType = hasFluidHandles\n\t\t? `/**\n * Opaque handle type representing a reference to a Fluid object.\n * This type should not be constructed by generated code.\n */\ntype ${fluidHandleTypeName} = unknown;\n\n`\n\t\t: \"\";\n\tconst exampleTypeName =\n\t\tnodeTypeUnion === undefined\n\t\t\t? undefined\n\t\t\t: nodeTypeUnion\n\t\t\t\t\t.split(\"|\")\n\t\t\t\t\t.map((part) => part.trim())\n\t\t\t\t\t.find((part) => part.length > 0);\n\n\tconst createDocs =\n\t\texampleObjectName === undefined\n\t\t\t? \"\"\n\t\t\t: `\\n\t/**\n\t * A collection of builder functions for creating new tree nodes.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to create a new node of that type.\n\t * Always use these builder functions when creating new nodes rather than plain JavaScript objects.\n\t *\n\t * For example:\n\t *\n\t * \\`\\`\\`javascript\n\t * // This creates a new ${exampleObjectName} object:\n\t * const ${communize(exampleObjectName)} = context.create.${exampleObjectName}({ ...properties });\n\t * // Don't do this:\n\t * // const ${communize(exampleObjectName)} = { ...properties };\n\t * \\`\\`\\`\n\t */\n\tcreate: Record<string, <T extends TreeData>(input: T) => T>;\\n`;\n\n\tconst isDocs =\n\t\texampleTypeName === undefined\n\t\t\t? \"\"\n\t\t\t: `\\n\t/**\n\t * A collection of type-guard functions for data in the tree.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to check if a node is of that specific type.\n\t * This is useful when working with nodes that could be one of multiple types.\n\t *\n\t * ${`Example: Check if a node is a ${exampleTypeName} with \\`if (context.is.${exampleTypeName}(node)) {}\\``}\n\t */\n\tis: Record<string, <T extends TreeData>(data: unknown) => data is T>;\n\n\t/**\n\t * Checks if the provided data is an array.\n\t * @remarks\n\t * DO NOT use \\`Array.isArray\\` to check if tree data is an array - use this function instead.\n\t *\n\t * This function will also work for native JavaScript arrays.\n\t *\n\t * ${`Example: \\`if (context.isArray(node)) {}\\``}\n\t */\n\tisArray(data: any): boolean;\n\n\t/**\n\t * Checks if the provided data is a map.\n\t * @remarks\n\t * DO NOT use \\`instanceof Map\\` to check if tree data is a map - use this function instead.\n\t *\n\t * This function will also work for native JavaScript Map instances.\n\t *\n\t * ${`Example: \\`if (context.isMap(node)) {}\\``}\n\t */\n\tisMap(data: any): boolean;\\n`;\n\n\tconst context = `\\`\\`\\`typescript\n\t${nodeTypeUnion === undefined ? \"\" : `type TreeData = ${nodeTypeUnion};\\n\\n`}\t/**\n\t * An object available to generated code which provides read and write access to the tree as well as utilities for creating and inspecting data in the tree.\n\t * @remarks This object is available as a variable named \\`context\\` in the scope of the generated JavaScript snippet.\n\t */\n\tinterface Context<TSchema extends ImplicitFieldSchema> {\n\t/**\n\t * The root of the tree that can be read or mutated.\n\t * @remarks\n\t * You can read properties and navigate through the tree starting from this root.\n\t * You can also assign a new value to this property to replace the entire tree, as long as the new value is one of the types allowed at the root.\n\t *\n\t * Example: Read the current root with \\`const currentRoot = context.root;\\`\n\t *${rootTypes.length > 0 ? ` Example: Replace the entire root with \\`context.root = context.create.${getFriendlyName(rootTypes[0] ?? oob())}({ });\\`\\n\t *` : \"\"}/\n\troot: ReadableField<TSchema>;\n\t${createDocs}\n\t${isDocs}\n\t/**\n\t * Returns the parent object/array/map of the given object/array/map, if there is one.\n\t * @returns The parent node, or \\`undefined\\` if the node is the root or is not in the tree.\n\t * @remarks\n\t * Example: Get the parent with \\`const parent = context.parent(child);\\`\n\t */\n\tparent(child: TreeData): TreeData | undefined;\n\n\t/**\n\t * Returns the property key or index of the given object/array/map within its parent.\n\t * @returns A string key if the child is in an object or map, or a numeric index if the child is in an array.\n\t *\n\t * Example: \\`const key = context.key(child);\\`\n\t */\n\tkey(child: TreeData): string | number;\n}\n\\`\\`\\``;\n\n\tconst helperMethodExplanation = hasHelperMethods\n\t\t? `Manipulating the data using the APIs described below is allowed, but when possible ALWAYS prefer to use any application helper methods exposed on the schema TypeScript types if the goal can be accomplished that way.\nIt will often not be possible to fully accomplish the goal using those helpers. When this is the case, mutate the objects as normal, taking into account the following guidance.`\n\t\t: \"\";\n\n\tconst reinsertionExplanation = `Once non-primitive data has been removed from the tree (e.g. replaced via assignment, or removed from an array), that data cannot be re-inserted into the tree.\nInstead, it must be deep cloned and recreated.\n${\n\texampleObjectName === undefined\n\t\t? \"\"\n\t\t: `For example:\n\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst ${communize(exampleObjectName)} = parent.${communize(exampleObjectName)};\nparent.${communize(exampleObjectName)} = undefined;\n// \\`${communize(exampleObjectName)}\\` cannot be directly re-inserted into the tree - this will throw an error:\n// parent.${communize(exampleObjectName)} = ${communize(exampleObjectName)}; // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nparent.${communize(exampleObjectName)} = context.create.${exampleObjectName}({ /*... deep clone all properties from \\`${communize(exampleObjectName)}\\` */ });\n\\`\\`\\`${\n\t\t\t\thasArrays\n\t\t\t\t\t? `\\n\\nThe same applies when using arrays:\\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst item = arrayOf${exampleObjectName}[0];\narrayOf${exampleObjectName}.removeAt(0);\n// \\`item\\` cannot be directly re-inserted into the tree - this will throw an error:\narrayOf${exampleObjectName}.insertAt(0, item); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\narrayOf${exampleObjectName}.insertAt(0, context.create.${exampleObjectName}({ /*... deep clone all properties from \\`item\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}${\n\t\t\t\thasMaps\n\t\t\t\t\t? `\\n\\nThe same applies when using maps:\n\\`\\`\\`javascript\n// Data is removed from the tree:\nconst value = mapOf${exampleObjectName}.get(\"someKey\");\nmapOf${exampleObjectName}.delete(\"someKey\");\n// \\`value\\` cannot be directly re-inserted into the tree - this will throw an error:\nmapOf${exampleObjectName}.set(\"someKey\", value); // ❌ A node may not be inserted into the tree more than once\n// Instead, it must be deep cloned and recreated before insertion:\nmapOf${exampleObjectName}.set(\"someKey\", context.create.${exampleObjectName}({ /*... deep clone all properties from \\`value\\` */ }));\n\\`\\`\\``\n\t\t\t\t\t: \"\"\n\t\t\t}`\n}`;\n\n\tconst arrayEditing = `#### Editing Arrays\n\nThe arrays in the tree are somewhat different than normal JavaScript \\`Array\\`s.\nRead-only operations are generally the same - you can create them, read via index, and call non-mutating methods like \\`concat\\`, \\`map\\`, \\`filter\\`, \\`find\\`, \\`forEach\\`, \\`indexOf\\`, \\`slice\\`, \\`join\\`, etc.\nHowever, write operations (e.g. index assignment, \\`push\\`, \\`pop\\`, \\`splice\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the array:\n\n\\`\\`\\`typescript\n${getTreeArrayNodeDocumentation(arrayInterfaceName)}\n\\`\\`\\`\n\nWhen possible, ensure that the edits preserve the identity of objects already in the tree.\nFor example, prefer \\`array.moveToIndex\\` over \\`array.removeAt\\` + \\`array.insertAt\\` and prefer \\`array.moveRangeToIndex\\` over \\`array.removeRange\\` + \\`array.insertAt\\`.\n\n`;\n\n\tconst mapEditing = `#### Editing Maps\n\nThe maps in the tree are somewhat different than normal JavaScript \\`Map\\`s.\nMap keys are always strings.\nRead-only operations are generally the same - you can create them, read via \\`get\\`, and call non-mutating methods like \\`has\\`, \\`forEach\\`, \\`entries\\`, \\`keys\\`, \\`values\\`, etc. (note the subtle differences around return values and iteration order).\nHowever, write operations (e.g. \\`set\\`, \\`delete\\`, etc.) are not supported.\nInstead, you must use the methods on the following interface to mutate the map:\n\n\\`\\`\\`typescript\n${getTreeMapNodeDocumentation(mapInterfaceName)}\n\\`\\`\\`\n\n`;\n\n\tconst editing = `If the user asks you to edit the tree, you should author a snippet of JavaScript code to accomplish the user-specified goal, following the instructions for editing detailed below.\nYou must use the \"${editToolName}\" tool to run the generated code.\nAfter editing the tree, review the latest state of the tree to see if it satisfies the user's request.\nIf it does not, or if you receive an error, you may try again with a different approach.\nOnce the tree is in the desired state, you should inform the user that the request has been completed.\n\n### Editing\n\nIf the user asks you to edit the document, you will write a snippet of JavaScript code that mutates the data in-place to achieve the user's goal.\nThe snippet may be synchronous or asynchronous (i.e. it may \\`await\\` functions if necessary).\nThe snippet has a \\`context\\` variable in its scope.\nThis \\`context\\` variable holds the current state of the tree in the \\`root\\` property.\nYou may mutate any part of this tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? \" and\" : \"\"}` : \"\"}${hasMaps ? \" maps\" : \"\"} detailed below.\nYou may also set the \\`root\\` property of the context to be an entirely new value as long as it is one of the types allowed at the root of the tree (\\`${rootTypeUnion}\\`).\nYou should also use the \\`context\\` object to create new data to insert into the tree, using the builder functions available on the \\`create\\` property.\nThere are other additional helper functions available on the \\`context\\` object to help you analyze the tree.\nHere is the definition of the \\`Context\\` interface:\n${context}\n${helperMethodExplanation}\n${hasArrays ? arrayEditing : \"\"}${hasMaps ? mapEditing : \"\"}#### Additional Notes\n\nBefore outputting the edit function, you should check that it is valid according to both the application tree's schema and any restrictions of the editing APIs described above.\n\n${reinsertionExplanation}\n\nFinally, double check that the edits would accomplish the user's request (if it is possible).\n\n`;\n\n\tconst prompt = `You are a helpful assistant collaborating with the user on a document. The document state is a JSON tree, and you are able to analyze and edit it.\nThe JSON tree adheres to the following Typescript schema:\n\n\\`\\`\\`typescript\n${fluidHandleType}${typescriptSchemaTypes}\n\\`\\`\\`\n\nIf the user asks you a question about the tree, you should inspect the state of the tree and answer the question.\nWhen answering such a question, DO NOT answer with information that is not part of the document unless requested to do so.\n\n${editToolName === undefined ? \"\" : editing}### Application data\n\n${\n\tdomainHints === undefined\n\t\t? \"\"\n\t\t: `\\nThe application supplied the following additional instructions: ${domainHints}`\n}\nThe current state of \\`context.root\\` (a \\`${field === undefined ? \"undefined\" : getFriendlyName(Tree.schema(field))}\\`) is:\n\n\\`\\`\\`JSON\n${stringified}\n\\`\\`\\``;\n\treturn prompt;\n}\n\n/**\n * Serializes tree data e.g. to include in a prompt or message.\n * @remarks This includes some extra metadata to make it easier to understand the structure of the tree.\n */\nexport function stringifyTree(tree: ReadableField<ImplicitFieldSchema>): string {\n\tconst typeReplacementKey = \"_e944da5a5fd04ea2b8b2eb6109e089ed\";\n\tconst indexReplacementKey = \"_27bb216b474d45e6aaee14d1ec267b96\";\n\tconst mapReplacementKey = \"_a0d98d22a1c644539f07828d3f064d71\";\n\tconst stringified = JSON.stringify(\n\t\ttree,\n\t\t(_, node: unknown) => {\n\t\t\tif (node instanceof TreeNode) {\n\t\t\t\tconst key = Tree.key(node);\n\t\t\t\tconst index = typeof key === \"number\" ? key : undefined;\n\t\t\t\tconst schema = Tree.schema(node);\n\t\t\t\tswitch (schema.kind) {\n\t\t\t\t\tcase NodeKind.Object: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[typeReplacementKey]: getFriendlyName(schema),\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tcase NodeKind.Map: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t[mapReplacementKey]: \"\",\n\t\t\t\t\t\t\t...Object.fromEntries(node as TreeMapNode),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t[indexReplacementKey]: index,\n\t\t\t\t\t\t\t...node,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn node;\n\t\t},\n\t\t2,\n\t);\n\n\treturn stringified\n\t\t.replace(new RegExp(`\"${typeReplacementKey}\":`, \"g\"), `// Type:`)\n\t\t.replace(new RegExp(`\"${indexReplacementKey}\":`, \"g\"), `// Index:`)\n\t\t.replace(\n\t\t\tnew RegExp(`\"${mapReplacementKey}\": \"\"`, \"g\"),\n\t\t\t`// Note: This is a map that has been serialized to JSON. It is not a key-value object/record but is being printed as such.`,\n\t\t);\n}\n\n/**\n * Retrieves the documentation for the `TreeArrayNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeArrayNode` docs if/when those docs change?\n */\nfunction getTreeArrayNodeDocumentation(typeName: string): string {\n\treturn `/** A special type of array which implements 'readonly T[]' (i.e. it supports all read-only JS array methods) and provides custom array mutation APIs. */\nexport interface ${typeName}<T> extends ReadonlyArray<T> {\n\t/**\n\t * Inserts new item(s) at a specified location.\n\t * @param index - The index at which to insert \\`value\\`.\n\t * @param value - The content to insert.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tinsertAt(index: number, ...value: readonly T[]): void;\n\n\t/**\n\t * Removes the item at the specified location.\n\t * @param index - The index at which to remove the item.\n\t * @throws Throws if \\`index\\` is not in the range [0, \\`array.length\\`).\n\t */\n\tremoveAt(index: number): void;\n\n\t/**\n\t * Removes all items between the specified indices.\n\t * @param start - The starting index of the range to remove (inclusive). Defaults to the start of the array.\n\t * @param end - The ending index of the range to remove (exclusive). Defaults to \\`array.length\\`.\n\t * @throws Throws if \\`start\\` is not in the range [0, \\`array.length\\`].\n\t * @throws Throws if \\`end\\` is less than \\`start\\`.\n\t * If \\`end\\` is not supplied or is greater than the length of the array, all items after \\`start\\` are removed.\n\t *\n\t * @remarks\n\t * The default values for start and end are computed when this is called,\n\t * and thus the behavior is the same as providing them explicitly, even with respect to merge resolution with concurrent edits.\n\t * For example, two concurrent transactions both emptying the array with \\`node.removeRange()\\` then inserting an item,\n\t * will merge to result in the array having both inserted items.\n\t */\n\tremoveRange(start?: number, end?: number): void;\n\n\t/**\n\t * Moves the specified item to the desired location in the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceIndex - The index of the item to move.\n\t * @param source - The optional source array to move the item out of (defaults to this array).\n\t * @throws Throws if any of the source index is not in the range [0, \\`array.length\\`),\n\t * or if the index is not in the range [0, \\`array.length\\`].\n\t */\n\tmoveToIndex(destinationGap: number, sourceIndex: number, source?: ${typeName}<T>): void;\n\n\t/**\n\t * Moves the specified items to the desired location within the array.\n\t *\n\t * WARNING - This API is easily misused.\n\t * Please read the documentation for the \\`destinationGap\\` parameter carefully.\n\t *\n\t * @param destinationGap - The location *between* existing items that the moved item should be moved to.\n\t *\n\t * WARNING - \\`destinationGap\\` describes a location between existing items *prior to applying the move operation*.\n\t *\n\t * For example, if the array contains items \\`[A, B, C]\\` before the move, the \\`destinationGap\\` must be one of the following:\n\t *\n\t * - \\`0\\` (between the start of the array and \\`A\\`'s original position)\n\t * - \\`1\\` (between \\`A\\`'s original position and \\`B\\`'s original position)\n\t * - \\`2\\` (between \\`B\\`'s original position and \\`C\\`'s original position)\n\t * - \\`3\\` (between \\`C\\`'s original position and the end of the array)\n\t *\n\t * So moving \\`A\\` between \\`B\\` and \\`C\\` would require \\`destinationGap\\` to be \\`2\\`.\n\t *\n\t * This interpretation of \\`destinationGap\\` makes it easy to specify the desired destination relative to a sibling item that is not being moved,\n\t * or relative to the start or end of the array:\n\t *\n\t * - Move to the start of the array: \\`array.moveToIndex(0, ...)\\` (see also \\`moveToStart\\`)\n\t * - Move to before some item X: \\`array.moveToIndex(indexOfX, ...)\\`\n\t * - Move to after some item X: \\`array.moveToIndex(indexOfX + 1\\`, ...)\n\t * - Move to the end of the array: \\`array.moveToIndex(array.length, ...)\\` (see also \\`moveToEnd\\`)\n\t *\n\t * This interpretation of \\`destinationGap\\` does however make it less obvious how to move an item relative to its current position:\n\t *\n\t * - Move item B before its predecessor: \\`array.moveToIndex(indexOfB - 1, ...)\\`\n\t * - Move item B after its successor: \\`array.moveToIndex(indexOfB + 2, ...)\\`\n\t *\n\t * Notice the asymmetry between \\`-1\\` and \\`+2\\` in the above examples.\n\t * In such scenarios, it can often be easier to approach such edits by swapping adjacent items:\n\t * If items A and B are adjacent, such that A precedes B,\n\t * then they can be swapped with \\`array.moveToIndex(indexOfA, indexOfB)\\`.\n\t *\n\t * @param sourceStart - The starting index of the range to move (inclusive).\n\t * @param sourceEnd - The ending index of the range to move (exclusive)\n\t * @param source - The optional source array to move items out of (defaults to this array).\n\t * @throws Throws if the types of any of the items being moved are not allowed in the destination array,\n\t * if any of the input indices are not in the range [0, \\`array.length\\`], or if \\`sourceStart\\` is greater than \\`sourceEnd\\`.\n\t */\n\tmoveRangeToIndex(\n\t\tdestinationGap: number,\n\t\tsourceStart: number,\n\t\tsourceEnd: number,\n\t\tsource?: ${typeName}<T>,\n\t): void;\n}`;\n}\n\n/**\n * Retrieves the documentation for the `TreeMapNode` interface to feed to the LLM.\n * @remarks The documentation has been simplified in various ways to make it easier for the LLM to understand.\n * @privateRemarks TODO: How do we keep this in sync with the actual `TreeMapNode` docs if/when those docs change?\n */\nfunction getTreeMapNodeDocumentation(typeName: string): string {\n\treturn `/**\n * A map of string keys to tree objects.\n */\nexport interface ${typeName}<T> extends ReadonlyMap<string, T> {\n\t/**\n\t * Adds or updates an entry in the map with a specified \\`key\\` and a \\`value\\`.\n\t *\n\t * @param key - The key of the element to add to the map.\n\t * @param value - The value of the element to add to the map.\n\t *\n\t * @remarks\n\t * Setting the value at a key to \\`undefined\\` is equivalent to calling {@link ${typeName}.delete} with that key.\n\t */\n\tset(key: string, value: T | undefined): void;\n\n\t/**\n\t * Removes the specified element from this map by its \\`key\\`.\n\t *\n\t * @remarks\n\t * Note: unlike JavaScript's Map API, this method does not return a flag indicating whether or not the value was\n\t * deleted.\n\t *\n\t * @param key - The key of the element to remove from the map.\n\t */\n\tdelete(key: string): void;\n\n\t/**\n\t * Returns an iterable of keys in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the keys returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tkeys(): IterableIterator<string>;\n\n\t/**\n\t * Returns an iterable of values in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the values returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tvalues(): IterableIterator<T>;\n\n\t/**\n\t * Returns an iterable of key/value pairs for every entry in the map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order of the entries returned.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tentries(): IterableIterator<[string, T]>;\n\n\t/**\n\t * Executes the provided function once per each key/value pair in this map.\n\t *\n\t * @remarks\n\t * Note: no guarantees are made regarding the order in which the function is called with respect to the map's entries.\n\t * If your usage scenario depends on consistent ordering, you will need to sort these yourself.\n\t */\n\tforEach(\n\t\tcallbackfn: (\n\t\t\tvalue: T,\n\t\t\tkey: string,\n\t\t\tmap: ReadonlyMap<string, T>,\n\t\t) => void,\n\t\tthisArg?: any,\n\t): void;\n}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"renderSchemaTypeScript.d.ts","sourceRoot":"","sources":["../src/renderSchemaTypeScript.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAIX,gBAAgB,EAGhB,MAAM,+BAA+B,CAAC;AAGvC,OAAO,KAAK,EAAE,cAAc,EAAmB,MAAM,oBAAoB,CAAC;AAuC1E;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,OAAO,CAAC;CAC1B;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACrC,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAClD,eAAe,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,GAC1C,4BAA4B,CAoV9B"}
1
+ {"version":3,"file":"renderSchemaTypeScript.d.ts","sourceRoot":"","sources":["../src/renderSchemaTypeScript.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAIX,gBAAgB,EAGhB,MAAM,+BAA+B,CAAC;AAGvC,OAAO,KAAK,EAAE,cAAc,EAAmB,MAAM,oBAAoB,CAAC;AAwC1E;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,OAAO,CAAC;CAC1B;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACrC,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAClD,eAAe,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,GAC1C,4BAA4B,CAoV9B"}
@@ -6,6 +6,7 @@ import { UsageError } from "@fluidframework/telemetry-utils/internal";
6
6
  import { FieldKind, NodeKind, ValueSchema } from "@fluidframework/tree/internal";
7
7
  import { z } from "zod";
8
8
  import { getExposedMethods } from "./methodBinding.js";
9
+ import { fluidHandleTypeName } from "./prompt.js";
9
10
  import { getExposedProperties } from "./propertyBinding.js";
10
11
  import { instanceOfsTypeFactory, renderTypeFactoryTypeScript, } from "./renderTypeFactoryTypeScript.js";
11
12
  import { instanceOfs, renderZodTypeScript } from "./renderZodTypeScript.js";
@@ -361,8 +362,11 @@ function renderLeaf(leafKind) {
361
362
  case ValueSchema.Null: {
362
363
  return "null";
363
364
  }
365
+ case ValueSchema.FluidHandle: {
366
+ return fluidHandleTypeName;
367
+ }
364
368
  default: {
365
- throw new Error(`Unsupported leaf kind ${NodeKind[leafKind]}.`);
369
+ throw new Error(`Unsupported leaf kind.`);
366
370
  }
367
371
  }
368
372
  }
@@ -1 +1 @@
1
- {"version":3,"file":"renderSchemaType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AAE,CAAC;QACnC,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,EAAkB,CAAC;QAC5C,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAC7C,CAAC;AAED;;GAEG;AACH,SAAS,uBAAuB,CAC/B,UAAkB,EAClB,UAA+B,EAC/B,OAAwC,EACxC,UAAuC;IAEvC,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,UAAU,CACnB,UAAU,IAAI,oDAAoD,UAAU,EAAE,CAC9E,CAAC;QACH,CAAC;IACF,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5C,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,UAAU,CACnB,YAAY,IAAI,oDAAoD,UAAU,EAAE,CAChF,CAAC;QACH,CAAC;IACF,CAAC;AACF,CAAC;AAED;;GAEG;AACH,SAAS,UAAU,CAAC,IAAoC,EAAE,cAAsB,CAAC;IAChF,OAAO,iBAAiB,CAAC,IAAI,CAAC;QAC7B,CAAC,CAAC,2BAA2B,CAAC,IAAI,EAAE,eAAe,EAAE,sBAAsB,EAAE,WAAW,CAAC;QACzF,CAAC,CAAC,mBAAmB,CAAC,IAAI,EAAE,eAAe,EAAE,WAAW,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { UsageError } from \"@fluidframework/telemetry-utils/internal\";\nimport { FieldKind, NodeKind, ValueSchema } from \"@fluidframework/tree/internal\";\nimport type {\n\tSimpleArrayNodeSchema,\n\tSimpleFieldSchema,\n\tSimpleMapNodeSchema,\n\tSimpleNodeSchema,\n\tSimpleObjectNodeSchema,\n\tSimpleRecordNodeSchema,\n} from \"@fluidframework/tree/internal\";\nimport { z } from \"zod\";\n\nimport type { BindableSchema, FunctionWrapper } from \"./methodBinding.js\";\nimport { getExposedMethods } from \"./methodBinding.js\";\nimport { getExposedProperties, type PropertyDef } from \"./propertyBinding.js\";\nimport {\n\tinstanceOfsTypeFactory,\n\trenderTypeFactoryTypeScript,\n} from \"./renderTypeFactoryTypeScript.js\";\nimport { instanceOfs, renderZodTypeScript } from \"./renderZodTypeScript.js\";\nimport type { TypeFactoryOptional, TypeFactoryType } from \"./treeAgentTypes.js\";\nimport { isTypeFactoryType } from \"./treeAgentTypes.js\";\nimport { getFriendlyName, isNamedSchema, llmDefault, unqualifySchema } from \"./utils.js\";\n\ninterface BoundMembers {\n\tmethods: Record<string, FunctionWrapper>;\n\tproperties: Record<string, PropertyDef>;\n}\n\ninterface RenderResult {\n\tdeclaration: string;\n\tdescription?: string;\n}\n\ninterface BindingIntersectionResult {\n\thasMethods: boolean;\n\thasProperties: boolean;\n\tsuffix: string;\n}\n\ninterface TypeExpression {\n\tprecedence: TypePrecedence;\n\ttext: string;\n}\n\nconst enum TypePrecedence {\n\tUnion = 0,\n\tIntersection = 1,\n\tObject = 2,\n}\n\n/**\n * Output of rendering schema metadata into TypeScript declaration text.\n */\nexport interface SchemaTypeScriptRenderResult {\n\tschemaText: string;\n\thasHelperMethods: boolean;\n}\n\n/**\n * Converts schema metadata into TypeScript declarations suitable for prompt inclusion.\n */\nexport function renderSchemaTypeScript(\n\tdefinitions: ReadonlyMap<string, SimpleNodeSchema>,\n\tbindableSchemas: Map<string, BindableSchema>,\n): SchemaTypeScriptRenderResult {\n\tconst friendlyNames = new Map<string, string>();\n\tlet hasHelperMethods = false;\n\n\tfor (const identifier of definitions.keys()) {\n\t\tif (isNamedSchema(identifier)) {\n\t\t\tfriendlyNames.set(identifier, unqualifySchema(identifier));\n\t\t}\n\t}\n\n\tconst declarations: string[] = [];\n\tfor (const [identifier, schema] of definitions) {\n\t\tif (!isNamedSchema(identifier)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst friendlyName = friendlyNames.get(identifier) ?? unqualifySchema(identifier);\n\t\tconst rendered = renderNamedSchema(identifier, friendlyName, schema);\n\t\tif (rendered === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst lines: string[] = [];\n\t\tif (rendered.description !== undefined && rendered.description !== \"\") {\n\t\t\tfor (const comment of rendered.description.split(\"\\n\")) {\n\t\t\t\tlines.push(`// ${comment}`);\n\t\t\t}\n\t\t}\n\t\tlines.push(rendered.declaration);\n\t\tdeclarations.push(lines.join(\"\\n\"));\n\t}\n\n\tconst schemaText = declarations.join(\"\\n\\n\");\n\treturn {\n\t\tschemaText: schemaText === \"\" ? \"\" : `${schemaText}\\n`,\n\t\thasHelperMethods,\n\t};\n\n\tfunction renderNamedSchema(\n\t\tidentifier: string,\n\t\tfriendlyName: string,\n\t\tschema: SimpleNodeSchema,\n\t): RenderResult | undefined {\n\t\tswitch (schema.kind) {\n\t\t\tcase NodeKind.Object: {\n\t\t\t\treturn renderObjectDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Array: {\n\t\t\t\treturn renderArrayDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\treturn renderMapDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Record: {\n\t\t\t\treturn renderRecordDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Leaf: {\n\t\t\t\treturn {\n\t\t\t\t\tdeclaration: `type ${friendlyName} = ${renderLeaf(schema.leafKind)};`,\n\t\t\t\t\tdescription: schema.metadata?.description,\n\t\t\t\t};\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction renderObjectDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleObjectNodeSchema,\n\t): RenderResult {\n\t\tconst fieldLines: string[] = [];\n\t\tconst fieldNames = new Set<string>();\n\n\t\tfor (const [fieldName, fieldSchema] of schema.fields) {\n\t\t\tfieldNames.add(fieldName);\n\t\t\tfieldLines.push(...renderFieldLine(fieldName, fieldSchema));\n\t\t}\n\n\t\tconst { methods, properties } = getBoundMembers(definition);\n\t\tensureNoMemberConflicts(definition, fieldNames, methods, properties);\n\t\tfieldLines.push(...renderPropertyLines(properties));\n\t\tfieldLines.push(...renderMethodLines(methods));\n\n\t\tconst members = fieldLines.map((line) => ` ${line}`).join(\"\\n\");\n\t\tconst body = members === \"\" ? \"\" : `\\n${members}`;\n\t\treturn {\n\t\t\tdeclaration: `interface ${name} {${body}\\n}`,\n\t\t\tdescription: schema.metadata?.description,\n\t\t};\n\t}\n\n\tfunction renderArrayDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleArrayNodeSchema,\n\t): RenderResult {\n\t\tconst elementTypes = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\tconst base = `${formatExpression(elementTypes)}[]`;\n\t\tconst binding = renderBindingIntersection(definition);\n\t\treturn {\n\t\t\tdeclaration: `type ${name} = ${base}${binding.suffix};`,\n\t\t\tdescription: describeBinding(schema.metadata?.description, \"array\", binding),\n\t\t};\n\t}\n\n\tfunction renderMapDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleMapNodeSchema,\n\t): RenderResult {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\tconst base = `Map<string, ${valueType.text}>`;\n\t\tconst binding = renderBindingIntersection(definition);\n\t\treturn {\n\t\t\tdeclaration: `type ${name} = ${base}${binding.suffix};`,\n\t\t\tdescription: describeBinding(schema.metadata?.description, \"map\", binding),\n\t\t};\n\t}\n\n\tfunction renderRecordDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleRecordNodeSchema,\n\t): RenderResult {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\tconst base = `Record<string, ${valueType.text}>`;\n\t\tconst binding = renderBindingIntersection(definition);\n\t\treturn {\n\t\t\tdeclaration: `type ${name} = ${base}${binding.suffix};`,\n\t\t\tdescription: describeBinding(schema.metadata?.description, \"record\", binding),\n\t\t};\n\t}\n\n\tfunction renderFieldLine(name: string, field: SimpleFieldSchema): string[] {\n\t\tconst { comment, optional, type } = describeField(field);\n\t\tconst lines: string[] = [];\n\t\tif (comment !== undefined && comment !== \"\") {\n\t\t\tfor (const note of comment.split(\"\\n\")) {\n\t\t\t\tlines.push(`// ${note}`);\n\t\t\t}\n\t\t}\n\t\tlines.push(`${name}${optional ? \"?\" : \"\"}: ${type};`);\n\t\treturn lines;\n\t}\n\n\tfunction describeField(field: SimpleFieldSchema): {\n\t\tcomment?: string;\n\t\toptional: boolean;\n\t\ttype: string;\n\t} {\n\t\tconst allowedTypes = renderAllowedTypes(field.simpleAllowedTypes.keys());\n\t\tconst type = formatExpression(allowedTypes);\n\t\tconst optional = field.kind !== FieldKind.Required;\n\t\tconst customMetadata = field.metadata.custom as\n\t\t\t| Record<string | symbol, unknown>\n\t\t\t| undefined;\n\t\tconst getDefault = customMetadata?.[llmDefault];\n\n\t\tif (getDefault !== undefined) {\n\t\t\tif (typeof getDefault !== \"function\") {\n\t\t\t\tthrow new UsageError(\n\t\t\t\t\t`Expected value of ${llmDefault.description} property to be a function, but got ${typeof getDefault}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (field.kind !== FieldKind.Optional) {\n\t\t\t\tthrow new UsageError(\n\t\t\t\t\t`The ${llmDefault.description} property is only permitted on optional fields.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toptional,\n\t\t\t\ttype,\n\t\t\t\tcomment:\n\t\t\t\t\t\"Do not populate this field. It will be automatically supplied by the system after insertion.\",\n\t\t\t};\n\t\t}\n\n\t\tif (field.kind === FieldKind.Identifier) {\n\t\t\treturn {\n\t\t\t\toptional: true,\n\t\t\t\ttype,\n\t\t\t\tcomment:\n\t\t\t\t\t\"This is an ID automatically generated by the system. Do not supply it when constructing a new object.\",\n\t\t\t};\n\t\t}\n\n\t\tconst description = field.metadata?.description;\n\t\treturn {\n\t\t\toptional,\n\t\t\ttype,\n\t\t\tcomment: description === undefined || description === \"\" ? undefined : description,\n\t\t};\n\t}\n\n\tfunction renderBindingIntersection(definition: string): BindingIntersectionResult {\n\t\tconst { methods, properties } = getBoundMembers(definition);\n\t\tconst propertyLines = renderPropertyLines(properties);\n\t\tconst methodLines = renderMethodLines(methods);\n\n\t\tif (propertyLines.length === 0 && methodLines.length === 0) {\n\t\t\treturn { hasMethods: false, hasProperties: false, suffix: \"\" };\n\t\t}\n\n\t\tconst lines = [...propertyLines, ...methodLines].map((line) => ` ${line}`);\n\t\tconst suffix = ` & {\\n${lines.join(\"\\n\")}\\n}`;\n\t\treturn {\n\t\t\thasMethods: methodLines.length > 0,\n\t\t\thasProperties: propertyLines.length > 0,\n\t\t\tsuffix,\n\t\t};\n\t}\n\n\tfunction renderMethodLines(methods: Record<string, FunctionWrapper>): string[] {\n\t\tconst lines: string[] = [];\n\t\tfor (const [name, method] of Object.entries(methods)) {\n\t\t\tif (method.description !== undefined && method.description !== \"\") {\n\t\t\t\tfor (const note of method.description.split(\"\\n\")) {\n\t\t\t\t\tlines.push(`// ${note}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst methodString = formatMethod(name, method);\n\t\t\tconst methodLines = methodString.split(\"\\n\");\n\t\t\tlines.push(...methodLines);\n\t\t}\n\t\tif (lines.length > 0) {\n\t\t\thasHelperMethods = true;\n\t\t}\n\t\treturn lines;\n\t}\n\n\tfunction getBoundMembers(definition: string): BoundMembers {\n\t\tconst schemaClass = bindableSchemas.get(definition);\n\t\tif (schemaClass === undefined) {\n\t\t\treturn { methods: {}, properties: {} };\n\t\t}\n\t\treturn {\n\t\t\tmethods: getExposedMethods(schemaClass).methods,\n\t\t\tproperties: getExposedProperties(schemaClass).properties,\n\t\t};\n\t}\n\n\tfunction renderAllowedTypes(allowedTypes: Iterable<string>): TypeExpression {\n\t\tconst expressions: TypeExpression[] = [];\n\t\tfor (const identifier of allowedTypes) {\n\t\t\texpressions.push(renderTypeReference(identifier));\n\t\t}\n\t\tif (expressions.length === 0) {\n\t\t\treturn { precedence: TypePrecedence.Object, text: \"never\" };\n\t\t}\n\t\tif (expressions.length === 1) {\n\t\t\treturn expressions[0] ?? { precedence: TypePrecedence.Object, text: \"never\" };\n\t\t}\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Union,\n\t\t\ttext: expressions\n\t\t\t\t.map((expr) => formatExpression(expr, TypePrecedence.Union))\n\t\t\t\t.join(\" | \"),\n\t\t};\n\t}\n\n\tfunction renderTypeReference(identifier: string): TypeExpression {\n\t\tconst schema = definitions.get(identifier);\n\t\tif (schema === undefined) {\n\t\t\treturn {\n\t\t\t\tprecedence: TypePrecedence.Object,\n\t\t\t\ttext: friendlyNames.get(identifier) ?? unqualifySchema(identifier),\n\t\t\t};\n\t\t}\n\t\tif (isNamedSchema(identifier)) {\n\t\t\treturn {\n\t\t\t\tprecedence: TypePrecedence.Object,\n\t\t\t\ttext: friendlyNames.get(identifier) ?? unqualifySchema(identifier),\n\t\t\t};\n\t\t}\n\t\treturn renderInlineSchema(schema);\n\t}\n\n\tfunction renderInlineSchema(schema: SimpleNodeSchema): TypeExpression {\n\t\tswitch (schema.kind) {\n\t\t\tcase NodeKind.Object: {\n\t\t\t\treturn renderInlineObject(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Array: {\n\t\t\t\treturn renderInlineArray(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\treturn renderInlineMap(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Record: {\n\t\t\t\treturn renderInlineRecord(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Leaf: {\n\t\t\t\treturn { precedence: TypePrecedence.Object, text: renderLeaf(schema.leafKind) };\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\treturn { precedence: TypePrecedence.Object, text: \"unknown\" };\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction renderInlineObject(schema: SimpleObjectNodeSchema): TypeExpression {\n\t\tconst fieldLines: string[] = [];\n\t\tfor (const [fieldName, fieldSchema] of schema.fields) {\n\t\t\tfieldLines.push(...renderFieldLine(fieldName, fieldSchema));\n\t\t}\n\t\tconst members = fieldLines.map((line) => ` ${line}`).join(\"\\n\");\n\t\tconst text =\n\t\t\tmembers === \"\"\n\t\t\t\t? \"{\\n}\"\n\t\t\t\t: `{\n${members}\n}`;\n\t\treturn { precedence: TypePrecedence.Object, text };\n\t}\n\n\tfunction renderInlineArray(schema: SimpleArrayNodeSchema): TypeExpression {\n\t\tconst elementTypes = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Object,\n\t\t\ttext: `${formatExpression(elementTypes)}[]`,\n\t\t};\n\t}\n\n\tfunction renderInlineMap(schema: SimpleMapNodeSchema): TypeExpression {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Object,\n\t\t\ttext: `Map<string, ${valueType.text}>`,\n\t\t};\n\t}\n\n\tfunction renderInlineRecord(schema: SimpleRecordNodeSchema): TypeExpression {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Object,\n\t\t\ttext: `Record<string, ${valueType.text}>`,\n\t\t};\n\t}\n}\n\nfunction describeBinding(\n\tdescription: string | undefined,\n\ttypeLabel: \"array\" | \"map\" | \"record\",\n\tbinding: BindingIntersectionResult,\n): string | undefined {\n\tlet note = \"\";\n\tif (binding.hasMethods && binding.hasProperties) {\n\t\tnote = `Note: this ${typeLabel} has custom user-defined methods and properties directly on it.`;\n\t} else if (binding.hasMethods) {\n\t\tnote = `Note: this ${typeLabel} has custom user-defined methods directly on it.`;\n\t} else if (binding.hasProperties) {\n\t\tnote = `Note: this ${typeLabel} has custom user-defined properties directly on it.`;\n\t}\n\n\tif (note === \"\") {\n\t\treturn description === undefined || description === \"\" ? undefined : description;\n\t}\n\tif (description === undefined || description === \"\") {\n\t\treturn note;\n\t}\n\treturn `${description} - ${note}`;\n}\n\nfunction renderPropertyLines(properties: Record<string, PropertyDef>): string[] {\n\tconst lines: string[] = [];\n\tfor (const [name, property] of Object.entries(properties)) {\n\t\tif (property.description !== undefined && property.description !== \"\") {\n\t\t\tfor (const note of property.description.split(\"\\n\")) {\n\t\t\t\tlines.push(`// ${note}`);\n\t\t\t}\n\t\t}\n\t\tconst modifier = property.readOnly ? \"readonly \" : \"\";\n\t\tconst typeString = renderType(property.schema, 0);\n\t\tconst propertyLine = `${modifier}${name}: ${typeString};`;\n\t\t// Split multi-line type strings and add to lines array\n\t\tconst propertyLines = propertyLine.split(\"\\n\");\n\t\tlines.push(...propertyLines);\n\t}\n\treturn lines;\n}\n\nfunction formatMethod(name: string, method: FunctionWrapper): string {\n\tconst args: string[] = [];\n\tfor (const [argName, argType] of method.args) {\n\t\tconst { innerType, optional } = unwrapOptional(argType);\n\t\tconst renderedType = renderType(innerType, 0);\n\t\targs.push(`${argName}${optional ? \"?\" : \"\"}: ${renderedType}`);\n\t}\n\tif (method.rest !== null) {\n\t\targs.push(`...rest: ${renderType(method.rest, 0)}[]`);\n\t}\n\treturn `${name}(${args.join(\", \")}): ${renderType(method.returns, 0)};`;\n}\n\nfunction renderLeaf(leafKind: ValueSchema): string {\n\tswitch (leafKind) {\n\t\tcase ValueSchema.Boolean: {\n\t\t\treturn \"boolean\";\n\t\t}\n\t\tcase ValueSchema.Number: {\n\t\t\treturn \"number\";\n\t\t}\n\t\tcase ValueSchema.String: {\n\t\t\treturn \"string\";\n\t\t}\n\t\tcase ValueSchema.Null: {\n\t\t\treturn \"null\";\n\t\t}\n\t\tdefault: {\n\t\t\tthrow new Error(`Unsupported leaf kind ${NodeKind[leafKind]}.`);\n\t\t}\n\t}\n}\n\nfunction formatExpression(\n\texpression: TypeExpression,\n\tminPrecedence: TypePrecedence = TypePrecedence.Object,\n): string {\n\treturn expression.precedence < minPrecedence ? `(${expression.text})` : expression.text;\n}\n\n/**\n * Detects optional zod wrappers so argument lists can keep TypeScript optional markers in sync.\n */\nfunction unwrapOptional(type: z.ZodTypeAny | TypeFactoryType): {\n\tinnerType: z.ZodTypeAny | TypeFactoryType;\n\toptional: boolean;\n} {\n\t// Handle type factory optional type\n\tif (isTypeFactoryType(type) && type._kind === \"optional\") {\n\t\treturn { innerType: (type as TypeFactoryOptional).innerType, optional: true };\n\t}\n\t// Handle Zod optional type\n\tif (type instanceof z.ZodOptional) {\n\t\tconst inner = type.unwrap() as z.ZodTypeAny;\n\t\treturn { innerType: inner, optional: true };\n\t}\n\treturn { innerType: type, optional: false };\n}\n\n/**\n * Verifies that helper members do not clobber structural fields and fails fast if they do.\n */\nfunction ensureNoMemberConflicts(\n\tdefinition: string,\n\tfieldNames: ReadonlySet<string>,\n\tmethods: Record<string, FunctionWrapper>,\n\tproperties: Record<string, PropertyDef>,\n): void {\n\tfor (const name of Object.keys(methods)) {\n\t\tif (fieldNames.has(name)) {\n\t\t\tthrow new UsageError(\n\t\t\t\t`Method ${name} conflicts with field of the same name in schema ${definition}`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const name of Object.keys(properties)) {\n\t\tif (fieldNames.has(name)) {\n\t\t\tthrow new UsageError(\n\t\t\t\t`Property ${name} conflicts with field of the same name in schema ${definition}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Dispatches to the correct renderer based on whether the type is Zod or type factory.\n */\nfunction renderType(type: z.ZodTypeAny | TypeFactoryType, indentLevel: number = 0): string {\n\treturn isTypeFactoryType(type)\n\t\t? renderTypeFactoryTypeScript(type, getFriendlyName, instanceOfsTypeFactory, indentLevel)\n\t\t: renderZodTypeScript(type, getFriendlyName, instanceOfs);\n}\n"]}
1
+ {"version":3,"file":"renderSchemaTypeScript.js","sourceRoot":"","sources":["../src/renderSchemaTypeScript.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,0CAA0C,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AASjF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAoB,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EACN,sBAAsB,EACtB,2BAA2B,GAC3B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAE5E,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAuBzF,IAAW,cAIV;AAJD,WAAW,cAAc;IACxB,qDAAS,CAAA;IACT,mEAAgB,CAAA;IAChB,uDAAU,CAAA;AACX,CAAC,EAJU,cAAc,KAAd,cAAc,QAIxB;AAUD;;GAEG;AACH,MAAM,UAAU,sBAAsB,CACrC,WAAkD,EAClD,eAA4C;IAE5C,MAAM,aAAa,GAAG,IAAI,GAAG,EAAkB,CAAC;IAChD,IAAI,gBAAgB,GAAG,KAAK,CAAC;IAE7B,KAAK,MAAM,UAAU,IAAI,WAAW,CAAC,IAAI,EAAE,EAAE,CAAC;QAC7C,IAAI,aAAa,CAAC,UAAU,CAAC,EAAE,CAAC;YAC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AAW,CAAC;QACzF,CAAC,CAAC,mBAAmB,CAAC,IAAI,EAAE,eAAe,EAAE,WAAW,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { UsageError } from \"@fluidframework/telemetry-utils/internal\";\nimport { FieldKind, NodeKind, ValueSchema } from \"@fluidframework/tree/internal\";\nimport type {\n\tSimpleArrayNodeSchema,\n\tSimpleFieldSchema,\n\tSimpleMapNodeSchema,\n\tSimpleNodeSchema,\n\tSimpleObjectNodeSchema,\n\tSimpleRecordNodeSchema,\n} from \"@fluidframework/tree/internal\";\nimport { z } from \"zod\";\n\nimport type { BindableSchema, FunctionWrapper } from \"./methodBinding.js\";\nimport { getExposedMethods } from \"./methodBinding.js\";\nimport { fluidHandleTypeName } from \"./prompt.js\";\nimport { getExposedProperties, type PropertyDef } from \"./propertyBinding.js\";\nimport {\n\tinstanceOfsTypeFactory,\n\trenderTypeFactoryTypeScript,\n} from \"./renderTypeFactoryTypeScript.js\";\nimport { instanceOfs, renderZodTypeScript } from \"./renderZodTypeScript.js\";\nimport type { TypeFactoryOptional, TypeFactoryType } from \"./treeAgentTypes.js\";\nimport { isTypeFactoryType } from \"./treeAgentTypes.js\";\nimport { getFriendlyName, isNamedSchema, llmDefault, unqualifySchema } from \"./utils.js\";\n\ninterface BoundMembers {\n\tmethods: Record<string, FunctionWrapper>;\n\tproperties: Record<string, PropertyDef>;\n}\n\ninterface RenderResult {\n\tdeclaration: string;\n\tdescription?: string;\n}\n\ninterface BindingIntersectionResult {\n\thasMethods: boolean;\n\thasProperties: boolean;\n\tsuffix: string;\n}\n\ninterface TypeExpression {\n\tprecedence: TypePrecedence;\n\ttext: string;\n}\n\nconst enum TypePrecedence {\n\tUnion = 0,\n\tIntersection = 1,\n\tObject = 2,\n}\n\n/**\n * Output of rendering schema metadata into TypeScript declaration text.\n */\nexport interface SchemaTypeScriptRenderResult {\n\tschemaText: string;\n\thasHelperMethods: boolean;\n}\n\n/**\n * Converts schema metadata into TypeScript declarations suitable for prompt inclusion.\n */\nexport function renderSchemaTypeScript(\n\tdefinitions: ReadonlyMap<string, SimpleNodeSchema>,\n\tbindableSchemas: Map<string, BindableSchema>,\n): SchemaTypeScriptRenderResult {\n\tconst friendlyNames = new Map<string, string>();\n\tlet hasHelperMethods = false;\n\n\tfor (const identifier of definitions.keys()) {\n\t\tif (isNamedSchema(identifier)) {\n\t\t\tfriendlyNames.set(identifier, unqualifySchema(identifier));\n\t\t}\n\t}\n\n\tconst declarations: string[] = [];\n\tfor (const [identifier, schema] of definitions) {\n\t\tif (!isNamedSchema(identifier)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst friendlyName = friendlyNames.get(identifier) ?? unqualifySchema(identifier);\n\t\tconst rendered = renderNamedSchema(identifier, friendlyName, schema);\n\t\tif (rendered === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst lines: string[] = [];\n\t\tif (rendered.description !== undefined && rendered.description !== \"\") {\n\t\t\tfor (const comment of rendered.description.split(\"\\n\")) {\n\t\t\t\tlines.push(`// ${comment}`);\n\t\t\t}\n\t\t}\n\t\tlines.push(rendered.declaration);\n\t\tdeclarations.push(lines.join(\"\\n\"));\n\t}\n\n\tconst schemaText = declarations.join(\"\\n\\n\");\n\treturn {\n\t\tschemaText: schemaText === \"\" ? \"\" : `${schemaText}\\n`,\n\t\thasHelperMethods,\n\t};\n\n\tfunction renderNamedSchema(\n\t\tidentifier: string,\n\t\tfriendlyName: string,\n\t\tschema: SimpleNodeSchema,\n\t): RenderResult | undefined {\n\t\tswitch (schema.kind) {\n\t\t\tcase NodeKind.Object: {\n\t\t\t\treturn renderObjectDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Array: {\n\t\t\t\treturn renderArrayDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\treturn renderMapDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Record: {\n\t\t\t\treturn renderRecordDeclaration(identifier, friendlyName, schema);\n\t\t\t}\n\t\t\tcase NodeKind.Leaf: {\n\t\t\t\treturn {\n\t\t\t\t\tdeclaration: `type ${friendlyName} = ${renderLeaf(schema.leafKind)};`,\n\t\t\t\t\tdescription: schema.metadata?.description,\n\t\t\t\t};\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction renderObjectDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleObjectNodeSchema,\n\t): RenderResult {\n\t\tconst fieldLines: string[] = [];\n\t\tconst fieldNames = new Set<string>();\n\n\t\tfor (const [fieldName, fieldSchema] of schema.fields) {\n\t\t\tfieldNames.add(fieldName);\n\t\t\tfieldLines.push(...renderFieldLine(fieldName, fieldSchema));\n\t\t}\n\n\t\tconst { methods, properties } = getBoundMembers(definition);\n\t\tensureNoMemberConflicts(definition, fieldNames, methods, properties);\n\t\tfieldLines.push(...renderPropertyLines(properties));\n\t\tfieldLines.push(...renderMethodLines(methods));\n\n\t\tconst members = fieldLines.map((line) => ` ${line}`).join(\"\\n\");\n\t\tconst body = members === \"\" ? \"\" : `\\n${members}`;\n\t\treturn {\n\t\t\tdeclaration: `interface ${name} {${body}\\n}`,\n\t\t\tdescription: schema.metadata?.description,\n\t\t};\n\t}\n\n\tfunction renderArrayDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleArrayNodeSchema,\n\t): RenderResult {\n\t\tconst elementTypes = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\tconst base = `${formatExpression(elementTypes)}[]`;\n\t\tconst binding = renderBindingIntersection(definition);\n\t\treturn {\n\t\t\tdeclaration: `type ${name} = ${base}${binding.suffix};`,\n\t\t\tdescription: describeBinding(schema.metadata?.description, \"array\", binding),\n\t\t};\n\t}\n\n\tfunction renderMapDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleMapNodeSchema,\n\t): RenderResult {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\tconst base = `Map<string, ${valueType.text}>`;\n\t\tconst binding = renderBindingIntersection(definition);\n\t\treturn {\n\t\t\tdeclaration: `type ${name} = ${base}${binding.suffix};`,\n\t\t\tdescription: describeBinding(schema.metadata?.description, \"map\", binding),\n\t\t};\n\t}\n\n\tfunction renderRecordDeclaration(\n\t\tdefinition: string,\n\t\tname: string,\n\t\tschema: SimpleRecordNodeSchema,\n\t): RenderResult {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\tconst base = `Record<string, ${valueType.text}>`;\n\t\tconst binding = renderBindingIntersection(definition);\n\t\treturn {\n\t\t\tdeclaration: `type ${name} = ${base}${binding.suffix};`,\n\t\t\tdescription: describeBinding(schema.metadata?.description, \"record\", binding),\n\t\t};\n\t}\n\n\tfunction renderFieldLine(name: string, field: SimpleFieldSchema): string[] {\n\t\tconst { comment, optional, type } = describeField(field);\n\t\tconst lines: string[] = [];\n\t\tif (comment !== undefined && comment !== \"\") {\n\t\t\tfor (const note of comment.split(\"\\n\")) {\n\t\t\t\tlines.push(`// ${note}`);\n\t\t\t}\n\t\t}\n\t\tlines.push(`${name}${optional ? \"?\" : \"\"}: ${type};`);\n\t\treturn lines;\n\t}\n\n\tfunction describeField(field: SimpleFieldSchema): {\n\t\tcomment?: string;\n\t\toptional: boolean;\n\t\ttype: string;\n\t} {\n\t\tconst allowedTypes = renderAllowedTypes(field.simpleAllowedTypes.keys());\n\t\tconst type = formatExpression(allowedTypes);\n\t\tconst optional = field.kind !== FieldKind.Required;\n\t\tconst customMetadata = field.metadata.custom as\n\t\t\t| Record<string | symbol, unknown>\n\t\t\t| undefined;\n\t\tconst getDefault = customMetadata?.[llmDefault];\n\n\t\tif (getDefault !== undefined) {\n\t\t\tif (typeof getDefault !== \"function\") {\n\t\t\t\tthrow new UsageError(\n\t\t\t\t\t`Expected value of ${llmDefault.description} property to be a function, but got ${typeof getDefault}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (field.kind !== FieldKind.Optional) {\n\t\t\t\tthrow new UsageError(\n\t\t\t\t\t`The ${llmDefault.description} property is only permitted on optional fields.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toptional,\n\t\t\t\ttype,\n\t\t\t\tcomment:\n\t\t\t\t\t\"Do not populate this field. It will be automatically supplied by the system after insertion.\",\n\t\t\t};\n\t\t}\n\n\t\tif (field.kind === FieldKind.Identifier) {\n\t\t\treturn {\n\t\t\t\toptional: true,\n\t\t\t\ttype,\n\t\t\t\tcomment:\n\t\t\t\t\t\"This is an ID automatically generated by the system. Do not supply it when constructing a new object.\",\n\t\t\t};\n\t\t}\n\n\t\tconst description = field.metadata?.description;\n\t\treturn {\n\t\t\toptional,\n\t\t\ttype,\n\t\t\tcomment: description === undefined || description === \"\" ? undefined : description,\n\t\t};\n\t}\n\n\tfunction renderBindingIntersection(definition: string): BindingIntersectionResult {\n\t\tconst { methods, properties } = getBoundMembers(definition);\n\t\tconst propertyLines = renderPropertyLines(properties);\n\t\tconst methodLines = renderMethodLines(methods);\n\n\t\tif (propertyLines.length === 0 && methodLines.length === 0) {\n\t\t\treturn { hasMethods: false, hasProperties: false, suffix: \"\" };\n\t\t}\n\n\t\tconst lines = [...propertyLines, ...methodLines].map((line) => ` ${line}`);\n\t\tconst suffix = ` & {\\n${lines.join(\"\\n\")}\\n}`;\n\t\treturn {\n\t\t\thasMethods: methodLines.length > 0,\n\t\t\thasProperties: propertyLines.length > 0,\n\t\t\tsuffix,\n\t\t};\n\t}\n\n\tfunction renderMethodLines(methods: Record<string, FunctionWrapper>): string[] {\n\t\tconst lines: string[] = [];\n\t\tfor (const [name, method] of Object.entries(methods)) {\n\t\t\tif (method.description !== undefined && method.description !== \"\") {\n\t\t\t\tfor (const note of method.description.split(\"\\n\")) {\n\t\t\t\t\tlines.push(`// ${note}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst methodString = formatMethod(name, method);\n\t\t\tconst methodLines = methodString.split(\"\\n\");\n\t\t\tlines.push(...methodLines);\n\t\t}\n\t\tif (lines.length > 0) {\n\t\t\thasHelperMethods = true;\n\t\t}\n\t\treturn lines;\n\t}\n\n\tfunction getBoundMembers(definition: string): BoundMembers {\n\t\tconst schemaClass = bindableSchemas.get(definition);\n\t\tif (schemaClass === undefined) {\n\t\t\treturn { methods: {}, properties: {} };\n\t\t}\n\t\treturn {\n\t\t\tmethods: getExposedMethods(schemaClass).methods,\n\t\t\tproperties: getExposedProperties(schemaClass).properties,\n\t\t};\n\t}\n\n\tfunction renderAllowedTypes(allowedTypes: Iterable<string>): TypeExpression {\n\t\tconst expressions: TypeExpression[] = [];\n\t\tfor (const identifier of allowedTypes) {\n\t\t\texpressions.push(renderTypeReference(identifier));\n\t\t}\n\t\tif (expressions.length === 0) {\n\t\t\treturn { precedence: TypePrecedence.Object, text: \"never\" };\n\t\t}\n\t\tif (expressions.length === 1) {\n\t\t\treturn expressions[0] ?? { precedence: TypePrecedence.Object, text: \"never\" };\n\t\t}\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Union,\n\t\t\ttext: expressions\n\t\t\t\t.map((expr) => formatExpression(expr, TypePrecedence.Union))\n\t\t\t\t.join(\" | \"),\n\t\t};\n\t}\n\n\tfunction renderTypeReference(identifier: string): TypeExpression {\n\t\tconst schema = definitions.get(identifier);\n\t\tif (schema === undefined) {\n\t\t\treturn {\n\t\t\t\tprecedence: TypePrecedence.Object,\n\t\t\t\ttext: friendlyNames.get(identifier) ?? unqualifySchema(identifier),\n\t\t\t};\n\t\t}\n\t\tif (isNamedSchema(identifier)) {\n\t\t\treturn {\n\t\t\t\tprecedence: TypePrecedence.Object,\n\t\t\t\ttext: friendlyNames.get(identifier) ?? unqualifySchema(identifier),\n\t\t\t};\n\t\t}\n\t\treturn renderInlineSchema(schema);\n\t}\n\n\tfunction renderInlineSchema(schema: SimpleNodeSchema): TypeExpression {\n\t\tswitch (schema.kind) {\n\t\t\tcase NodeKind.Object: {\n\t\t\t\treturn renderInlineObject(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Array: {\n\t\t\t\treturn renderInlineArray(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Map: {\n\t\t\t\treturn renderInlineMap(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Record: {\n\t\t\t\treturn renderInlineRecord(schema);\n\t\t\t}\n\t\t\tcase NodeKind.Leaf: {\n\t\t\t\treturn { precedence: TypePrecedence.Object, text: renderLeaf(schema.leafKind) };\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\treturn { precedence: TypePrecedence.Object, text: \"unknown\" };\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction renderInlineObject(schema: SimpleObjectNodeSchema): TypeExpression {\n\t\tconst fieldLines: string[] = [];\n\t\tfor (const [fieldName, fieldSchema] of schema.fields) {\n\t\t\tfieldLines.push(...renderFieldLine(fieldName, fieldSchema));\n\t\t}\n\t\tconst members = fieldLines.map((line) => ` ${line}`).join(\"\\n\");\n\t\tconst text =\n\t\t\tmembers === \"\"\n\t\t\t\t? \"{\\n}\"\n\t\t\t\t: `{\n${members}\n}`;\n\t\treturn { precedence: TypePrecedence.Object, text };\n\t}\n\n\tfunction renderInlineArray(schema: SimpleArrayNodeSchema): TypeExpression {\n\t\tconst elementTypes = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Object,\n\t\t\ttext: `${formatExpression(elementTypes)}[]`,\n\t\t};\n\t}\n\n\tfunction renderInlineMap(schema: SimpleMapNodeSchema): TypeExpression {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Object,\n\t\t\ttext: `Map<string, ${valueType.text}>`,\n\t\t};\n\t}\n\n\tfunction renderInlineRecord(schema: SimpleRecordNodeSchema): TypeExpression {\n\t\tconst valueType = renderAllowedTypes(schema.simpleAllowedTypes.keys());\n\t\treturn {\n\t\t\tprecedence: TypePrecedence.Object,\n\t\t\ttext: `Record<string, ${valueType.text}>`,\n\t\t};\n\t}\n}\n\nfunction describeBinding(\n\tdescription: string | undefined,\n\ttypeLabel: \"array\" | \"map\" | \"record\",\n\tbinding: BindingIntersectionResult,\n): string | undefined {\n\tlet note = \"\";\n\tif (binding.hasMethods && binding.hasProperties) {\n\t\tnote = `Note: this ${typeLabel} has custom user-defined methods and properties directly on it.`;\n\t} else if (binding.hasMethods) {\n\t\tnote = `Note: this ${typeLabel} has custom user-defined methods directly on it.`;\n\t} else if (binding.hasProperties) {\n\t\tnote = `Note: this ${typeLabel} has custom user-defined properties directly on it.`;\n\t}\n\n\tif (note === \"\") {\n\t\treturn description === undefined || description === \"\" ? undefined : description;\n\t}\n\tif (description === undefined || description === \"\") {\n\t\treturn note;\n\t}\n\treturn `${description} - ${note}`;\n}\n\nfunction renderPropertyLines(properties: Record<string, PropertyDef>): string[] {\n\tconst lines: string[] = [];\n\tfor (const [name, property] of Object.entries(properties)) {\n\t\tif (property.description !== undefined && property.description !== \"\") {\n\t\t\tfor (const note of property.description.split(\"\\n\")) {\n\t\t\t\tlines.push(`// ${note}`);\n\t\t\t}\n\t\t}\n\t\tconst modifier = property.readOnly ? \"readonly \" : \"\";\n\t\tconst typeString = renderType(property.schema, 0);\n\t\tconst propertyLine = `${modifier}${name}: ${typeString};`;\n\t\t// Split multi-line type strings and add to lines array\n\t\tconst propertyLines = propertyLine.split(\"\\n\");\n\t\tlines.push(...propertyLines);\n\t}\n\treturn lines;\n}\n\nfunction formatMethod(name: string, method: FunctionWrapper): string {\n\tconst args: string[] = [];\n\tfor (const [argName, argType] of method.args) {\n\t\tconst { innerType, optional } = unwrapOptional(argType);\n\t\tconst renderedType = renderType(innerType, 0);\n\t\targs.push(`${argName}${optional ? \"?\" : \"\"}: ${renderedType}`);\n\t}\n\tif (method.rest !== null) {\n\t\targs.push(`...rest: ${renderType(method.rest, 0)}[]`);\n\t}\n\treturn `${name}(${args.join(\", \")}): ${renderType(method.returns, 0)};`;\n}\n\nfunction renderLeaf(leafKind: ValueSchema): string {\n\tswitch (leafKind) {\n\t\tcase ValueSchema.Boolean: {\n\t\t\treturn \"boolean\";\n\t\t}\n\t\tcase ValueSchema.Number: {\n\t\t\treturn \"number\";\n\t\t}\n\t\tcase ValueSchema.String: {\n\t\t\treturn \"string\";\n\t\t}\n\t\tcase ValueSchema.Null: {\n\t\t\treturn \"null\";\n\t\t}\n\t\tcase ValueSchema.FluidHandle: {\n\t\t\treturn fluidHandleTypeName;\n\t\t}\n\t\tdefault: {\n\t\t\tthrow new Error(`Unsupported leaf kind.`);\n\t\t}\n\t}\n}\n\nfunction formatExpression(\n\texpression: TypeExpression,\n\tminPrecedence: TypePrecedence = TypePrecedence.Object,\n): string {\n\treturn expression.precedence < minPrecedence ? `(${expression.text})` : expression.text;\n}\n\n/**\n * Detects optional zod wrappers so argument lists can keep TypeScript optional markers in sync.\n */\nfunction unwrapOptional(type: z.ZodTypeAny | TypeFactoryType): {\n\tinnerType: z.ZodTypeAny | TypeFactoryType;\n\toptional: boolean;\n} {\n\t// Handle type factory optional type\n\tif (isTypeFactoryType(type) && type._kind === \"optional\") {\n\t\treturn { innerType: (type as TypeFactoryOptional).innerType, optional: true };\n\t}\n\t// Handle Zod optional type\n\tif (type instanceof z.ZodOptional) {\n\t\tconst inner = type.unwrap() as z.ZodTypeAny;\n\t\treturn { innerType: inner, optional: true };\n\t}\n\treturn { innerType: type, optional: false };\n}\n\n/**\n * Verifies that helper members do not clobber structural fields and fails fast if they do.\n */\nfunction ensureNoMemberConflicts(\n\tdefinition: string,\n\tfieldNames: ReadonlySet<string>,\n\tmethods: Record<string, FunctionWrapper>,\n\tproperties: Record<string, PropertyDef>,\n): void {\n\tfor (const name of Object.keys(methods)) {\n\t\tif (fieldNames.has(name)) {\n\t\t\tthrow new UsageError(\n\t\t\t\t`Method ${name} conflicts with field of the same name in schema ${definition}`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const name of Object.keys(properties)) {\n\t\tif (fieldNames.has(name)) {\n\t\t\tthrow new UsageError(\n\t\t\t\t`Property ${name} conflicts with field of the same name in schema ${definition}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Dispatches to the correct renderer based on whether the type is Zod or type factory.\n */\nfunction renderType(type: z.ZodTypeAny | TypeFactoryType, indentLevel: number = 0): string {\n\treturn isTypeFactoryType(type)\n\t\t? renderTypeFactoryTypeScript(type, getFriendlyName, instanceOfsTypeFactory, indentLevel)\n\t\t: renderZodTypeScript(type, getFriendlyName, instanceOfs);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluidframework/tree-agent",
3
- "version": "2.81.0",
3
+ "version": "2.82.0",
4
4
  "description": "Experimental package to simplify integrating AI into Fluid-based applications",
5
5
  "homepage": "https://fluidframework.com",
6
6
  "repository": {
@@ -70,31 +70,31 @@
70
70
  },
71
71
  "dependencies": {
72
72
  "@anthropic-ai/sdk": "^0.39.0",
73
- "@fluidframework/core-utils": "~2.81.0",
74
- "@fluidframework/runtime-utils": "~2.81.0",
75
- "@fluidframework/telemetry-utils": "~2.81.0",
76
- "@fluidframework/tree": "~2.81.0",
73
+ "@fluidframework/core-utils": "~2.82.0",
74
+ "@fluidframework/runtime-utils": "~2.82.0",
75
+ "@fluidframework/telemetry-utils": "~2.82.0",
76
+ "@fluidframework/tree": "~2.82.0",
77
77
  "uuid": "^11.1.0",
78
78
  "zod": "^3.25.32"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@arethetypeswrong/cli": "^0.18.2",
82
82
  "@biomejs/biome": "~1.9.3",
83
- "@fluid-internal/mocha-test-setup": "~2.81.0",
83
+ "@fluid-internal/mocha-test-setup": "~2.82.0",
84
84
  "@fluid-tools/build-cli": "^0.63.0",
85
85
  "@fluidframework/build-common": "^2.0.3",
86
86
  "@fluidframework/build-tools": "^0.63.0",
87
- "@fluidframework/eslint-config-fluid": "~2.81.0",
88
- "@fluidframework/id-compressor": "~2.81.0",
89
- "@fluidframework/runtime-utils": "~2.81.0",
90
- "@fluidframework/test-runtime-utils": "~2.81.0",
87
+ "@fluidframework/eslint-config-fluid": "~2.82.0",
88
+ "@fluidframework/id-compressor": "~2.82.0",
89
+ "@fluidframework/runtime-utils": "~2.82.0",
90
+ "@fluidframework/test-runtime-utils": "~2.82.0",
91
91
  "@langchain/anthropic": "^0.3.24",
92
92
  "@langchain/core": "^0.3.78",
93
93
  "@langchain/google-genai": "^0.2.16",
94
94
  "@langchain/openai": "^0.6.12",
95
95
  "@microsoft/api-extractor": "7.52.11",
96
96
  "@types/mocha": "^10.0.10",
97
- "@types/node": "^18.19.0",
97
+ "@types/node": "~20.19.30",
98
98
  "@types/uuid": "^9.0.2",
99
99
  "c8": "^10.1.3",
100
100
  "concurrently": "^9.2.1",
@@ -159,21 +159,21 @@ export type InferArgsZod<Args extends readonly Arg<z.ZodTypeAny>[]> = Args exten
159
159
  * A utility type that infers the function signature from a Zod function definition with strict type checking.
160
160
  * @alpha
161
161
  */
162
- export type InferZod<T> = T extends FunctionDef<
163
- infer Args extends readonly Arg<z.ZodTypeAny>[],
164
- infer Return extends z.ZodTypeAny,
165
- any
166
- >
167
- ? (...args: InferArgsZod<Args>) => z.infer<Return>
168
- : never;
162
+ export type InferZod<T> =
163
+ T extends FunctionDef<
164
+ infer Args extends readonly Arg<z.ZodTypeAny>[],
165
+ infer Return extends z.ZodTypeAny,
166
+ any
167
+ >
168
+ ? (...args: InferArgsZod<Args>) => z.infer<Return>
169
+ : never;
169
170
 
170
171
  /**
171
172
  * A utility type that infers the function signature from a type factory function definition with relaxed type checking.
172
173
  * @alpha
173
174
  */
174
- export type InferTypeFactory<T> = T extends FunctionDef<readonly Arg[], infer Return, any>
175
- ? (...args: any[]) => any
176
- : never;
175
+ export type InferTypeFactory<T> =
176
+ T extends FunctionDef<readonly Arg[], infer Return, any> ? (...args: any[]) => any : never;
177
177
 
178
178
  /**
179
179
  * A utility type that infers the return type of a function definition.
@@ -182,11 +182,12 @@ export type InferTypeFactory<T> = T extends FunctionDef<readonly Arg[], infer Re
182
182
  * For Zod types, provides strict compile-time type checking. For type factory types, returns `any`.
183
183
  * @deprecated Use InferZod or InferTypeFactory directly for better type safety.
184
184
  */
185
- export type Infer<T> = T extends FunctionDef<readonly Arg[], infer Return, any>
186
- ? Return extends z.ZodTypeAny
187
- ? InferZod<T>
188
- : InferTypeFactory<T>
189
- : never;
185
+ export type Infer<T> =
186
+ T extends FunctionDef<readonly Arg[], infer Return, any>
187
+ ? Return extends z.ZodTypeAny
188
+ ? InferZod<T>
189
+ : InferTypeFactory<T>
190
+ : never;
190
191
 
191
192
  /**
192
193
  * An interface for exposing methods of schema classes to an agent.