alchemy 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +3 -3
  2. package/lib/ai/astro-file.d.ts +137 -0
  3. package/lib/ai/astro-file.js +173 -0
  4. package/lib/ai/client.d.ts +2 -10
  5. package/lib/ai/client.js +8 -24
  6. package/lib/ai/css-file.d.ts +131 -0
  7. package/lib/ai/css-file.js +158 -0
  8. package/lib/ai/data.d.ts +45 -5
  9. package/lib/ai/data.js +45 -10
  10. package/lib/ai/document.d.ts +44 -20
  11. package/lib/ai/document.js +95 -28
  12. package/lib/ai/html-file.d.ts +128 -0
  13. package/lib/ai/html-file.js +155 -0
  14. package/lib/ai/index.d.ts +7 -0
  15. package/lib/ai/index.js +7 -0
  16. package/lib/ai/json-file.d.ts +160 -0
  17. package/lib/ai/json-file.js +208 -0
  18. package/lib/ai/typescript-file.d.ts +140 -0
  19. package/lib/ai/typescript-file.js +176 -0
  20. package/lib/ai/vue-file.d.ts +126 -0
  21. package/lib/ai/vue-file.js +153 -0
  22. package/lib/ai/yaml-file.d.ts +169 -0
  23. package/lib/ai/yaml-file.js +236 -0
  24. package/lib/cloudflare/dns.d.ts +88 -0
  25. package/lib/cloudflare/dns.js +192 -0
  26. package/lib/cloudflare/index.d.ts +2 -1
  27. package/lib/cloudflare/index.js +2 -1
  28. package/lib/cloudflare/r2-rest-state-store.d.ts +125 -0
  29. package/lib/cloudflare/r2-rest-state-store.js +254 -0
  30. package/lib/cloudflare/response.d.ts +12 -0
  31. package/lib/cloudflare/response.js +0 -0
  32. package/lib/cloudflare/zone.d.ts +18 -0
  33. package/lib/cloudflare/zone.js +17 -4
  34. package/lib/dns/godaddy.d.ts +7 -0
  35. package/lib/dns/godaddy.js +21 -0
  36. package/lib/dns/import-dns.d.ts +82 -0
  37. package/lib/dns/import-dns.js +114 -0
  38. package/lib/dns/index.d.ts +2 -0
  39. package/lib/dns/index.js +2 -0
  40. package/lib/dns/record.d.ts +88 -0
  41. package/lib/dns/record.js +13 -0
  42. package/lib/fs/file-system-state-store.d.ts +17 -0
  43. package/lib/fs/file-system-state-store.js +87 -0
  44. package/lib/fs/folder.d.ts +10 -0
  45. package/lib/fs/folder.js +2 -2
  46. package/lib/fs/index.d.ts +4 -4
  47. package/lib/fs/index.js +4 -4
  48. package/lib/fs/{json-file.d.ts → static-json-file.d.ts} +2 -2
  49. package/lib/fs/static-json-file.js +14 -0
  50. package/lib/fs/{text-file.d.ts → static-text-file.d.ts} +2 -2
  51. package/lib/fs/{text-file.js → static-text-file.js} +1 -1
  52. package/lib/fs/{typescript-file.d.ts → static-typescript-file.d.ts} +2 -2
  53. package/lib/fs/{typescript-file.js → static-typescript-file.js} +1 -1
  54. package/lib/fs/{yaml-file.d.ts → static-yaml-file.d.ts} +2 -2
  55. package/lib/fs/{yaml-file.js → static-yaml-file.js} +1 -1
  56. package/lib/internal/getting-started.d.ts +10 -0
  57. package/lib/internal/getting-started.js +94 -0
  58. package/lib/internal/project.d.ts +13 -0
  59. package/lib/internal/project.js +101 -0
  60. package/lib/internal/providers.d.ts +23 -0
  61. package/lib/internal/providers.js +148 -0
  62. package/lib/resource.js +8 -1
  63. package/lib/scope.d.ts +1 -1
  64. package/lib/scope.js +4 -2
  65. package/lib/state.d.ts +1 -16
  66. package/lib/state.js +0 -87
  67. package/lib/test/bun.d.ts +11 -0
  68. package/lib/test/bun.js +36 -8
  69. package/lib/web/astro.d.ts +147 -0
  70. package/lib/web/astro.js +414 -0
  71. package/lib/{shadcn/component.js → web/shadcn-component.js} +2 -9
  72. package/lib/web/shadcn.d.ts +97 -0
  73. package/lib/web/shadcn.js +99 -0
  74. package/lib/web/tailwind.d.ts +64 -0
  75. package/lib/web/tailwind.js +97 -0
  76. package/lib/{vite → web}/vite.d.ts +5 -0
  77. package/lib/{vite → web}/vite.js +44 -44
  78. package/lib/web/vitepress/custom-theme.d.ts +173 -0
  79. package/lib/web/vitepress/custom-theme.js +336 -0
  80. package/lib/{vitepress → web/vitepress}/dependencies.d.ts +2 -2
  81. package/lib/{vitepress → web/vitepress}/dependencies.js +1 -1
  82. package/lib/web/vitepress/home-page.d.ts +244 -0
  83. package/lib/web/vitepress/home-page.js +134 -0
  84. package/lib/{vitepress → web/vitepress}/index.d.ts +1 -0
  85. package/lib/{vitepress → web/vitepress}/index.js +1 -0
  86. package/lib/{vitepress → web/vitepress}/vitepress.d.ts +10 -8
  87. package/lib/{vitepress → web/vitepress}/vitepress.js +11 -12
  88. package/package.json +6 -2
  89. package/src/ai/astro-file.ts +288 -0
  90. package/src/ai/client.ts +8 -28
  91. package/src/ai/css-file.ts +266 -0
  92. package/src/ai/data.ts +53 -16
  93. package/src/ai/document.ts +130 -33
  94. package/src/ai/html-file.ts +263 -0
  95. package/src/ai/index.ts +7 -0
  96. package/src/ai/json-file.ts +349 -0
  97. package/src/ai/typescript-file.ts +293 -0
  98. package/src/ai/vue-file.ts +261 -0
  99. package/src/ai/yaml-file.ts +368 -0
  100. package/src/apply.ts +0 -1
  101. package/src/cloudflare/dns.ts +344 -0
  102. package/src/cloudflare/index.ts +2 -1
  103. package/src/cloudflare/r2-rest-state-store.ts +353 -0
  104. package/src/cloudflare/response.ts +9 -0
  105. package/src/cloudflare/zone.ts +39 -23
  106. package/src/dns/godaddy.ts +29 -0
  107. package/src/dns/import-dns.ts +213 -0
  108. package/src/dns/index.ts +2 -0
  109. package/src/dns/record.ts +121 -0
  110. package/src/fs/file-system-state-store.ts +109 -0
  111. package/src/fs/folder.ts +14 -2
  112. package/src/fs/index.ts +4 -4
  113. package/src/fs/{json-file.ts → static-json-file.ts} +13 -3
  114. package/src/fs/{text-file.ts → static-text-file.ts} +5 -2
  115. package/src/fs/{typescript-file.ts → static-typescript-file.ts} +3 -3
  116. package/src/fs/{yaml-file.ts → static-yaml-file.ts} +5 -2
  117. package/src/internal/getting-started.ts +107 -0
  118. package/src/internal/project.ts +119 -0
  119. package/src/internal/providers.ts +209 -0
  120. package/src/resource.ts +10 -1
  121. package/src/scope.ts +5 -6
  122. package/src/state.ts +1 -111
  123. package/src/test/bun.ts +60 -10
  124. package/src/web/astro.ts +644 -0
  125. package/src/{shadcn/component.ts → web/shadcn-component.ts} +5 -13
  126. package/src/web/shadcn.ts +219 -0
  127. package/src/web/tailwind.ts +167 -0
  128. package/src/{vite → web}/vite.ts +54 -56
  129. package/src/web/vitepress/custom-theme.ts +514 -0
  130. package/src/{vitepress → web/vitepress}/dependencies.ts +2 -2
  131. package/src/web/vitepress/home-page.ts +363 -0
  132. package/src/{vitepress → web/vitepress}/index.ts +1 -0
  133. package/src/{vitepress → web/vitepress}/vitepress.ts +34 -27
  134. package/lib/cloudflare/state.d.ts +0 -82
  135. package/lib/cloudflare/state.js +0 -108
  136. package/lib/fs/json-file.js +0 -7
  137. package/lib/internal/docs.d.ts +0 -5
  138. package/lib/internal/docs.js +0 -287
  139. package/lib/shadcn/index.d.ts +0 -1
  140. package/lib/shadcn/index.js +0 -1
  141. package/lib/vite/index.d.ts +0 -1
  142. package/lib/vite/index.js +0 -1
  143. package/lib/vitepress/home-page.d.ts +0 -133
  144. package/lib/vitepress/home-page.js +0 -11
  145. package/src/cloudflare/state.ts +0 -138
  146. package/src/internal/docs.ts +0 -338
  147. package/src/shadcn/index.ts +0 -1
  148. package/src/vite/index.ts +0 -1
  149. package/src/vitepress/home-page.ts +0 -166
  150. /package/lib/{shadcn/component.d.ts → web/shadcn-component.d.ts} +0 -0
  151. /package/src/{vitepress → web/vitepress}/index.md +0 -0
@@ -0,0 +1,155 @@
1
+ import { generateText } from "ai";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { Resource } from "../resource";
5
+ import { ignore } from "../util/ignore";
6
+ import { createModel } from "./client";
7
+ /**
8
+ * Default system prompt for HTML file generation
9
+ */
10
+ const DEFAULT_HTML_SYSTEM_PROMPT = "You are an HTML code generator. Create HTML code based on the user's requirements. Your response MUST include only HTML code inside ```html fences. Do not include any other text, explanations, or multiple code blocks.";
11
+ /**
12
+ * Resource for generating HTML files using AI models.
13
+ * Extracts HTML code from between ```html fences and validates the response.
14
+ *
15
+ * @example
16
+ * // Create a simple landing page
17
+ * const landingPage = await HTMLFile("landing-page", {
18
+ * path: "./public/index.html",
19
+ * prompt: await alchemy`
20
+ * Generate a modern landing page for a SaaS product with:
21
+ * - Hero section with headline and call-to-action
22
+ * - Features section with 3 key features
23
+ * - Pricing section with 3 tiers
24
+ * - Testimonials section with 2 customer quotes
25
+ * - Contact form and footer
26
+ * `,
27
+ * model: {
28
+ * id: "gpt-4o",
29
+ * provider: "openai"
30
+ * }
31
+ * });
32
+ *
33
+ * @example
34
+ * // Generate an HTML email template
35
+ * const emailTemplate = await HTMLFile("welcome-email", {
36
+ * path: "./emails/welcome.html",
37
+ * prompt: await alchemy`
38
+ * Create an HTML email template for welcoming new users to our platform.
39
+ * The email should include:
40
+ * - Company logo and branding
41
+ * - Personalized welcome message (use {{name}} placeholder)
42
+ * - Three steps to get started
43
+ * - Support contact information
44
+ * - Unsubscribe footer
45
+ *
46
+ * Make sure it's responsive and works in all major email clients.
47
+ * `,
48
+ * temperature: 0.2
49
+ * });
50
+ *
51
+ * @example
52
+ * // Generate an HTML component with custom system prompt
53
+ * const navComponent = await HTMLFile("navigation", {
54
+ * path: "./components/nav.html",
55
+ * prompt: await alchemy`
56
+ * Create a responsive navigation component with:
57
+ * - Logo in the left corner
58
+ * - Navigation links: Home, Products, Services, About, Contact
59
+ * - Mobile hamburger menu that expands/collapses
60
+ * - Login/signup buttons on the right side
61
+ * - Dark/light mode toggle
62
+ * `,
63
+ * system: "You are an expert HTML/CSS developer specializing in responsive components. Create a single HTML file inside ```html fences with no additional text. Use modern HTML5 semantic elements and inline CSS if needed.",
64
+ * model: {
65
+ * id: "claude-3-opus-20240229",
66
+ * provider: "anthropic"
67
+ * }
68
+ * });
69
+ */
70
+ export const HTMLFile = Resource("ai::HTMLFile", async function (id, props) {
71
+ // Ensure directory exists
72
+ await fs.mkdir(path.dirname(props.path), { recursive: true });
73
+ if (this.phase === "delete") {
74
+ try {
75
+ await fs.unlink(props.path);
76
+ }
77
+ catch (error) {
78
+ // Ignore if file doesn't exist
79
+ if (error.code !== "ENOENT") {
80
+ throw error;
81
+ }
82
+ }
83
+ return this.destroy();
84
+ }
85
+ // Use provided system prompt or default
86
+ const system = props.system || DEFAULT_HTML_SYSTEM_PROMPT;
87
+ // Generate initial content
88
+ const { text } = await generateText({
89
+ model: createModel(props),
90
+ prompt: props.prompt,
91
+ system,
92
+ providerOptions: props.model?.options,
93
+ ...(props.temperature === undefined
94
+ ? {}
95
+ : { temperature: props.temperature }),
96
+ });
97
+ // Extract and validate HTML code
98
+ let { code, error } = await extractHTMLCode(text);
99
+ // Re-prompt if there are validation errors
100
+ if (error) {
101
+ const errorSystem = `${system}\n\nERROR: ${error}\n\nPlease try again and ensure your response contains exactly one HTML code block inside \`\`\`html fences.`;
102
+ const { text: retryText } = await generateText({
103
+ model: createModel(props),
104
+ prompt: props.prompt,
105
+ system: errorSystem,
106
+ providerOptions: props.model?.options,
107
+ ...(props.temperature === undefined
108
+ ? {}
109
+ : { temperature: props.temperature }),
110
+ });
111
+ const retryResult = await extractHTMLCode(retryText);
112
+ if (retryResult.error) {
113
+ throw new Error(`Failed to generate valid HTML code: ${retryResult.error}`);
114
+ }
115
+ code = retryResult.code;
116
+ }
117
+ if (this.phase === "update" && props.path !== this.props.path) {
118
+ await ignore("ENOENT", () => fs.unlink(this.props.path));
119
+ }
120
+ // Write content to file
121
+ await fs.writeFile(props.path, code);
122
+ // Get file stats for timestamps
123
+ const stats = await fs.stat(props.path);
124
+ // Return the resource
125
+ return this({
126
+ ...props,
127
+ content: code,
128
+ createdAt: stats.birthtimeMs,
129
+ updatedAt: stats.mtimeMs,
130
+ });
131
+ });
132
+ /**
133
+ * Extracts HTML code from between ```html fences
134
+ * Validates that exactly one HTML code block exists
135
+ *
136
+ * @param text The text to extract HTML code from
137
+ * @returns The extracted HTML code or error message
138
+ */
139
+ async function extractHTMLCode(text) {
140
+ const htmlCodeRegex = /```html\s*([\s\S]*?)```/g;
141
+ const matches = Array.from(text.matchAll(htmlCodeRegex));
142
+ if (matches.length === 0) {
143
+ return {
144
+ code: "",
145
+ error: "No HTML code block found in the response. Please include your code within ```html fences.",
146
+ };
147
+ }
148
+ if (matches.length > 1) {
149
+ return {
150
+ code: "",
151
+ error: "Multiple HTML code blocks found in the response. Please provide exactly one code block within ```html fences.",
152
+ };
153
+ }
154
+ return { code: matches[0][1].trim() };
155
+ }
package/lib/ai/index.d.ts CHANGED
@@ -1,3 +1,10 @@
1
1
  export * from "./ark";
2
+ export * from "./astro-file";
3
+ export * from "./css-file";
2
4
  export * from "./data";
3
5
  export * from "./document";
6
+ export * from "./html-file";
7
+ export * from "./json-file";
8
+ export * from "./typescript-file";
9
+ export * from "./vue-file";
10
+ export * from "./yaml-file";
package/lib/ai/index.js CHANGED
@@ -1,3 +1,10 @@
1
1
  export * from "./ark";
2
+ export * from "./astro-file";
3
+ export * from "./css-file";
2
4
  export * from "./data";
3
5
  export * from "./document";
6
+ export * from "./html-file";
7
+ export * from "./json-file";
8
+ export * from "./typescript-file";
9
+ export * from "./vue-file";
10
+ export * from "./yaml-file";
@@ -0,0 +1,160 @@
1
+ import type { JsonSchema, Type, type } from "arktype";
2
+ import type { Context } from "../context";
3
+ import { Resource } from "../resource";
4
+ import type { Secret } from "../secret";
5
+ import { type ModelConfig } from "./client";
6
+ /**
7
+ * Properties for creating or updating a JSONFile
8
+ */
9
+ export interface JSONFileProps<T extends Type<any, any> | undefined = undefined> {
10
+ /**
11
+ * Path to the JSON file
12
+ */
13
+ path: string;
14
+ /**
15
+ * Optional ArkType schema to validate and structure the generated JSON
16
+ * When provided, the resource will use generateObject with schema validation
17
+ * When not provided, it will extract JSON from between ```json fences
18
+ */
19
+ schema?: T;
20
+ /**
21
+ * Base URL for the OpenAI API
22
+ * @default 'https://api.openai.com/v1'
23
+ */
24
+ baseURL?: string;
25
+ /**
26
+ * Prompt for generating content
27
+ * Use alchemy template literals to include file context:
28
+ * @example
29
+ * prompt: await alchemy`
30
+ * Generate a JSON configuration for:
31
+ * ${alchemy.file("src/config.ts")}
32
+ * `
33
+ */
34
+ prompt: string;
35
+ /**
36
+ * System prompt for the model
37
+ * This is used to provide instructions to the model about how to format the response
38
+ * @default Depends on whether schema is provided
39
+ */
40
+ system?: string;
41
+ /**
42
+ * OpenAI API key to use for generating content
43
+ * If not provided, will use OPENAI_API_KEY environment variable
44
+ */
45
+ apiKey?: Secret;
46
+ /**
47
+ * Model configuration
48
+ */
49
+ model?: ModelConfig;
50
+ /**
51
+ * Temperature for controlling randomness in generation.
52
+ * Higher values (e.g., 0.8) make output more random,
53
+ * lower values (e.g., 0.2) make it more deterministic.
54
+ * @default 0.7
55
+ */
56
+ temperature?: number;
57
+ /**
58
+ * Whether to pretty-print the JSON with indentation
59
+ * @default true
60
+ */
61
+ pretty?: boolean;
62
+ /**
63
+ * Number of spaces to use for indentation when pretty-printing
64
+ * @default 2
65
+ */
66
+ indent?: number;
67
+ }
68
+ /**
69
+ * A JSON file that can be created, updated, and deleted
70
+ */
71
+ export interface JSONFile<T = any> extends Omit<JSONFileProps, "schema">, Resource<"ai::JSONFile"> {
72
+ /**
73
+ * Content of the JSON file as a string
74
+ */
75
+ content: string;
76
+ /**
77
+ * Parsed JSON object
78
+ */
79
+ json: T;
80
+ /**
81
+ * Schema used to validate the JSON (if provided)
82
+ */
83
+ schema?: JsonSchema;
84
+ /**
85
+ * Time at which the file was created
86
+ */
87
+ createdAt: number;
88
+ /**
89
+ * Time at which the file was last updated
90
+ */
91
+ updatedAt: number;
92
+ }
93
+ /**
94
+ * Resource for generating JSON files using AI models.
95
+ * Can operate in two modes:
96
+ * 1. With schema: Uses generateObject with type validation
97
+ * 2. Without schema: Extracts JSON from between ```json fences
98
+ *
99
+ * @example
100
+ * // Generate a configuration file with freeform JSON
101
+ * const config = await JSONFile("app-config", {
102
+ * path: "./config/app.json",
103
+ * prompt: await alchemy`
104
+ * Generate a configuration for a web application with:
105
+ * - Server settings (port, host, timeout)
106
+ * - Database connection details (redact any passwords)
107
+ * - Logging configuration
108
+ * - Feature flags
109
+ * `,
110
+ * model: {
111
+ * id: "gpt-4o",
112
+ * provider: "openai"
113
+ * }
114
+ * });
115
+ *
116
+ * @example
117
+ * // Generate JSON with schema validation
118
+ * import { type } from "arktype";
119
+ *
120
+ * const userSchema = type({
121
+ * users: [{
122
+ * id: "string",
123
+ * name: "string",
124
+ * email: "string",
125
+ * role: "'admin' | 'user' | 'guest'",
126
+ * permissions: "string[]",
127
+ * active: "boolean"
128
+ * }]
129
+ * });
130
+ *
131
+ * const userData = await JSONFile("user-data", {
132
+ * path: "./data/users.json",
133
+ * schema: userSchema,
134
+ * prompt: "Generate sample user data for an application with various roles and permissions",
135
+ * temperature: 0.2
136
+ * });
137
+ *
138
+ * // Type-safe access to the generated data
139
+ * console.log(userData.json.users[0].role); // Typed as 'admin' | 'user' | 'guest'
140
+ *
141
+ * @example
142
+ * // Generate API mock data with custom system prompt
143
+ * const apiMock = await JSONFile("api-mock", {
144
+ * path: "./mocks/products-api.json",
145
+ * prompt: await alchemy`
146
+ * Create mock data for a product catalog API response with:
147
+ * - 10 products with different categories
148
+ * - Each product should have id, name, price, category, inventory, and image_url
149
+ * - Include pagination metadata (total, page, limit)
150
+ * `,
151
+ * system: "You are an API design expert. Create realistic mock JSON data that follows REST API best practices. Your response must be valid JSON inside ```json fences.",
152
+ * model: {
153
+ * id: "claude-3-opus-20240229",
154
+ * provider: "anthropic"
155
+ * },
156
+ * pretty: true,
157
+ * indent: 4
158
+ * });
159
+ */
160
+ export declare const JSONFile: (((this: any, id: string, props?: {}) => never) & (new (_: never) => never)) | (<const T extends Type<any, any> | undefined = undefined>(this: Context<JSONFile<T extends Type<any, any> ? type.infer<T> : any>>, id: string, props: JSONFileProps<T>) => Promise<JSONFile<T extends Type<any, any> ? type.infer<T> : any>>);
@@ -0,0 +1,208 @@
1
+ import { generateObject, generateText } from "ai";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { Resource } from "../resource";
5
+ import { ignore } from "../util/ignore";
6
+ import { ark } from "./ark";
7
+ import { createModel } from "./client";
8
+ /**
9
+ * Default system prompt for JSON file generation without schema
10
+ */
11
+ const DEFAULT_JSON_SYSTEM_PROMPT = "You are a JSON generator. Create valid JSON based on the user's requirements. Your response MUST include only JSON inside ```json fences. Do not include any other text, explanations, or multiple code blocks.";
12
+ /**
13
+ * Resource for generating JSON files using AI models.
14
+ * Can operate in two modes:
15
+ * 1. With schema: Uses generateObject with type validation
16
+ * 2. Without schema: Extracts JSON from between ```json fences
17
+ *
18
+ * @example
19
+ * // Generate a configuration file with freeform JSON
20
+ * const config = await JSONFile("app-config", {
21
+ * path: "./config/app.json",
22
+ * prompt: await alchemy`
23
+ * Generate a configuration for a web application with:
24
+ * - Server settings (port, host, timeout)
25
+ * - Database connection details (redact any passwords)
26
+ * - Logging configuration
27
+ * - Feature flags
28
+ * `,
29
+ * model: {
30
+ * id: "gpt-4o",
31
+ * provider: "openai"
32
+ * }
33
+ * });
34
+ *
35
+ * @example
36
+ * // Generate JSON with schema validation
37
+ * import { type } from "arktype";
38
+ *
39
+ * const userSchema = type({
40
+ * users: [{
41
+ * id: "string",
42
+ * name: "string",
43
+ * email: "string",
44
+ * role: "'admin' | 'user' | 'guest'",
45
+ * permissions: "string[]",
46
+ * active: "boolean"
47
+ * }]
48
+ * });
49
+ *
50
+ * const userData = await JSONFile("user-data", {
51
+ * path: "./data/users.json",
52
+ * schema: userSchema,
53
+ * prompt: "Generate sample user data for an application with various roles and permissions",
54
+ * temperature: 0.2
55
+ * });
56
+ *
57
+ * // Type-safe access to the generated data
58
+ * console.log(userData.json.users[0].role); // Typed as 'admin' | 'user' | 'guest'
59
+ *
60
+ * @example
61
+ * // Generate API mock data with custom system prompt
62
+ * const apiMock = await JSONFile("api-mock", {
63
+ * path: "./mocks/products-api.json",
64
+ * prompt: await alchemy`
65
+ * Create mock data for a product catalog API response with:
66
+ * - 10 products with different categories
67
+ * - Each product should have id, name, price, category, inventory, and image_url
68
+ * - Include pagination metadata (total, page, limit)
69
+ * `,
70
+ * system: "You are an API design expert. Create realistic mock JSON data that follows REST API best practices. Your response must be valid JSON inside ```json fences.",
71
+ * model: {
72
+ * id: "claude-3-opus-20240229",
73
+ * provider: "anthropic"
74
+ * },
75
+ * pretty: true,
76
+ * indent: 4
77
+ * });
78
+ */
79
+ export const JSONFile = Resource("ai::JSONFile", async function (id, props) {
80
+ // Ensure directory exists
81
+ await fs.mkdir(path.dirname(props.path), { recursive: true });
82
+ if (this.phase === "delete") {
83
+ try {
84
+ await fs.unlink(props.path);
85
+ }
86
+ catch (error) {
87
+ // Ignore if file doesn't exist
88
+ if (error.code !== "ENOENT") {
89
+ throw error;
90
+ }
91
+ }
92
+ return this.destroy();
93
+ }
94
+ // Determine if we should use pretty printing
95
+ const pretty = props.pretty !== false;
96
+ const indent = props.indent ?? 2;
97
+ let jsonContent;
98
+ let jsonObject;
99
+ // Check if schema is provided
100
+ if (props.schema) {
101
+ // Use schema-based generation
102
+ const { object } = await generateObject({
103
+ model: createModel(props),
104
+ schema: ark.schema(props.schema),
105
+ providerOptions: props.model?.options,
106
+ system: props.system ||
107
+ "Generate a valid JSON object based on the provided requirements.",
108
+ prompt: props.prompt,
109
+ ...(props.temperature === undefined
110
+ ? {}
111
+ : { temperature: props.temperature }),
112
+ });
113
+ jsonObject = object;
114
+ jsonContent = pretty
115
+ ? JSON.stringify(jsonObject, null, indent)
116
+ : JSON.stringify(jsonObject);
117
+ }
118
+ else {
119
+ // Use fence-based extraction
120
+ // Use provided system prompt or default
121
+ const system = props.system || DEFAULT_JSON_SYSTEM_PROMPT;
122
+ // Generate initial content
123
+ const { text } = await generateText({
124
+ model: createModel(props),
125
+ prompt: props.prompt,
126
+ system,
127
+ providerOptions: props.model?.options,
128
+ ...(props.temperature === undefined
129
+ ? {}
130
+ : { temperature: props.temperature }),
131
+ });
132
+ // Extract and validate JSON content
133
+ let { content, error } = await extractJSONContent(text);
134
+ // Re-prompt if there are validation errors
135
+ if (error) {
136
+ const errorSystem = `${system}\n\nERROR: ${error}\n\nPlease try again and ensure your response contains exactly one valid JSON block inside \`\`\`json fences.`;
137
+ const { text: retryText } = await generateText({
138
+ model: createModel(props),
139
+ prompt: props.prompt,
140
+ system: errorSystem,
141
+ providerOptions: props.model?.options,
142
+ ...(props.temperature === undefined
143
+ ? {}
144
+ : { temperature: props.temperature }),
145
+ });
146
+ const retryResult = await extractJSONContent(retryText);
147
+ if (retryResult.error) {
148
+ throw new Error(`Failed to generate valid JSON: ${retryResult.error}`);
149
+ }
150
+ content = retryResult.content;
151
+ }
152
+ // Parse JSON
153
+ jsonObject = JSON.parse(content);
154
+ // Format with or without indentation based on pretty option
155
+ jsonContent = pretty ? JSON.stringify(jsonObject, null, indent) : content;
156
+ }
157
+ if (this.phase === "update" && props.path !== this.props.path) {
158
+ await ignore("ENOENT", () => fs.unlink(this.props.path));
159
+ }
160
+ // Write content to file
161
+ await fs.writeFile(props.path, jsonContent);
162
+ // Get file stats for timestamps
163
+ const stats = await fs.stat(props.path);
164
+ // Return the resource
165
+ return this({
166
+ ...props,
167
+ schema: props.schema,
168
+ content: jsonContent,
169
+ json: jsonObject,
170
+ createdAt: stats.birthtimeMs,
171
+ updatedAt: stats.mtimeMs,
172
+ });
173
+ });
174
+ /**
175
+ * Extracts JSON content from between ```json fences
176
+ * Validates that exactly one JSON code block exists
177
+ *
178
+ * @param text The text to extract JSON from
179
+ * @returns The extracted JSON or error message
180
+ */
181
+ async function extractJSONContent(text) {
182
+ const jsonCodeRegex = /```json\s*([\s\S]*?)```/g;
183
+ const matches = Array.from(text.matchAll(jsonCodeRegex));
184
+ if (matches.length === 0) {
185
+ return {
186
+ content: "",
187
+ error: "No JSON code block found in the response. Please include your JSON within ```json fences.",
188
+ };
189
+ }
190
+ if (matches.length > 1) {
191
+ return {
192
+ content: "",
193
+ error: "Multiple JSON code blocks found in the response. Please provide exactly one JSON block within ```json fences.",
194
+ };
195
+ }
196
+ const content = matches[0][1].trim();
197
+ // Validate JSON can be parsed
198
+ try {
199
+ JSON.parse(content);
200
+ return { content };
201
+ }
202
+ catch (e) {
203
+ return {
204
+ content: "",
205
+ error: `Invalid JSON: ${e.message}. Please provide valid JSON syntax.`,
206
+ };
207
+ }
208
+ }
@@ -0,0 +1,140 @@
1
+ import prettier from "prettier";
2
+ import type { Context } from "../context";
3
+ import { Resource } from "../resource";
4
+ import type { Secret } from "../secret";
5
+ import { type ModelConfig } from "./client";
6
+ /**
7
+ * Properties for creating or updating a TypeScriptFile
8
+ */
9
+ export interface TypeScriptFileProps {
10
+ /**
11
+ * Path to the TypeScript file
12
+ */
13
+ path: string;
14
+ /**
15
+ * Base URL for the OpenAI API
16
+ * @default 'https://api.openai.com/v1'
17
+ */
18
+ baseURL?: string;
19
+ /**
20
+ * Prompt for generating content
21
+ * Use alchemy template literals to include file context:
22
+ * @example
23
+ * prompt: await alchemy`
24
+ * Generate a TypeScript utility function using:
25
+ * ${alchemy.file("src/types.ts")}
26
+ * `
27
+ */
28
+ prompt: string;
29
+ /**
30
+ * System prompt for the model
31
+ * This is used to provide instructions to the model about how to format the response
32
+ * The default system prompt instructs the model to return TypeScript code inside ```ts fences
33
+ * @default "You are a TypeScript code generator. Create TypeScript code based on the user's requirements. Your response MUST include only TypeScript code inside ```ts fences. Do not include any other text, explanations, or multiple code blocks."
34
+ */
35
+ system?: string;
36
+ /**
37
+ * OpenAI API key to use for generating content
38
+ * If not provided, will use OPENAI_API_KEY environment variable
39
+ */
40
+ apiKey?: Secret;
41
+ /**
42
+ * Model configuration
43
+ */
44
+ model?: ModelConfig;
45
+ /**
46
+ * Temperature for controlling randomness in generation.
47
+ * Higher values (e.g., 0.8) make output more random,
48
+ * lower values (e.g., 0.2) make it more deterministic.
49
+ * @default 0.7
50
+ */
51
+ temperature?: number;
52
+ /**
53
+ * Prettier configuration to use for formatting the TypeScript code
54
+ * If not provided, will use the default Prettier configuration
55
+ */
56
+ prettierConfig?: prettier.Options;
57
+ }
58
+ /**
59
+ * A TypeScript file that can be created, updated, and deleted
60
+ */
61
+ export interface TypeScriptFile extends TypeScriptFileProps, Resource<"ai::TypeScriptFile"> {
62
+ /**
63
+ * Content of the TypeScript file
64
+ */
65
+ content: string;
66
+ /**
67
+ * Time at which the file was created
68
+ */
69
+ createdAt: number;
70
+ /**
71
+ * Time at which the file was last updated
72
+ */
73
+ updatedAt: number;
74
+ }
75
+ /**
76
+ * Resource for generating TypeScript files using AI models.
77
+ * Extracts TypeScript code from between ```ts fences, validates the response,
78
+ * and formats the code with Prettier.
79
+ *
80
+ * @example
81
+ * // Create a utility function
82
+ * const utils = await TypeScriptFile("string-utils", {
83
+ * path: "./src/utils/string-utils.ts",
84
+ * prompt: await alchemy`
85
+ * Generate TypeScript utility functions for string manipulation:
86
+ * - Capitalize first letter
87
+ * - Truncate with ellipsis
88
+ * - Convert to camelCase and kebab-case
89
+ * - Remove special characters
90
+ * `,
91
+ * model: {
92
+ * id: "gpt-4o",
93
+ * provider: "openai"
94
+ * }
95
+ * });
96
+ *
97
+ * @example
98
+ * // Generate a TypeScript class with custom formatting
99
+ * const userService = await TypeScriptFile("user-service", {
100
+ * path: "./src/services/UserService.ts",
101
+ * prompt: await alchemy`
102
+ * Create a UserService class that handles user authentication and profile management.
103
+ * The service should use the User type from:
104
+ * ${alchemy.file("src/types/User.ts")}
105
+ *
106
+ * Include methods for:
107
+ * - login(email, password)
108
+ * - register(user)
109
+ * - updateProfile(userId, profileData)
110
+ * - deleteAccount(userId)
111
+ * `,
112
+ * temperature: 0.2,
113
+ * prettierConfig: {
114
+ * semi: false,
115
+ * singleQuote: true,
116
+ * printWidth: 120
117
+ * }
118
+ * });
119
+ *
120
+ * @example
121
+ * // Generate a React hook with custom system prompt
122
+ * const useFormHook = await TypeScriptFile("use-form", {
123
+ * path: "./src/hooks/useForm.ts",
124
+ * prompt: await alchemy`
125
+ * Create a custom React hook called useForm that handles form state, validation, and submission.
126
+ * It should support:
127
+ * - Initial values
128
+ * - Validation rules
129
+ * - Field errors
130
+ * - Form submission with loading state
131
+ * - Reset functionality
132
+ * `,
133
+ * system: "You are an expert React developer specializing in TypeScript hooks. Create a single TypeScript file inside ```ts fences with no additional text. Follow React best practices and include proper typing.",
134
+ * model: {
135
+ * id: "claude-3-opus-20240229",
136
+ * provider: "anthropic"
137
+ * }
138
+ * });
139
+ */
140
+ export declare const TypeScriptFile: (((this: any, id: string, props?: {}) => never) & (new (_: never) => never)) | ((this: Context<TypeScriptFile>, id: string, props: TypeScriptFileProps) => Promise<TypeScriptFile>);