swallowkit 1.0.0-beta.2 → 1.0.0-beta.20

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 (191) hide show
  1. package/LICENSE +21 -21
  2. package/README.ja.md +312 -215
  3. package/README.md +369 -216
  4. package/dist/__tests__/fixtures.d.ts +22 -0
  5. package/dist/__tests__/fixtures.d.ts.map +1 -0
  6. package/dist/__tests__/fixtures.js +146 -0
  7. package/dist/__tests__/fixtures.js.map +1 -0
  8. package/dist/cli/commands/add-auth.d.ts +10 -0
  9. package/dist/cli/commands/add-auth.d.ts.map +1 -0
  10. package/dist/cli/commands/add-auth.js +444 -0
  11. package/dist/cli/commands/add-auth.js.map +1 -0
  12. package/dist/cli/commands/add-connector.d.ts +20 -0
  13. package/dist/cli/commands/add-connector.d.ts.map +1 -0
  14. package/dist/cli/commands/add-connector.js +163 -0
  15. package/dist/cli/commands/add-connector.js.map +1 -0
  16. package/dist/cli/commands/create-model.d.ts +1 -4
  17. package/dist/cli/commands/create-model.d.ts.map +1 -1
  18. package/dist/cli/commands/create-model.js +21 -82
  19. package/dist/cli/commands/create-model.js.map +1 -1
  20. package/dist/cli/commands/dev-seeds.d.ts +35 -0
  21. package/dist/cli/commands/dev-seeds.d.ts.map +1 -0
  22. package/dist/cli/commands/dev-seeds.js +292 -0
  23. package/dist/cli/commands/dev-seeds.js.map +1 -0
  24. package/dist/cli/commands/dev.d.ts +19 -0
  25. package/dist/cli/commands/dev.d.ts.map +1 -1
  26. package/dist/cli/commands/dev.js +476 -117
  27. package/dist/cli/commands/dev.js.map +1 -1
  28. package/dist/cli/commands/index.d.ts +1 -0
  29. package/dist/cli/commands/index.d.ts.map +1 -1
  30. package/dist/cli/commands/index.js +3 -1
  31. package/dist/cli/commands/index.js.map +1 -1
  32. package/dist/cli/commands/init.d.ts +13 -0
  33. package/dist/cli/commands/init.d.ts.map +1 -1
  34. package/dist/cli/commands/init.js +2627 -1708
  35. package/dist/cli/commands/init.js.map +1 -1
  36. package/dist/cli/commands/scaffold.d.ts +3 -0
  37. package/dist/cli/commands/scaffold.d.ts.map +1 -1
  38. package/dist/cli/commands/scaffold.js +617 -129
  39. package/dist/cli/commands/scaffold.js.map +1 -1
  40. package/dist/cli/index.d.ts +4 -1
  41. package/dist/cli/index.d.ts.map +1 -1
  42. package/dist/cli/index.js +162 -42
  43. package/dist/cli/index.js.map +1 -1
  44. package/dist/core/config.d.ts +8 -2
  45. package/dist/core/config.d.ts.map +1 -1
  46. package/dist/core/config.js +90 -4
  47. package/dist/core/config.js.map +1 -1
  48. package/dist/core/mock/connector-mock-server.d.ts +101 -0
  49. package/dist/core/mock/connector-mock-server.d.ts.map +1 -0
  50. package/dist/core/mock/connector-mock-server.js +480 -0
  51. package/dist/core/mock/connector-mock-server.js.map +1 -0
  52. package/dist/core/mock/zod-mock-generator.d.ts +14 -0
  53. package/dist/core/mock/zod-mock-generator.d.ts.map +1 -0
  54. package/dist/core/mock/zod-mock-generator.js +163 -0
  55. package/dist/core/mock/zod-mock-generator.js.map +1 -0
  56. package/dist/core/operations/create-model.d.ts +15 -0
  57. package/dist/core/operations/create-model.d.ts.map +1 -0
  58. package/dist/core/operations/create-model.js +171 -0
  59. package/dist/core/operations/create-model.js.map +1 -0
  60. package/dist/core/operations/runtime.d.ts +32 -0
  61. package/dist/core/operations/runtime.d.ts.map +1 -0
  62. package/dist/core/operations/runtime.js +225 -0
  63. package/dist/core/operations/runtime.js.map +1 -0
  64. package/dist/core/operations/scaffold-machine.d.ts +16 -0
  65. package/dist/core/operations/scaffold-machine.d.ts.map +1 -0
  66. package/dist/core/operations/scaffold-machine.js +63 -0
  67. package/dist/core/operations/scaffold-machine.js.map +1 -0
  68. package/dist/core/project/manifest.d.ts +92 -0
  69. package/dist/core/project/manifest.d.ts.map +1 -0
  70. package/dist/core/project/manifest.js +321 -0
  71. package/dist/core/project/manifest.js.map +1 -0
  72. package/dist/core/project/validation.d.ts +20 -0
  73. package/dist/core/project/validation.d.ts.map +1 -0
  74. package/dist/core/project/validation.js +204 -0
  75. package/dist/core/project/validation.js.map +1 -0
  76. package/dist/core/scaffold/auth-generator.d.ts +38 -0
  77. package/dist/core/scaffold/auth-generator.d.ts.map +1 -0
  78. package/dist/core/scaffold/auth-generator.js +1244 -0
  79. package/dist/core/scaffold/auth-generator.js.map +1 -0
  80. package/dist/core/scaffold/connector-functions-generator.d.ts +41 -0
  81. package/dist/core/scaffold/connector-functions-generator.d.ts.map +1 -0
  82. package/dist/core/scaffold/connector-functions-generator.js +1027 -0
  83. package/dist/core/scaffold/connector-functions-generator.js.map +1 -0
  84. package/dist/core/scaffold/functions-generator.d.ts +7 -1
  85. package/dist/core/scaffold/functions-generator.d.ts.map +1 -1
  86. package/dist/core/scaffold/functions-generator.js +920 -213
  87. package/dist/core/scaffold/functions-generator.js.map +1 -1
  88. package/dist/core/scaffold/model-parser.d.ts +20 -1
  89. package/dist/core/scaffold/model-parser.d.ts.map +1 -1
  90. package/dist/core/scaffold/model-parser.js +329 -135
  91. package/dist/core/scaffold/model-parser.js.map +1 -1
  92. package/dist/core/scaffold/nextjs-generator.d.ts +8 -0
  93. package/dist/core/scaffold/nextjs-generator.d.ts.map +1 -1
  94. package/dist/core/scaffold/nextjs-generator.js +314 -182
  95. package/dist/core/scaffold/nextjs-generator.js.map +1 -1
  96. package/dist/core/scaffold/openapi-generator.d.ts +3 -0
  97. package/dist/core/scaffold/openapi-generator.d.ts.map +1 -0
  98. package/dist/core/scaffold/openapi-generator.js +190 -0
  99. package/dist/core/scaffold/openapi-generator.js.map +1 -0
  100. package/dist/core/scaffold/ui-generator.d.ts +10 -4
  101. package/dist/core/scaffold/ui-generator.d.ts.map +1 -1
  102. package/dist/core/scaffold/ui-generator.js +768 -663
  103. package/dist/core/scaffold/ui-generator.js.map +1 -1
  104. package/dist/database/base-model.d.ts +3 -3
  105. package/dist/database/base-model.js +3 -3
  106. package/dist/index.d.ts +2 -2
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.js +2 -1
  109. package/dist/index.js.map +1 -1
  110. package/dist/machine/contracts.d.ts +16 -0
  111. package/dist/machine/contracts.d.ts.map +1 -0
  112. package/dist/machine/contracts.js +3 -0
  113. package/dist/machine/contracts.js.map +1 -0
  114. package/dist/machine/errors.d.ts +11 -0
  115. package/dist/machine/errors.d.ts.map +1 -0
  116. package/dist/machine/errors.js +34 -0
  117. package/dist/machine/errors.js.map +1 -0
  118. package/dist/machine/index.d.ts +3 -0
  119. package/dist/machine/index.d.ts.map +1 -0
  120. package/dist/machine/index.js +156 -0
  121. package/dist/machine/index.js.map +1 -0
  122. package/dist/mcp/index.d.ts +25 -0
  123. package/dist/mcp/index.d.ts.map +1 -0
  124. package/dist/mcp/index.js +184 -0
  125. package/dist/mcp/index.js.map +1 -0
  126. package/dist/types/index.d.ts +65 -0
  127. package/dist/types/index.d.ts.map +1 -1
  128. package/dist/utils/package-manager.d.ts +109 -0
  129. package/dist/utils/package-manager.d.ts.map +1 -0
  130. package/dist/utils/package-manager.js +215 -0
  131. package/dist/utils/package-manager.js.map +1 -0
  132. package/package.json +85 -73
  133. package/src/__tests__/__snapshots__/functions-generator.test.ts.snap +1139 -0
  134. package/src/__tests__/__snapshots__/nextjs-generator.test.ts.snap +194 -0
  135. package/src/__tests__/__snapshots__/ui-generator.test.ts.snap +532 -0
  136. package/src/__tests__/auth.test.ts +654 -0
  137. package/src/__tests__/config.test.ts +263 -0
  138. package/src/__tests__/connector-functions-generator.test.ts +288 -0
  139. package/src/__tests__/connector-mock-server.test.ts +439 -0
  140. package/src/__tests__/connector-model-bff.test.ts +162 -0
  141. package/src/__tests__/dev-seeds.test.ts +112 -0
  142. package/src/__tests__/dev.test.ts +148 -0
  143. package/src/__tests__/fixtures.ts +144 -0
  144. package/src/__tests__/functions-generator.test.ts +237 -0
  145. package/src/__tests__/init.test.ts +80 -0
  146. package/src/__tests__/machine.test.ts +212 -0
  147. package/src/__tests__/mcp.test.ts +56 -0
  148. package/src/__tests__/model-parser.test.ts +72 -0
  149. package/src/__tests__/nextjs-generator.test.ts +97 -0
  150. package/src/__tests__/openapi-generator.test.ts +43 -0
  151. package/src/__tests__/package-manager.test.ts +189 -0
  152. package/src/__tests__/scaffold.test.ts +39 -0
  153. package/src/__tests__/string-utils.test.ts +75 -0
  154. package/src/__tests__/ui-generator.test.ts +144 -0
  155. package/src/__tests__/zod-mock-generator.test.ts +132 -0
  156. package/src/cli/commands/add-auth.ts +500 -0
  157. package/src/cli/commands/add-connector.ts +158 -0
  158. package/src/cli/commands/create-model.ts +62 -0
  159. package/src/cli/commands/dev-seeds.ts +358 -0
  160. package/src/cli/commands/dev.ts +962 -0
  161. package/src/cli/commands/index.ts +9 -0
  162. package/src/cli/commands/init.ts +3371 -0
  163. package/src/cli/commands/provision.ts +193 -0
  164. package/src/cli/commands/scaffold.ts +1211 -0
  165. package/src/cli/index.ts +191 -0
  166. package/src/core/config.ts +308 -0
  167. package/src/core/mock/connector-mock-server.ts +555 -0
  168. package/src/core/mock/zod-mock-generator.ts +205 -0
  169. package/src/core/operations/create-model.ts +174 -0
  170. package/src/core/operations/runtime.ts +235 -0
  171. package/src/core/operations/scaffold-machine.ts +91 -0
  172. package/src/core/project/manifest.ts +402 -0
  173. package/src/core/project/validation.ts +221 -0
  174. package/src/core/scaffold/auth-generator.ts +1284 -0
  175. package/src/core/scaffold/connector-functions-generator.ts +1128 -0
  176. package/src/core/scaffold/functions-generator.ts +970 -0
  177. package/src/core/scaffold/model-parser.ts +841 -0
  178. package/src/core/scaffold/nextjs-generator.ts +370 -0
  179. package/src/core/scaffold/openapi-generator.ts +212 -0
  180. package/src/core/scaffold/ui-generator.ts +1061 -0
  181. package/src/database/base-model.ts +184 -0
  182. package/src/database/client.ts +140 -0
  183. package/src/database/repository.ts +104 -0
  184. package/src/database/runtime-check.ts +25 -0
  185. package/src/index.ts +27 -0
  186. package/src/machine/contracts.ts +17 -0
  187. package/src/machine/errors.ts +34 -0
  188. package/src/machine/index.ts +173 -0
  189. package/src/mcp/index.ts +185 -0
  190. package/src/types/index.ts +134 -0
  191. package/src/utils/package-manager.ts +229 -0
@@ -0,0 +1,3371 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { spawn, execSync } from "child_process";
4
+ import prompts from "prompts";
5
+ import { BackendLanguage } from "../../types";
6
+ import {
7
+ type PackageManager,
8
+ detectFromUserAgent,
9
+ getCommands,
10
+ getWorkspaceConfig,
11
+ getCiSetupStep,
12
+ getAzurePipelinesSetup,
13
+ getBuildScript,
14
+ getFunctionsPrestart,
15
+ getFunctionsStartScript,
16
+ } from "../../utils/package-manager";
17
+ import { syncProjectManifest } from "../../core/project/manifest";
18
+
19
+ interface InitOptions {
20
+ name: string;
21
+ template: string;
22
+ nextVersion?: string;
23
+ cicd?: CiCdProvider;
24
+ backendLanguage?: BackendLanguage;
25
+ cosmosDbMode?: CosmosDbMode;
26
+ vnet?: VNetOption;
27
+ }
28
+
29
+ type CiCdProvider = 'github' | 'azure' | 'skip';
30
+ type CosmosDbMode = 'freetier' | 'serverless';
31
+ type VNetOption = 'none' | 'outbound';
32
+
33
+ interface AzureConfig {
34
+ cosmosDbMode: CosmosDbMode;
35
+ vnetOption: VNetOption;
36
+ }
37
+
38
+ const BACKEND_LANGUAGE_CHOICES: Array<{ title: string; value: BackendLanguage }> = [
39
+ { title: "TypeScript", value: "typescript" },
40
+ { title: "C#", value: "csharp" },
41
+ { title: "Python", value: "python" },
42
+ ];
43
+
44
+ function usesNodeFunctionsProject(backendLanguage: BackendLanguage): boolean {
45
+ return backendLanguage === "typescript";
46
+ }
47
+
48
+ function getBackendLanguageLabel(backendLanguage: BackendLanguage): string {
49
+ return BACKEND_LANGUAGE_CHOICES.find((choice) => choice.value === backendLanguage)?.title || backendLanguage;
50
+ }
51
+
52
+ function getFunctionsWorkerRuntime(backendLanguage: BackendLanguage): string {
53
+ if (backendLanguage === "csharp") {
54
+ return "dotnet-isolated";
55
+ }
56
+ if (backendLanguage === "python") {
57
+ return "python";
58
+ }
59
+ return "node";
60
+ }
61
+
62
+ function getFunctionsRuntimeConfig(backendLanguage: BackendLanguage): { name: string; version: string } {
63
+ if (backendLanguage === "csharp") {
64
+ return { name: "dotnet-isolated", version: "8.0" };
65
+ }
66
+ if (backendLanguage === "python") {
67
+ return { name: "python", version: "3.11" };
68
+ }
69
+ return { name: "node", version: "22" };
70
+ }
71
+
72
+ async function promptBackendLanguage(): Promise<BackendLanguage> {
73
+ const response = await prompts({
74
+ type: "select",
75
+ name: "backendLanguage",
76
+ message: "Azure Functions backend language:",
77
+ choices: BACKEND_LANGUAGE_CHOICES,
78
+ initial: 0,
79
+ });
80
+
81
+ return response.backendLanguage || "typescript";
82
+ }
83
+
84
+ async function promptCiCd(): Promise<CiCdProvider> {
85
+ const response = await prompts({
86
+ type: 'select',
87
+ name: 'cicd',
88
+ message: 'CI/CD Setup (choose deployment automation):',
89
+ choices: [
90
+ { title: 'GitHub Actions', value: 'github' },
91
+ { title: 'Azure Pipelines', value: 'azure' },
92
+ { title: 'Skip (manual deployment)', value: 'skip' }
93
+ ],
94
+ initial: 0
95
+ });
96
+
97
+ return response.cicd || 'skip';
98
+ }
99
+
100
+ async function promptAzureConfig(): Promise<AzureConfig> {
101
+ const cosmosResponse = await prompts({
102
+ type: 'select',
103
+ name: 'mode',
104
+ message: 'Cosmos DB mode (affects cost):',
105
+ choices: [
106
+ { title: 'Free Tier (1000 RU/s free, best for first project)', value: 'freetier' },
107
+ { title: 'Serverless (pay-per-use, flexible)', value: 'serverless' }
108
+ ],
109
+ initial: 0
110
+ });
111
+
112
+ const vnetResponse = await prompts({
113
+ type: 'select',
114
+ name: 'vnet',
115
+ message: 'Network security:',
116
+ choices: [
117
+ { title: 'VNet Integration (recommended) - Cosmos DB via Private Endpoint', value: 'outbound' },
118
+ { title: 'None - Public endpoints, simplest but least secure', value: 'none' }
119
+ ],
120
+ initial: 0
121
+ });
122
+
123
+ return {
124
+ cosmosDbMode: cosmosResponse.mode || 'freetier',
125
+ vnetOption: vnetResponse.vnet || 'outbound'
126
+ };
127
+ }
128
+
129
+ const VALID_CICD: CiCdProvider[] = ['github', 'azure', 'skip'];
130
+ const VALID_BACKEND_LANGUAGE: BackendLanguage[] = ['typescript', 'csharp', 'python'];
131
+ const VALID_COSMOS_DB_MODE: CosmosDbMode[] = ['freetier', 'serverless'];
132
+ const VALID_VNET: VNetOption[] = ['none', 'outbound'];
133
+
134
+ function validateInitFlags(options: InitOptions): void {
135
+ if (options.cicd && !VALID_CICD.includes(options.cicd)) {
136
+ console.error(`❌ Invalid --cicd value: "${options.cicd}". Must be: ${VALID_CICD.join(', ')}`);
137
+ process.exit(1);
138
+ }
139
+ if (options.backendLanguage && !VALID_BACKEND_LANGUAGE.includes(options.backendLanguage)) {
140
+ console.error(`❌ Invalid --backend-language value: "${options.backendLanguage}". Must be: ${VALID_BACKEND_LANGUAGE.join(', ')}`);
141
+ process.exit(1);
142
+ }
143
+ if (options.cosmosDbMode && !VALID_COSMOS_DB_MODE.includes(options.cosmosDbMode)) {
144
+ console.error(`❌ Invalid --cosmos-db-mode value: "${options.cosmosDbMode}". Must be: ${VALID_COSMOS_DB_MODE.join(', ')}`);
145
+ process.exit(1);
146
+ }
147
+ if (options.vnet && !VALID_VNET.includes(options.vnet)) {
148
+ console.error(`❌ Invalid --vnet value: "${options.vnet}". Must be: ${VALID_VNET.join(', ')}`);
149
+ process.exit(1);
150
+ }
151
+ }
152
+
153
+ export async function initCommand(options: InitOptions) {
154
+ // Validate flag values before doing anything
155
+ validateInitFlags(options);
156
+
157
+ console.log(`🚀 Initializing SwallowKit project: ${options.name}`);
158
+ console.log(`📋 Template: ${options.template}`);
159
+
160
+ // Detect package manager from invocation context (npx → npm, pnpm dlx → pnpm)
161
+ const pm: PackageManager = detectFromUserAgent();
162
+ const pmCmd = getCommands(pm);
163
+ console.log(`📦 Package manager: ${pm}`);
164
+
165
+ const projectDir = path.join(process.cwd(), options.name);
166
+
167
+ try {
168
+ // Check if directory already exists
169
+ if (fs.existsSync(projectDir)) {
170
+ console.error(`❌ Directory "${options.name}" already exists.`);
171
+ process.exit(1);
172
+ }
173
+
174
+ // Use flag values if provided, otherwise prompt interactively
175
+ const cicdProvider: CiCdProvider = options.cicd || await promptCiCd();
176
+ const backendLanguage: BackendLanguage = options.backendLanguage || await promptBackendLanguage();
177
+
178
+ const azureConfig: AzureConfig = (options.cosmosDbMode && options.vnet)
179
+ ? { cosmosDbMode: options.cosmosDbMode, vnetOption: options.vnet }
180
+ : await promptAzureConfig();
181
+
182
+ // Create Next.js project with create-next-app
183
+ await createNextJsProject(options.name, pm);
184
+
185
+ // Upgrade Next.js to specified version (or latest) to avoid cached old versions
186
+ await upgradeNextJs(projectDir, options.nextVersion || 'latest', pm);
187
+
188
+ // Add SwallowKit specific files
189
+ await addSwallowKitFiles(projectDir, options, cicdProvider, azureConfig, pm, backendLanguage);
190
+
191
+ // Create infrastructure files (Bicep)
192
+ await createInfrastructure(projectDir, options.name, azureConfig, backendLanguage);
193
+
194
+ // Create CI/CD files based on choice
195
+ if (cicdProvider === 'github') {
196
+ await createGitHubActionsWorkflows(projectDir, azureConfig, pm, backendLanguage);
197
+ } else if (cicdProvider === 'azure') {
198
+ await createAzurePipelines(projectDir, pm, backendLanguage);
199
+ }
200
+
201
+ await syncProjectManifest(projectDir);
202
+
203
+ // Initialize Git repository and create initial commit
204
+ try {
205
+ // Try git init with -b main (Git 2.28+), fallback to git init
206
+ try {
207
+ execSync('git init -b main', { cwd: projectDir, stdio: 'ignore' });
208
+ } catch {
209
+ // Fallback for older Git versions
210
+ execSync('git init', { cwd: projectDir, stdio: 'ignore' });
211
+ }
212
+
213
+ // Configure git user if not set (required for commits)
214
+ try {
215
+ execSync('git config user.name', { cwd: projectDir, stdio: 'pipe' });
216
+ execSync('git config user.email', { cwd: projectDir, stdio: 'pipe' });
217
+ } catch {
218
+ // Not configured globally, set locally for this repository
219
+ execSync('git config user.name "SwallowKit"', { cwd: projectDir, stdio: 'ignore' });
220
+ execSync('git config user.email "swallowkit@example.com"', { cwd: projectDir, stdio: 'ignore' });
221
+ }
222
+
223
+ execSync('git add -A', { cwd: projectDir, stdio: 'ignore' });
224
+ execSync('git commit -m "Initial commit from SwallowKit"', { cwd: projectDir, stdio: 'ignore' });
225
+
226
+ // Rename branch to main if git init -b main didn't work
227
+ try {
228
+ const currentBranch = execSync('git branch --show-current', { cwd: projectDir, encoding: 'utf-8' }).trim();
229
+ if (currentBranch !== 'main') {
230
+ execSync('git branch -M main', { cwd: projectDir, stdio: 'ignore' });
231
+ }
232
+ } catch {
233
+ // Ignore errors - branch renaming is not critical
234
+ }
235
+
236
+ console.log('✅ Git repository initialized with initial commit\n');
237
+ } catch (error) {
238
+ console.warn('⚠️ Could not initialize Git repository (is git installed?)');
239
+ if (error instanceof Error) {
240
+ console.warn(` Error: ${error.message}`);
241
+ }
242
+ }
243
+
244
+ console.log(`\n✅ Project "${options.name}" created successfully!`);
245
+ console.log("\n📝 Next steps:");
246
+ console.log(` cd ${options.name}`);
247
+ console.log(` ${pmCmd.dlx} swallowkit create-model <name> # Create your first model`);
248
+ console.log(` ${pmCmd.dlx} swallowkit scaffold shared/models/<name>.ts # Generate CRUD code`);
249
+ console.log(` ${pmCmd.dlx} swallowkit dev # Start development servers`);
250
+ console.log("\n🚀 Deploy to Azure:");
251
+ console.log(` ${pmCmd.dlx} swallowkit provision --resource-group <name>`);
252
+ if (cicdProvider !== 'skip') {
253
+ console.log(" Configure CI/CD secrets and push to repository");
254
+ }
255
+ } catch (error) {
256
+ console.error("❌ Project creation failed:", error);
257
+ // Clean up on failure
258
+ if (fs.existsSync(projectDir)) {
259
+ fs.rmSync(projectDir, { recursive: true, force: true });
260
+ }
261
+ process.exit(1);
262
+ }
263
+ }
264
+
265
+ async function createNextJsProject(projectName: string, pm: PackageManager): Promise<void> {
266
+ return new Promise((resolve, reject) => {
267
+ console.log('\n📦 Creating Next.js project with create-next-app...\n');
268
+
269
+ const pmCmd = getCommands(pm);
270
+
271
+ // Build args: for pnpm use "pnpm dlx create-next-app@latest ... --use-pnpm"
272
+ // for npm use "npx create-next-app@latest ..."
273
+ const baseArgs = pm === 'pnpm'
274
+ ? ['dlx', 'create-next-app@latest']
275
+ : ['create-next-app@latest'];
276
+
277
+ const args = [
278
+ ...baseArgs,
279
+ projectName,
280
+ '--typescript',
281
+ '--tailwind',
282
+ '--app',
283
+ '--no-src',
284
+ '--disable-git',
285
+ '--import-alias',
286
+ '@/*',
287
+ ...(pmCmd.createNextAppFlag ? [pmCmd.createNextAppFlag] : []),
288
+ '--yes'
289
+ ];
290
+
291
+ // Run create-next-app with recommended options for Azure
292
+ const createNextApp = spawn(
293
+ pm === 'pnpm' ? 'pnpm' : 'npx',
294
+ args,
295
+ {
296
+ stdio: 'inherit',
297
+ shell: true,
298
+ }
299
+ );
300
+
301
+ createNextApp.on('close', (code: number | null) => {
302
+ if (code !== 0) {
303
+ reject(new Error(`create-next-app exited with code ${code}`));
304
+ } else {
305
+ console.log('\n✅ Next.js project created\n');
306
+ resolve();
307
+ }
308
+ });
309
+
310
+ createNextApp.on('error', (error: Error) => {
311
+ reject(error);
312
+ });
313
+ });
314
+ }
315
+
316
+ async function upgradeNextJs(projectDir: string, version: string, pm: PackageManager): Promise<void> {
317
+ return new Promise((resolve, reject) => {
318
+ console.log(`\n📦 Installing Next.js ${version} (to ensure latest security patches)...\n`);
319
+
320
+ // pnpm: pnpm add next@... ; npm: npm install next@...
321
+ const args = pm === 'pnpm'
322
+ ? ['add', `next@${version}`, `react@latest`, `react-dom@latest`, '--save-exact']
323
+ : ['install', `next@${version}`, `react@latest`, `react-dom@latest`, '--save-exact'];
324
+
325
+ const child = spawn(
326
+ pm,
327
+ args,
328
+ {
329
+ cwd: projectDir,
330
+ stdio: 'inherit',
331
+ shell: true,
332
+ }
333
+ );
334
+
335
+ child.on('close', (code: number | null) => {
336
+ if (code !== 0) {
337
+ reject(new Error(`${pm} add next@${version} exited with code ${code}`));
338
+ } else {
339
+ console.log(`\n✅ Next.js ${version} installed\n`);
340
+ resolve();
341
+ }
342
+ });
343
+
344
+ child.on('error', (error: Error) => {
345
+ reject(error);
346
+ });
347
+ });
348
+ }
349
+
350
+ async function installDependencies(projectDir: string, pm: PackageManager = 'pnpm'): Promise<void> {
351
+ return new Promise((resolve, reject) => {
352
+ console.log('\n📦 Installing dependencies...\n');
353
+
354
+ const child = spawn(
355
+ pm,
356
+ ['install'],
357
+ {
358
+ cwd: projectDir,
359
+ stdio: 'inherit',
360
+ shell: true,
361
+ }
362
+ );
363
+
364
+ child.on('close', (code: number | null) => {
365
+ if (code !== 0) {
366
+ reject(new Error(`${pm} install exited with code ${code}`));
367
+ } else {
368
+ console.log('\n✅ Dependencies installed\n');
369
+ resolve();
370
+ }
371
+ });
372
+
373
+ child.on('error', (error: Error) => {
374
+ reject(error);
375
+ });
376
+ });
377
+ }
378
+
379
+ export function injectSwallowKitNextConfig(nextConfigContent: string, projectName: string): string {
380
+ return nextConfigContent.replace(
381
+ /(const\s+nextConfig[:\s]*(?::\s*NextConfig\s*)?=\s*\{)(\s*\/\*[^*]*\*\/)?/,
382
+ `$1\n output: 'standalone',\n transpilePackages: ['@${projectName}/shared'],\n serverExternalPackages: ['applicationinsights', 'diagnostic-channel-publishers'],$2`
383
+ );
384
+ }
385
+
386
+ export function buildCSharpFunctionsProgramSource(): string {
387
+ return `using Microsoft.Extensions.DependencyInjection;
388
+ using Microsoft.Extensions.Hosting;
389
+
390
+ var host = new HostBuilder()
391
+ .ConfigureFunctionsWorkerDefaults()
392
+ .ConfigureServices(services =>
393
+ {
394
+ services.AddApplicationInsightsTelemetryWorkerService();
395
+ })
396
+ .Build();
397
+
398
+ host.Run();
399
+ `;
400
+ }
401
+
402
+ export function buildCSharpFunctionsProjectSource(): string {
403
+ return `<Project Sdk="Microsoft.NET.Sdk">
404
+ <PropertyGroup>
405
+ <TargetFramework>net8.0</TargetFramework>
406
+ <AzureFunctionsVersion>v4</AzureFunctionsVersion>
407
+ <OutputType>Exe</OutputType>
408
+ <ImplicitUsings>enable</ImplicitUsings>
409
+ <Nullable>enable</Nullable>
410
+ </PropertyGroup>
411
+ <ItemGroup>
412
+ <Compile Remove="generated\\**\\bin\\**\\*.cs;generated\\**\\obj\\**\\*.cs" />
413
+ <EmbeddedResource Remove="generated\\**\\bin\\**;generated\\**\\obj\\**" />
414
+ <None Remove="generated\\**\\bin\\**;generated\\**\\obj\\**" />
415
+ </ItemGroup>
416
+ <ItemGroup>
417
+ <PackageReference Include="Microsoft.Azure.Cosmos" Version="3.47.0" />
418
+ <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
419
+ <PackageReference Include="Azure.Identity" Version="1.13.2" />
420
+ <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.23.0" />
421
+ <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.2.0" />
422
+ <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.18.0" OutputItemType="Analyzer" />
423
+ <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
424
+ <PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.2.0" />
425
+ </ItemGroup>
426
+ </Project>
427
+ `;
428
+ }
429
+
430
+ export function buildSwallowKitConfigSource(backendLanguage: BackendLanguage): string {
431
+ return `module.exports = {
432
+ backend: {
433
+ language: '${backendLanguage}',
434
+ },
435
+ functions: {
436
+ baseUrl: process.env.BACKEND_FUNCTIONS_BASE_URL || process.env.FUNCTIONS_BASE_URL || 'http://localhost:7071',
437
+ },
438
+ deployment: {
439
+ resourceGroup: process.env.AZURE_RESOURCE_GROUP || '',
440
+ swaName: process.env.AZURE_SWA_NAME || '',
441
+ },
442
+ }
443
+ `;
444
+ }
445
+
446
+ export function buildGeneratedProjectDependencies(projectName: string): Record<string, string> {
447
+ return {
448
+ '@azure/cosmos': '^4.0.0',
449
+ 'applicationinsights': '^3.3.0',
450
+ [`@${projectName}/shared`]: '*',
451
+ };
452
+ }
453
+
454
+ async function addSwallowKitFiles(
455
+ projectDir: string,
456
+ options: InitOptions,
457
+ cicdChoice: string,
458
+ azureConfig: AzureConfig,
459
+ pm: PackageManager,
460
+ backendLanguage: BackendLanguage
461
+ ) {
462
+ console.log('📦 Adding SwallowKit files...\n');
463
+
464
+ const projectName = options.name;
465
+
466
+ // 1. Update package.json to add runtime dependencies for generated projects
467
+ const packageJsonPath = path.join(projectDir, 'package.json');
468
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
469
+
470
+ // zod is in the shared workspace package, not here
471
+ packageJson.dependencies = {
472
+ ...packageJson.dependencies,
473
+ ...buildGeneratedProjectDependencies(projectName),
474
+ };
475
+
476
+ if (backendLanguage !== "typescript") {
477
+ packageJson.devDependencies = {
478
+ ...packageJson.devDependencies,
479
+ '@openapitools/openapi-generator-cli': '^2.21.0',
480
+ };
481
+ }
482
+
483
+ packageJson.scripts = {
484
+ ...packageJson.scripts,
485
+ 'build': getBuildScript(pm),
486
+ 'start': 'next start',
487
+ 'functions:start': getFunctionsStartScript(pm, backendLanguage),
488
+ };
489
+
490
+ if (pm === 'pnpm') {
491
+ packageJson.packageManager = 'pnpm@latest';
492
+ }
493
+
494
+ packageJson.engines = {
495
+ node: '20.x',
496
+ };
497
+
498
+ // Workspace configuration depends on package manager
499
+ const workspacePackages = usesNodeFunctionsProject(backendLanguage) ? ['shared', 'functions'] : ['shared'];
500
+ const wsConfig = getWorkspaceConfig(pm, workspacePackages);
501
+ if (wsConfig.type === 'file') {
502
+ // pnpm: workspaces are defined in pnpm-workspace.yaml
503
+ delete packageJson.workspaces;
504
+ } else {
505
+ // npm: workspaces are defined in package.json
506
+ packageJson.workspaces = wsConfig.value;
507
+ }
508
+
509
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
510
+
511
+ // Create workspace config file if needed (pnpm-workspace.yaml)
512
+ if (wsConfig.type === 'file') {
513
+ fs.writeFileSync(path.join(projectDir, wsConfig.filename), wsConfig.content);
514
+ }
515
+
516
+ // Don't install yet — wait until all workspace packages (shared, functions) are created
517
+
518
+ // 2. Update next.config to add standalone output
519
+ // Check for both .ts and .js variants
520
+ let nextConfigPath = path.join(projectDir, 'next.config.ts');
521
+ if (!fs.existsSync(nextConfigPath)) {
522
+ nextConfigPath = path.join(projectDir, 'next.config.js');
523
+ }
524
+
525
+ if (fs.existsSync(nextConfigPath)) {
526
+ let nextConfigContent = fs.readFileSync(nextConfigPath, 'utf-8');
527
+
528
+ // Add output, transpiled workspace package, and server externals for standalone deployment
529
+ if (!nextConfigContent.includes("output:") && !nextConfigContent.includes('output =')) {
530
+ nextConfigContent = injectSwallowKitNextConfig(nextConfigContent, projectName);
531
+ fs.writeFileSync(nextConfigPath, nextConfigContent);
532
+ }
533
+ }
534
+
535
+ // 3. Update tsconfig.json to exclude functions directory
536
+ const tsconfigPath = path.join(projectDir, 'tsconfig.json');
537
+ if (fs.existsSync(tsconfigPath)) {
538
+ const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf-8'));
539
+ if (!tsconfig.exclude) {
540
+ tsconfig.exclude = [];
541
+ }
542
+ if (!tsconfig.exclude.includes('functions')) {
543
+ tsconfig.exclude.push('functions');
544
+ }
545
+ if (!tsconfig.exclude.includes('shared')) {
546
+ tsconfig.exclude.push('shared');
547
+ }
548
+ fs.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2));
549
+ }
550
+
551
+ // 3. Create SwallowKit config
552
+ const swallowkitConfig = buildSwallowKitConfigSource(backendLanguage);
553
+ fs.writeFileSync(path.join(projectDir, 'swallowkit.config.js'), swallowkitConfig);
554
+
555
+ // 4. Create shared workspace package for Zod models (Single Source of Truth)
556
+ await createSharedPackage(projectDir, projectName);
557
+
558
+ // Create lib directory for Next.js-specific utilities
559
+ const libDir = path.join(projectDir, 'lib');
560
+
561
+ // Create lib/api directory for backend utilities
562
+ const apiLibDir = path.join(libDir, 'api');
563
+ fs.mkdirSync(apiLibDir, { recursive: true });
564
+
565
+ // Create backend utility for calling Azure Functions
566
+ const backendUtilContent = `// Get Functions base URL at runtime (not at build time)
567
+ function getFunctionsBaseUrl(): string {
568
+ return process.env.BACKEND_FUNCTIONS_BASE_URL || process.env.FUNCTIONS_BASE_URL || 'http://localhost:7071';
569
+ }
570
+
571
+ /**
572
+ * Simple HTTP client for calling backend APIs
573
+ * Use this to make requests to BFF API routes (which forward to Azure Functions)
574
+ */
575
+ async function request<T>(
576
+ endpoint: string,
577
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE',
578
+ body?: any,
579
+ queryParams?: Record<string, string>
580
+ ): Promise<T> {
581
+ const functionsBaseUrl = getFunctionsBaseUrl();
582
+ let url = \`\${functionsBaseUrl}\${endpoint}\`;
583
+ if (queryParams) {
584
+ const params = new URLSearchParams(queryParams);
585
+ url += \`?\${params.toString()}\`;
586
+ }
587
+
588
+ try {
589
+ const response = await fetch(url, {
590
+ method,
591
+ headers: {
592
+ 'Content-Type': 'application/json',
593
+ },
594
+ body: body ? JSON.stringify(body) : undefined,
595
+ });
596
+
597
+ if (!response.ok) {
598
+ const text = await response.text();
599
+ let errorMessage = text || 'Failed to call backend function';
600
+ try {
601
+ const error = JSON.parse(text);
602
+ errorMessage = error.error || error.message || text;
603
+ } catch {
604
+ // If not JSON, use text as-is
605
+ }
606
+ throw new Error(errorMessage);
607
+ }
608
+
609
+ const contentType = response.headers.get('content-type');
610
+ if (!contentType?.includes('application/json')) {
611
+ const text = await response.text();
612
+ return text as T;
613
+ }
614
+
615
+ return await response.json();
616
+ } catch (error) {
617
+ console.error('Error calling backend:', error);
618
+ throw error;
619
+ }
620
+ }
621
+
622
+ /**
623
+ * Generic API client for making HTTP requests
624
+ * Simply calls endpoints - no DB dependencies, no schema validation
625
+ * Validation happens on the backend (BFF/Functions)
626
+ *
627
+ * @example
628
+ * // Call custom endpoint
629
+ * await api.get('/api/greet?name=World')
630
+ *
631
+ * // Call scaffolded CRUD endpoints
632
+ * await api.get('/api/todos')
633
+ * await api.post('/api/todos', { title: 'New task' })
634
+ * await api.put('/api/todos/123', { title: 'Updated' })
635
+ * await api.delete('/api/todos/123')
636
+ */
637
+ export const api = {
638
+ /**
639
+ * Make a GET request
640
+ */
641
+ get: <T>(endpoint: string, params?: Record<string, string>): Promise<T> => {
642
+ return request<T>(endpoint, 'GET', undefined, params);
643
+ },
644
+
645
+ /**
646
+ * Make a POST request
647
+ */
648
+ post: <T>(endpoint: string, body?: any): Promise<T> => {
649
+ return request<T>(endpoint, 'POST', body);
650
+ },
651
+
652
+ /**
653
+ * Make a PUT request
654
+ */
655
+ put: <T>(endpoint: string, body?: any): Promise<T> => {
656
+ return request<T>(endpoint, 'PUT', body);
657
+ },
658
+
659
+ /**
660
+ * Make a DELETE request
661
+ */
662
+ delete: <T>(endpoint: string): Promise<T> => {
663
+ return request<T>(endpoint, 'DELETE');
664
+ },
665
+ };
666
+ `;
667
+ fs.writeFileSync(path.join(apiLibDir, 'backend.ts'), backendUtilContent);
668
+
669
+ // 5. Create components directory
670
+ const componentsDir = path.join(projectDir, 'components');
671
+ fs.mkdirSync(componentsDir, { recursive: true });
672
+
673
+ // 6. Create .env.example
674
+ const envExample = `# Azure Functions Backend URL
675
+ BACKEND_FUNCTIONS_BASE_URL=http://localhost:7071
676
+
677
+ # Azure Configuration
678
+ AZURE_RESOURCE_GROUP=your-resource-group
679
+ AZURE_SWA_NAME=your-static-web-app-name
680
+ `;
681
+ fs.writeFileSync(path.join(projectDir, '.env.example'), envExample);
682
+
683
+ // 7. Create instrumentation.ts for Application Insights (Next.js official way)
684
+ const instrumentationContent = `// Application Insights instrumentation for Next.js
685
+ // This file is automatically loaded by Next.js when instrumentationHook is enabled
686
+ export async function register() {
687
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
688
+ // Only run on server-side
689
+ const connectionString = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING;
690
+
691
+ if (connectionString) {
692
+ const appInsights = await import('applicationinsights');
693
+
694
+ appInsights
695
+ .setup(connectionString)
696
+ .setAutoCollectConsole(true)
697
+ .setAutoCollectDependencies(true)
698
+ .setAutoCollectExceptions(true)
699
+ .setAutoCollectHeartbeat(true)
700
+ .setAutoCollectPerformance(true, true)
701
+ .setAutoCollectRequests(true)
702
+ .setAutoDependencyCorrelation(true)
703
+ .setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C)
704
+ .setSendLiveMetrics(true)
705
+ .setUseDiskRetryCaching(true);
706
+
707
+ appInsights.defaultClient.setAutoPopulateAzureProperties();
708
+ appInsights.start();
709
+
710
+ // Override console methods to send to Application Insights
711
+ const originalConsoleLog = console.log;
712
+ const originalConsoleError = console.error;
713
+ const originalConsoleWarn = console.warn;
714
+
715
+ console.log = function(...args: any[]) {
716
+ originalConsoleLog.apply(console, args);
717
+ const message = args.map(arg =>
718
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
719
+ ).join(' ');
720
+ appInsights.defaultClient.trackTrace({
721
+ message: message,
722
+ severity: '1'
723
+ });
724
+ };
725
+
726
+ console.error = function(...args: any[]) {
727
+ originalConsoleError.apply(console, args);
728
+ const message = args.map(arg =>
729
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
730
+ ).join(' ');
731
+ appInsights.defaultClient.trackTrace({
732
+ message: message,
733
+ severity: '3'
734
+ });
735
+ };
736
+
737
+ console.warn = function(...args: any[]) {
738
+ originalConsoleWarn.apply(console, args);
739
+ const message = args.map(arg =>
740
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
741
+ ).join(' ');
742
+ appInsights.defaultClient.trackTrace({
743
+ message: message,
744
+ severity: '2'
745
+ });
746
+ };
747
+
748
+ console.log('[App Insights] Initialized for Next.js server-side telemetry with console override');
749
+ } else {
750
+ console.log('[App Insights] Not configured (skipped in development mode)');
751
+ }
752
+ }
753
+ }
754
+ `;
755
+ fs.writeFileSync(path.join(projectDir, 'instrumentation.ts'), instrumentationContent);
756
+
757
+ // 8. Create .env.local for local development
758
+ const envLocalContent = [
759
+ '# Azure Functions Backend URL (Local)',
760
+ 'BACKEND_FUNCTIONS_BASE_URL=http://localhost:7071',
761
+ ''
762
+ ].join('\n');
763
+ fs.writeFileSync(path.join(projectDir, '.env.local'), envLocalContent);
764
+
765
+ // 8. Create staticwebapp.config.json for Azure Static Web Apps (Next.js Hybrid Rendering)
766
+ const swaConfig = {
767
+ platform: {
768
+ apiRuntime: "node:20"
769
+ },
770
+ routes: [
771
+ {
772
+ route: "/*",
773
+ allowedRoles: ["anonymous"]
774
+ }
775
+ ],
776
+ globalHeaders: {
777
+ "X-Content-Type-Options": "nosniff",
778
+ "X-Frame-Options": "DENY",
779
+ "X-XSS-Protection": "1; mode=block"
780
+ },
781
+ mimeTypes: {
782
+ ".json": "application/json"
783
+ }
784
+ };
785
+ fs.writeFileSync(
786
+ path.join(projectDir, 'staticwebapp.config.json'),
787
+ JSON.stringify(swaConfig, null, 2)
788
+ );
789
+
790
+ // 14. Create Azure Functions project
791
+ await createAzureFunctionsProject(projectDir, pm, backendLanguage);
792
+
793
+ // 15. Create BFF API route to call Azure Functions
794
+ await createBffApiRoute(projectDir);
795
+
796
+ // 16. Create home page
797
+ await createHomePage(projectDir, pm);
798
+
799
+ // 17. Install all workspace dependencies (root + shared + functions)
800
+ console.log('📦 Installing workspace dependencies...\n');
801
+ await installDependencies(projectDir, pm);
802
+
803
+ console.log('✅ Project structure created\n');
804
+
805
+ // 18. Create README.md
806
+ createReadme(projectDir, projectName, cicdChoice, azureConfig, pm, backendLanguage);
807
+
808
+ // 19. Create AI agent instruction files (AGENTS.md, CLAUDE.md, .github/copilot-instructions.md, etc.)
809
+ createAiAgentFiles(projectDir, projectName, backendLanguage);
810
+ }
811
+
812
+ async function createSharedPackage(projectDir: string, projectName: string) {
813
+ console.log('📦 Creating shared workspace package for Zod models...\n');
814
+
815
+ const sharedDir = path.join(projectDir, 'shared');
816
+ const modelsDir = path.join(sharedDir, 'models');
817
+ fs.mkdirSync(modelsDir, { recursive: true });
818
+
819
+ // shared/package.json
820
+ const sharedPackageJson = {
821
+ name: `@${projectName}/shared`,
822
+ version: '1.0.0',
823
+ description: 'Shared Zod models — Single Source of Truth for validation schemas',
824
+ main: 'dist/index.js',
825
+ types: 'dist/index.d.ts',
826
+ scripts: {
827
+ build: 'tsc',
828
+ watch: 'tsc --watch',
829
+ },
830
+ dependencies: {
831
+ 'zod': '>=3.25.0',
832
+ },
833
+ devDependencies: {
834
+ 'typescript': '^5.0.0',
835
+ },
836
+ };
837
+ fs.writeFileSync(
838
+ path.join(sharedDir, 'package.json'),
839
+ JSON.stringify(sharedPackageJson, null, 2)
840
+ );
841
+
842
+ // shared/tsconfig.json
843
+ const sharedTsConfig = {
844
+ compilerOptions: {
845
+ target: 'ES2020',
846
+ module: 'commonjs',
847
+ moduleResolution: 'node',
848
+ lib: ['ES2020'],
849
+ outDir: 'dist',
850
+ rootDir: '.',
851
+ declaration: true,
852
+ declarationMap: true,
853
+ sourceMap: true,
854
+ strict: true,
855
+ esModuleInterop: true,
856
+ skipLibCheck: true,
857
+ forceConsistentCasingInFileNames: true,
858
+ },
859
+ include: ['index.ts', 'models/**/*'],
860
+ exclude: ['node_modules', 'dist'],
861
+ };
862
+ fs.writeFileSync(
863
+ path.join(sharedDir, 'tsconfig.json'),
864
+ JSON.stringify(sharedTsConfig, null, 2)
865
+ );
866
+
867
+ // shared/index.ts (empty re-export file, scaffold will add entries)
868
+ fs.writeFileSync(
869
+ path.join(sharedDir, 'index.ts'),
870
+ `// Shared Zod models — auto-managed by SwallowKit scaffold command\n// Do not edit the export list below manually\n`
871
+ );
872
+
873
+ // shared/.gitignore
874
+ fs.writeFileSync(
875
+ path.join(sharedDir, '.gitignore'),
876
+ `node_modules\ndist\n`
877
+ );
878
+
879
+ console.log('✅ Shared package created\n');
880
+ }
881
+
882
+ async function createAzureFunctionsProject(
883
+ projectDir: string,
884
+ pm: PackageManager = 'pnpm',
885
+ backendLanguage: BackendLanguage = 'typescript'
886
+ ) {
887
+ console.log(`📦 Creating Azure Functions project (${getBackendLanguageLabel(backendLanguage)})...\n`);
888
+
889
+ const functionsDir = path.join(projectDir, 'functions');
890
+ fs.mkdirSync(functionsDir, { recursive: true });
891
+
892
+ const projectName = path.basename(projectDir);
893
+ const databaseName = `${projectName.charAt(0).toUpperCase() + projectName.slice(1)}Database`;
894
+
895
+ createFunctionsHostFiles(functionsDir, databaseName, backendLanguage);
896
+
897
+ if (backendLanguage === 'typescript') {
898
+ createTypeScriptFunctionsProject(projectDir, functionsDir, pm);
899
+ } else if (backendLanguage === 'csharp') {
900
+ createCSharpFunctionsProject(projectDir, functionsDir);
901
+ } else {
902
+ createPythonFunctionsProject(projectDir, functionsDir);
903
+ }
904
+
905
+ console.log('✅ Azure Functions project created\n');
906
+ }
907
+
908
+ function createFunctionsHostFiles(functionsDir: string, databaseName: string, backendLanguage: BackendLanguage): void {
909
+ const hostJson = {
910
+ version: '2.0',
911
+ logging: {
912
+ applicationInsights: {
913
+ samplingSettings: {
914
+ isEnabled: true,
915
+ maxTelemetryItemsPerSecond: 20,
916
+ },
917
+ },
918
+ },
919
+ extensionBundle: {
920
+ id: 'Microsoft.Azure.Functions.ExtensionBundle',
921
+ version: '[4.0.0, 4.10.0)',
922
+ },
923
+ };
924
+ fs.writeFileSync(path.join(functionsDir, 'host.json'), JSON.stringify(hostJson, null, 2));
925
+
926
+ const localSettings = {
927
+ IsEncrypted: false,
928
+ Values: {
929
+ AzureWebJobsStorage: '',
930
+ FUNCTIONS_WORKER_RUNTIME: getFunctionsWorkerRuntime(backendLanguage),
931
+ AzureWebJobsFeatureFlags: 'EnableWorkerIndexing',
932
+ CosmosDBConnection: 'AccountEndpoint=http://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==',
933
+ COSMOS_DB_DATABASE_NAME: databaseName,
934
+ NODE_TLS_REJECT_UNAUTHORIZED: '0',
935
+ },
936
+ };
937
+ fs.writeFileSync(path.join(functionsDir, 'local.settings.json'), JSON.stringify(localSettings, null, 2));
938
+
939
+ const gitignoreLines = [
940
+ 'local.settings.json',
941
+ '*.log',
942
+ '.vscode',
943
+ '.DS_Store',
944
+ ];
945
+
946
+ if (backendLanguage === 'typescript') {
947
+ gitignoreLines.unshift('node_modules', 'dist');
948
+ fs.writeFileSync(path.join(functionsDir, '.funcignore'), `node_modules
949
+ .git
950
+ .vscode
951
+ local.settings.json
952
+ test
953
+ tsconfig.json
954
+ *.ts
955
+ !dist/**/*.js
956
+ `);
957
+ } else if (backendLanguage === 'python') {
958
+ gitignoreLines.unshift('.venv', '__pycache__', '.python_packages');
959
+ fs.writeFileSync(path.join(functionsDir, '.funcignore'), `.venv
960
+ __pycache__
961
+ .pytest_cache
962
+ .mypy_cache
963
+ .ruff_cache
964
+ local.settings.json
965
+ tests
966
+ `);
967
+ } else {
968
+ gitignoreLines.unshift('bin', 'obj');
969
+ fs.writeFileSync(path.join(functionsDir, '.funcignore'), `bin
970
+ obj
971
+ local.settings.json
972
+ tests
973
+ `);
974
+ }
975
+
976
+ fs.writeFileSync(path.join(functionsDir, '.gitignore'), `${gitignoreLines.join('\n')}\n`);
977
+ }
978
+
979
+ function createTypeScriptFunctionsProject(projectDir: string, functionsDir: string, pm: PackageManager): void {
980
+ const functionsPackageJson = {
981
+ name: 'functions',
982
+ version: '1.0.0',
983
+ description: 'Azure Functions backend',
984
+ main: 'dist/*.js',
985
+ scripts: {
986
+ start: 'func start',
987
+ build: 'tsc',
988
+ prestart: getFunctionsPrestart(pm),
989
+ },
990
+ dependencies: {
991
+ '@azure/functions': '~4.5.0',
992
+ '@azure/cosmos': '^4.0.0',
993
+ '@azure/identity': '^4.0.0',
994
+ zod: '>=3.25.0',
995
+ [`@${path.basename(projectDir)}/shared`]: '*',
996
+ },
997
+ devDependencies: {
998
+ '@types/node': '^20.0.0',
999
+ typescript: '^5.0.0',
1000
+ },
1001
+ };
1002
+ fs.writeFileSync(path.join(functionsDir, 'package.json'), JSON.stringify(functionsPackageJson, null, 2));
1003
+
1004
+ const sharedPkgName = `@${path.basename(projectDir)}/shared`;
1005
+ const functionsTsConfig = {
1006
+ compilerOptions: {
1007
+ target: 'ES2020',
1008
+ module: 'commonjs',
1009
+ moduleResolution: 'node',
1010
+ lib: ['ES2020'],
1011
+ outDir: 'dist',
1012
+ rootDir: 'src',
1013
+ strict: true,
1014
+ esModuleInterop: true,
1015
+ skipLibCheck: true,
1016
+ forceConsistentCasingInFileNames: true,
1017
+ paths: {
1018
+ [sharedPkgName]: ['../shared'],
1019
+ [`${sharedPkgName}/*`]: ['../shared/*'],
1020
+ },
1021
+ },
1022
+ include: ['src/**/*'],
1023
+ exclude: ['node_modules', 'dist'],
1024
+ };
1025
+ fs.writeFileSync(path.join(functionsDir, 'tsconfig.json'), JSON.stringify(functionsTsConfig, null, 2));
1026
+
1027
+ const srcDir = path.join(functionsDir, 'src');
1028
+ fs.mkdirSync(srcDir, { recursive: true });
1029
+ fs.writeFileSync(path.join(srcDir, 'greet.ts'), `import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';
1030
+ import { z } from 'zod/v4';
1031
+
1032
+ const greetRequestSchema = z.object({
1033
+ name: z.string().min(1, 'Name is required').max(50, 'Name must be less than 50 characters'),
1034
+ });
1035
+
1036
+ export async function greet(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
1037
+ context.log('HTTP trigger function processed a request.');
1038
+
1039
+ try {
1040
+ const name = request.query.get('name') || (await request.text());
1041
+ const result = greetRequestSchema.safeParse({ name });
1042
+
1043
+ if (!result.success) {
1044
+ return {
1045
+ status: 400,
1046
+ jsonBody: {
1047
+ error: result.error.issues[0].message
1048
+ }
1049
+ };
1050
+ }
1051
+
1052
+ const greeting = \`Hello, \${result.data.name}! This message is from Azure Functions.\`;
1053
+
1054
+ return {
1055
+ status: 200,
1056
+ jsonBody: {
1057
+ message: greeting,
1058
+ timestamp: new Date().toISOString()
1059
+ }
1060
+ };
1061
+ } catch (error) {
1062
+ context.error('Error processing request:', error);
1063
+ return {
1064
+ status: 500,
1065
+ jsonBody: {
1066
+ error: 'Internal server error'
1067
+ }
1068
+ };
1069
+ }
1070
+ }
1071
+
1072
+ app.http('greet', {
1073
+ methods: ['GET', 'POST'],
1074
+ authLevel: 'anonymous',
1075
+ handler: greet
1076
+ });
1077
+ `);
1078
+ }
1079
+
1080
+ function createCSharpFunctionsProject(projectDir: string, functionsDir: string): void {
1081
+ const projectBaseName = path.basename(projectDir);
1082
+ const projectPascal = projectBaseName.charAt(0).toUpperCase() + projectBaseName.slice(1);
1083
+ const csprojName = `${projectPascal}.Functions.csproj`;
1084
+
1085
+ fs.writeFileSync(path.join(functionsDir, csprojName), buildCSharpFunctionsProjectSource());
1086
+
1087
+ fs.writeFileSync(path.join(functionsDir, 'Program.cs'), buildCSharpFunctionsProgramSource());
1088
+
1089
+ const crudDir = path.join(functionsDir, 'Crud');
1090
+ fs.mkdirSync(crudDir, { recursive: true });
1091
+ fs.writeFileSync(path.join(crudDir, 'GreetFunction.cs'), `using System.Net;
1092
+ using Microsoft.Azure.Functions.Worker;
1093
+ using Microsoft.Azure.Functions.Worker.Http;
1094
+
1095
+ namespace SwallowKit.Functions;
1096
+
1097
+ public sealed class GreetFunction
1098
+ {
1099
+ [Function("greet")]
1100
+ public async Task<HttpResponseData> Run(
1101
+ [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "greet")] HttpRequestData request)
1102
+ {
1103
+ var query = request.Url.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries);
1104
+ var name = "SwallowKit";
1105
+ foreach (var segment in query)
1106
+ {
1107
+ var parts = segment.Split('=', 2);
1108
+ if (parts.Length == 2 && parts[0] == "name")
1109
+ {
1110
+ name = Uri.UnescapeDataString(parts[1]);
1111
+ break;
1112
+ }
1113
+ }
1114
+ var response = request.CreateResponse(HttpStatusCode.OK);
1115
+ await response.WriteAsJsonAsync(new
1116
+ {
1117
+ message = $"Hello, {name}! This message is from Azure Functions.",
1118
+ timestamp = DateTimeOffset.UtcNow.ToString("O"),
1119
+ });
1120
+ return response;
1121
+ }
1122
+ }
1123
+ `);
1124
+ }
1125
+
1126
+ function createPythonFunctionsProject(projectDir: string, functionsDir: string): void {
1127
+ fs.writeFileSync(path.join(projectDir, '.python-version'), '3.11\n');
1128
+
1129
+ fs.writeFileSync(path.join(functionsDir, 'requirements.txt'), `azure-functions>=1.20.0
1130
+ azure-cosmos>=4.9.0
1131
+ azure-identity>=1.19.0
1132
+ `);
1133
+
1134
+ const blueprintsDir = path.join(functionsDir, 'blueprints');
1135
+ fs.mkdirSync(blueprintsDir, { recursive: true });
1136
+ fs.writeFileSync(path.join(blueprintsDir, '__init__.py'), '');
1137
+
1138
+ fs.writeFileSync(path.join(blueprintsDir, 'greet.py'), `import json
1139
+ from datetime import datetime, timezone
1140
+
1141
+ import azure.functions as func
1142
+
1143
+ bp = func.Blueprint()
1144
+
1145
+
1146
+ @bp.route(route="greet", methods=["GET", "POST"])
1147
+ def greet(req: func.HttpRequest) -> func.HttpResponse:
1148
+ name = req.params.get("name") or "SwallowKit"
1149
+ payload = {
1150
+ "message": f"Hello, {name}! This message is from Azure Functions.",
1151
+ "timestamp": datetime.now(timezone.utc).isoformat(),
1152
+ }
1153
+ return func.HttpResponse(
1154
+ body=json.dumps(payload, ensure_ascii=False),
1155
+ status_code=200,
1156
+ mimetype="application/json",
1157
+ )
1158
+ `);
1159
+
1160
+ fs.writeFileSync(path.join(functionsDir, 'function_app.py'), `import azure.functions as func
1161
+
1162
+ from blueprints.greet import bp as greet_bp
1163
+
1164
+ app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
1165
+
1166
+ app.register_blueprint(greet_bp)
1167
+ # SwallowKit scaffold registrations
1168
+ `);
1169
+ }
1170
+
1171
+ async function createBffApiRoute(projectDir: string) {
1172
+ console.log('📦 Creating BFF API route...\n');
1173
+
1174
+ const apiDir = path.join(projectDir, 'app', 'api', 'greet');
1175
+ fs.mkdirSync(apiDir, { recursive: true });
1176
+
1177
+ // Create API route that calls Azure Functions using shared utility
1178
+ const apiRoute = `import { NextRequest, NextResponse } from 'next/server';
1179
+ import { api } from '@/lib/api/backend';
1180
+
1181
+ interface GreetResponse {
1182
+ message: string;
1183
+ timestamp: string;
1184
+ }
1185
+
1186
+ export async function GET(request: NextRequest) {
1187
+ try {
1188
+ const { searchParams } = new URL(request.url);
1189
+ const name = searchParams.get('name') || 'World';
1190
+
1191
+ const data = await api.get<GreetResponse>('/api/greet', { name });
1192
+
1193
+ return NextResponse.json(data);
1194
+ } catch (error) {
1195
+ console.error('Error calling Azure Functions:', error);
1196
+ const errorMessage = error instanceof Error ? error.message : 'Failed to call backend function';
1197
+ return NextResponse.json(
1198
+ { error: errorMessage, details: 'Make sure Azure Functions is running on port 7071' },
1199
+ { status: 500 }
1200
+ );
1201
+ }
1202
+ }
1203
+
1204
+ export async function POST(request: NextRequest) {
1205
+ try {
1206
+ const body = await request.json();
1207
+
1208
+ const data = await api.post<GreetResponse>('/api/greet', body);
1209
+
1210
+ return NextResponse.json(data);
1211
+ } catch (error) {
1212
+ console.error('Error calling Azure Functions:', error);
1213
+ const errorMessage = error instanceof Error ? error.message : 'Failed to call backend function';
1214
+ return NextResponse.json(
1215
+ { error: errorMessage, details: 'Make sure Azure Functions is running on port 7071' },
1216
+ { status: 500 }
1217
+ );
1218
+ }
1219
+ }
1220
+ `;
1221
+ fs.writeFileSync(path.join(apiDir, 'route.ts'), apiRoute);
1222
+
1223
+ // Update .env.example to include BACKEND_FUNCTIONS_BASE_URL
1224
+ const envExamplePath = path.join(projectDir, '.env.example');
1225
+ let envExample = fs.readFileSync(envExamplePath, 'utf-8');
1226
+
1227
+ if (!envExample.includes('BACKEND_FUNCTIONS_BASE_URL')) {
1228
+ envExample += `\n# Azure Functions Backend URL\nBACKEND_FUNCTIONS_BASE_URL=http://localhost:7071\n`;
1229
+ fs.writeFileSync(envExamplePath, envExample);
1230
+ }
1231
+
1232
+ // Update .env.local
1233
+ const envLocalPath = path.join(projectDir, '.env.local');
1234
+ let envLocal = fs.readFileSync(envLocalPath, 'utf-8');
1235
+
1236
+ if (!envLocal.includes('BACKEND_FUNCTIONS_BASE_URL')) {
1237
+ envLocal += `\n# Azure Functions Backend URL (Local)\nBACKEND_FUNCTIONS_BASE_URL=http://localhost:7071\n`;
1238
+ fs.writeFileSync(envLocalPath, envLocal);
1239
+ }
1240
+
1241
+ console.log('✅ BFF API route created\n');
1242
+ }
1243
+
1244
+ async function createHomePage(projectDir: string, pm: PackageManager = 'pnpm') {
1245
+ console.log('📦 Creating home page...\n');
1246
+
1247
+ const pmCmd = getCommands(pm);
1248
+
1249
+ const pageContent = `'use client'
1250
+
1251
+ export const dynamic = 'force-dynamic';
1252
+
1253
+ import { useState } from 'react';
1254
+ import { scaffoldConfig } from '@/lib/scaffold-config';
1255
+
1256
+ export default function Home() {
1257
+ const [greetingStatus, setGreetingStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
1258
+ const [message, setMessage] = useState('');
1259
+
1260
+ const testConnection = async () => {
1261
+ setGreetingStatus('loading');
1262
+ try {
1263
+ const response = await fetch('/api/greet?name=SwallowKit');
1264
+ const data = await response.json();
1265
+ if (!response.ok) {
1266
+ throw new Error(data.error || \`Server error: \${response.status}\`);
1267
+ }
1268
+ setMessage(data.message);
1269
+ setGreetingStatus('success');
1270
+ } catch (error) {
1271
+ setMessage(error instanceof Error ? error.message : 'Failed to connect to Azure Functions');
1272
+ setGreetingStatus('error');
1273
+ }
1274
+ };
1275
+
1276
+ return (
1277
+ <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-gray-900 dark:to-gray-800">
1278
+ <div className="container mx-auto px-4 py-12">
1279
+ <header className="text-center mb-16">
1280
+ <h1 className="text-5xl font-bold text-gray-800 dark:text-white mb-4">
1281
+ Welcome to SwallowKit
1282
+ </h1>
1283
+ <p className="text-xl text-gray-600 dark:text-gray-400">
1284
+ Next.js on Azure Static Web Apps + Functions + Cosmos DB — Zod schema sharing
1285
+ </p>
1286
+ </header>
1287
+
1288
+ {/* Connection Test */}
1289
+ <section className="max-w-2xl mx-auto mb-12">
1290
+ <div className="bg-white dark:bg-gray-800 rounded-xl p-8 border border-gray-200 dark:border-gray-700">
1291
+ <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-gray-100">
1292
+ Test BFF → Functions Connection
1293
+ </h2>
1294
+ <button
1295
+ onClick={testConnection}
1296
+ disabled={greetingStatus === 'loading'}
1297
+ className="px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white rounded-lg font-medium transition-colors"
1298
+ >
1299
+ {greetingStatus === 'loading' ? 'Testing...' : 'Test Connection'}
1300
+ </button>
1301
+ {greetingStatus === 'success' && (
1302
+ <div className="mt-4 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
1303
+ <p className="text-green-800 dark:text-green-200 font-medium">✅ Connection successful!</p>
1304
+ <p className="text-green-700 dark:text-green-300 text-sm mt-1">{message}</p>
1305
+ </div>
1306
+ )}
1307
+ {greetingStatus === 'error' && (
1308
+ <div className="mt-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
1309
+ <p className="text-red-800 dark:text-red-200 font-medium">❌ Connection failed</p>
1310
+ <p className="text-red-700 dark:text-red-300 text-sm mt-1">{message}</p>
1311
+ </div>
1312
+ )}
1313
+ </div>
1314
+ </section>
1315
+
1316
+ {/* Scaffolded Models Menu */}
1317
+ {scaffoldConfig.models.length > 0 ? (
1318
+ <section className="max-w-6xl mx-auto">
1319
+ <h2 className="text-3xl font-bold mb-8 text-gray-900 dark:text-gray-100">Your Models</h2>
1320
+ <div className="grid gap-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
1321
+ {scaffoldConfig.models.map((model) => (
1322
+ <a
1323
+ key={model.name}
1324
+ href={model.path}
1325
+ className="block p-8 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl hover:shadow-lg hover:border-blue-400 dark:hover:border-blue-600 transition-all"
1326
+ >
1327
+ <h3 className="text-2xl font-semibold mb-2 text-gray-900 dark:text-gray-100">{model.label}</h3>
1328
+ <p className="text-gray-600 dark:text-gray-400">Manage {model.label.toLowerCase()}</p>
1329
+ </a>
1330
+ ))}
1331
+ </div>
1332
+ </section>
1333
+ ) : (
1334
+ <section className="max-w-2xl mx-auto text-center">
1335
+ <div className="bg-white dark:bg-gray-800 rounded-xl p-12 border border-gray-200 dark:border-gray-700">
1336
+ <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-gray-100">Get Started</h2>
1337
+ <p className="text-gray-600 dark:text-gray-400 mb-6">
1338
+ Create your first model with Zod and generate CRUD operations automatically.
1339
+ </p>
1340
+ <code className="block bg-gray-100 dark:bg-gray-900 p-4 rounded text-left text-sm">
1341
+ ${pmCmd.dlx} swallowkit scaffold shared/models/your-model.ts
1342
+ </code>
1343
+ </div>
1344
+ </section>
1345
+ )}
1346
+
1347
+ <footer className="mt-16 text-center text-gray-600 dark:text-gray-400 text-sm">
1348
+ <p>Built with SwallowKit</p>
1349
+ </footer>
1350
+ </div>
1351
+ </div>
1352
+ );
1353
+ }
1354
+ `;
1355
+
1356
+ fs.writeFileSync(path.join(projectDir, 'app', 'page.tsx'), pageContent);
1357
+
1358
+ console.log('✅ Home page created\n');
1359
+
1360
+ // Create initial scaffold-config.ts
1361
+ const scaffoldConfigDir = path.join(projectDir, 'lib');
1362
+ if (!fs.existsSync(scaffoldConfigDir)) {
1363
+ fs.mkdirSync(scaffoldConfigDir, { recursive: true });
1364
+ }
1365
+
1366
+ const scaffoldConfigContent = `export interface ScaffoldModel {
1367
+ name: string;
1368
+ path: string;
1369
+ label: string;
1370
+ }
1371
+
1372
+ export const scaffoldConfig = {
1373
+ models: [
1374
+ // Scaffolded models will be added here by 'swallowkit scaffold' command
1375
+ ] as ScaffoldModel[]
1376
+ };
1377
+ `;
1378
+
1379
+ fs.writeFileSync(path.join(scaffoldConfigDir, 'scaffold-config.ts'), scaffoldConfigContent);
1380
+ console.log('✅ Scaffold config created\n');
1381
+ }
1382
+
1383
+ function createReadme(
1384
+ projectDir: string,
1385
+ projectName: string,
1386
+ cicdChoice: string,
1387
+ azureConfig: AzureConfig,
1388
+ pm: PackageManager,
1389
+ backendLanguage: BackendLanguage
1390
+ ) {
1391
+ console.log('📝 Creating README.md...\n');
1392
+
1393
+ const pmCmd = getCommands(pm);
1394
+ const cosmosDbModeLabel = azureConfig.cosmosDbMode === 'freetier' ? 'Free Tier (1000 RU/s)' : 'Serverless';
1395
+ const cicdLabel = cicdChoice === 'github' ? 'GitHub Actions' : cicdChoice === 'azure' ? 'Azure Pipelines' : 'None';
1396
+ const vnetLabel = azureConfig.vnetOption === 'none' ? 'None (public endpoints)' :
1397
+ 'Outbound VNet (Cosmos DB Private Endpoint)';
1398
+ const backendLanguageLabel = getBackendLanguageLabel(backendLanguage);
1399
+ const schemaBridgeDescription = backendLanguage === 'typescript'
1400
+ ? 'Zod (shared between frontend and backend)'
1401
+ : `Zod + OpenAPI bridge (Zod in shared/, generated ${backendLanguageLabel} schemas in functions/generated/)`;
1402
+ const functionsTree = backendLanguage === 'typescript'
1403
+ ? `│ └── src/\n│ └── greet.ts # Sample function`
1404
+ : backendLanguage === 'csharp'
1405
+ ? `│ ├── Crud/\n│ │ └── GreetFunction.cs\n│ └── generated/ # OpenAPI-derived C# models`
1406
+ : `│ ├── blueprints/\n│ │ └── greet.py\n│ └── generated/ # OpenAPI-derived Python models`;
1407
+ const backendScaffoldNote = backendLanguage === 'typescript'
1408
+ ? '- Azure Functions CRUD endpoints'
1409
+ : `- Azure Functions ${backendLanguageLabel} CRUD handlers\n- OpenAPI spec + generated ${backendLanguageLabel} schema assets`;
1410
+ const pythonLocalDevNote = backendLanguage === 'python'
1411
+ ? `\n**Python local dev note**: SwallowKit uses \`functions/.venv\` for local Azure Functions development. If \`uv\` is installed, \`swallowkit dev\` uses it to create/manage that virtual environment; otherwise it falls back to the standard \`venv\` + \`pip\` workflow. Keep \`functions/requirements.txt\` as the dependency source of truth for Azure Functions compatibility.\n`
1412
+ : '';
1413
+
1414
+ const readme = `# ${projectName}
1415
+
1416
+ A full-stack application built with **SwallowKit** - Next.js on Azure Static Web Apps + Functions + Cosmos DB with Zod schema sharing.
1417
+
1418
+ ## 🚀 Tech Stack
1419
+
1420
+ - **Frontend**: Next.js 15 (App Router), React, TypeScript, Tailwind CSS
1421
+ - **BFF (Backend for Frontend)**: Next.js API Routes
1422
+ - **Backend**: Azure Functions (${backendLanguageLabel})
1423
+ - **Database**: Azure Cosmos DB
1424
+ - **Schema Validation**: ${schemaBridgeDescription}
1425
+ - **Infrastructure**: Bicep (Infrastructure as Code)
1426
+ - **CI/CD**: ${cicdLabel}
1427
+
1428
+ ## 📋 Project Configuration
1429
+
1430
+ This project was initialized with the following settings:
1431
+
1432
+ - **Azure Functions Plan**: Flex Consumption
1433
+ - **Cosmos DB Mode**: ${cosmosDbModeLabel}
1434
+ - **Network Security**: ${vnetLabel}
1435
+ - **CI/CD**: ${cicdLabel}
1436
+
1437
+ ## ✅ Prerequisites
1438
+
1439
+ Before you begin, ensure you have the following installed:
1440
+
1441
+ 1. **Node.js 18+**: [Download](https://nodejs.org/)${pm === 'pnpm' ? `\n2. **pnpm**: \`corepack enable\` or \`npm install -g pnpm\`` : ''}
1442
+ ${pm === 'pnpm' ? '3' : '2'}. **Azure CLI**: Required for provisioning Azure resources
1443
+ - Install: \`winget install Microsoft.AzureCLI\` (Windows)
1444
+ - Or: [Download](https://aka.ms/installazurecliwindows)
1445
+ ${pm === 'pnpm' ? '4' : '3'}. **Azure Cosmos DB Emulator**: Required for local development
1446
+ - Windows: \`winget install Microsoft.Azure.CosmosEmulator\`
1447
+ - Or: [Download](https://aka.ms/cosmosdb-emulator)
1448
+ - Docker: \`docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator\`
1449
+ ${pm === 'pnpm' ? '6' : '5'}. **Azure Functions Core Tools**: Automatically installed with project dependencies
1450
+
1451
+ ## 📁 Project Structure
1452
+
1453
+ \`\`\`
1454
+ ${projectName}/
1455
+ ├── app/ # Next.js App Router (frontend)
1456
+ │ ├── api/ # BFF API routes (proxy to Functions)
1457
+ │ └── page.tsx # Home page
1458
+ ├── functions/ # Azure Functions (backend)
1459
+ ${functionsTree}
1460
+ ├── lib/
1461
+ │ └── api/ # API client utilities
1462
+ ├── infra/ # Bicep infrastructure files
1463
+ │ ├── main.bicep
1464
+ │ └── modules/ # Bicep modules for each resource
1465
+ └── .github/workflows/ # CI/CD workflows
1466
+ \`\`\`
1467
+
1468
+ ## 🏗️ Getting Started
1469
+
1470
+ ### 1. Create Your First Model
1471
+
1472
+ Define your data model with Zod schema:
1473
+
1474
+ \`\`\`bash
1475
+ ${pmCmd.dlx} swallowkit create-model <model-name>
1476
+ \`\`\`
1477
+
1478
+ This creates a model file in \`shared/models/<model-name>.ts\`. Edit it to define your schema.
1479
+
1480
+ ### 2. Generate CRUD Code
1481
+
1482
+ Generate complete CRUD operations (Functions, API routes, UI):
1483
+
1484
+ \`\`\`bash
1485
+ ${pmCmd.dlx} swallowkit scaffold shared/models/<model-name>.ts
1486
+ \`\`\`
1487
+
1488
+ This generates:
1489
+ ${backendScaffoldNote}
1490
+ - Next.js BFF API routes
1491
+ - React UI components (list, detail, create, edit)
1492
+ - Navigation menu integration
1493
+
1494
+ ### 3. Start Development Servers
1495
+
1496
+ \`\`\`bash
1497
+ ${pmCmd.dlx} swallowkit dev
1498
+ \`\`\`
1499
+
1500
+ This starts:
1501
+ - Next.js dev server (http://localhost:3000)
1502
+ - Azure Functions (http://localhost:7071)
1503
+ - Cosmos DB Emulator check (must be running separately)
1504
+
1505
+ **Note**: You need to start Cosmos DB Emulator manually before running \`swallowkit dev\`.
1506
+ ${pythonLocalDevNote}
1507
+
1508
+ ## ☁️ Deploy to Azure
1509
+
1510
+ ### Provision Azure Resources
1511
+
1512
+ Create all required Azure resources using Bicep:
1513
+
1514
+ \`\`\`bash
1515
+ ${pmCmd.dlx} swallowkit provision --resource-group <rg-name>
1516
+ \`\`\`
1517
+
1518
+ This creates:
1519
+ - Static Web App (\`swa-${projectName}\`)
1520
+ - Azure Functions (\`func-${projectName}\`)
1521
+ - Cosmos DB (\`cosmos-${projectName}\`)
1522
+ - Storage Account
1523
+
1524
+ You will be prompted to select Azure regions:
1525
+ 1. **Primary location**: For Functions and Cosmos DB (default: Japan East)
1526
+ 2. **Static Web App location**: Limited availability (default: East Asia)
1527
+
1528
+ ### CI/CD Setup
1529
+
1530
+ ${cicdChoice === 'github' ? `#### GitHub Actions
1531
+
1532
+ 1. Get Static Web App deployment token:
1533
+ \`\`\`bash
1534
+ az staticwebapp secrets list --name swa-${projectName} --resource-group <rg-name> --query "properties.apiKey" -o tsv
1535
+ \`\`\`
1536
+
1537
+ 2. Get Function App publish profile:
1538
+ \`\`\`bash
1539
+ az webapp deployment list-publishing-profiles --name func-${projectName} --resource-group <rg-name> --xml
1540
+ \`\`\`
1541
+
1542
+ 3. Add secrets to GitHub repository:
1543
+ - \`AZURE_STATIC_WEB_APPS_API_TOKEN\`: SWA deployment token (from step 1)
1544
+ - \`AZURE_FUNCTIONAPP_NAME\`: \`func-${projectName}\`
1545
+ - \`AZURE_FUNCTIONAPP_PUBLISH_PROFILE\`: Functions publish profile (from step 2)
1546
+
1547
+ 4. Push to \`main\` branch to trigger deployment (or use **Actions** → **Run workflow** for manual deployment)` : cicdChoice === 'azure' ? `#### Azure Pipelines
1548
+
1549
+ 1. Set up service connection in Azure DevOps
1550
+ 2. Update \`azure-pipelines.yml\` with your resource names
1551
+ 3. Configure pipeline variables:
1552
+ - \`azureSubscription\`: Service connection name
1553
+ - \`resourceGroupName\`: Resource group name
1554
+ 4. Run pipeline to deploy` : `CI/CD is not configured. You can manually deploy:
1555
+
1556
+ **Deploy Static Web App:**
1557
+ \`\`\`bash
1558
+ ${pmCmd.run} build
1559
+ az staticwebapp deploy --name swa-${projectName} --resource-group <rg-name> --app-location ./
1560
+ \`\`\`
1561
+
1562
+ **Deploy Functions:**
1563
+ \`\`\`bash
1564
+ cd functions
1565
+ ${pmCmd.run} build
1566
+ func azure functionapp publish func-${projectName}
1567
+ \`\`\``}
1568
+
1569
+ ## 🔧 Available Commands
1570
+
1571
+ - \`${pmCmd.dlx} swallowkit create-model <name>\` - Create a new data model
1572
+ - \`${pmCmd.dlx} swallowkit scaffold <model-file>\` - Generate CRUD code
1573
+ - \`${pmCmd.dlx} swallowkit dev\` - Start development servers
1574
+ - \`${pmCmd.dlx} swallowkit provision -g <rg-name>\` - Provision Azure resources
1575
+ ${azureConfig.vnetOption !== 'none' ? `
1576
+ ## 🔒 Network Security (VNet Configuration)
1577
+
1578
+ This project is configured with **${vnetLabel}**.
1579
+
1580
+ ### Architecture
1581
+
1582
+ \`\`\`
1583
+ Static Web App ──(public)──> Azure Functions ──(VNet/PE)──> Cosmos DB
1584
+
1585
+ VNet Integration
1586
+ (outbound only)
1587
+ \`\`\`
1588
+
1589
+ - **Functions → Cosmos DB**: Connected via Private Endpoint (private connection)
1590
+ - **SWA → Functions**: Connected via public endpoint (secured with CORS + IP restrictions)
1591
+
1592
+ ### VNet Resources
1593
+
1594
+ | Resource | Purpose |
1595
+ |----------|---------|
1596
+ | \`vnet-${projectName}\` | Virtual Network (10.0.0.0/16) |
1597
+ | \`snet-functions\` | Functions subnet (10.0.1.0/24) |
1598
+ | \`snet-private-endpoints\` | Private Endpoints subnet (10.0.2.0/24) |
1599
+ | \`pe-cosmos-${projectName}\` | Cosmos DB Private Endpoint |
1600
+
1601
+ ### Private DNS Zones
1602
+
1603
+ - \`privatelink.documents.azure.com\` (Cosmos DB)
1604
+ ` : ''}
1605
+ ## 📚 Learn More
1606
+
1607
+ - [SwallowKit Documentation](https://github.com/himanago/swallowkit)
1608
+ - [Azure Static Web Apps](https://learn.microsoft.com/en-us/azure/static-web-apps/)
1609
+ - [Azure Functions](https://learn.microsoft.com/en-us/azure/azure-functions/)
1610
+ - [Azure Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/)
1611
+ - [Next.js](https://nextjs.org/)
1612
+ - [Zod](https://zod.dev/)
1613
+
1614
+ ## 💭 Feedback
1615
+
1616
+ This project was generated by SwallowKit. If you encounter any issues or have suggestions for improvements, please open an issue on the [SwallowKit repository](https://github.com/himanago/swallowkit).
1617
+ `;
1618
+
1619
+ fs.writeFileSync(path.join(projectDir, 'README.md'), readme);
1620
+ console.log('✅ README.md created\n');
1621
+ }
1622
+
1623
+ function createAiAgentFiles(projectDir: string, projectName: string, backendLanguage: BackendLanguage) {
1624
+ console.log('🤖 Creating AI agent instruction files...\n');
1625
+ const backendLanguageLabel = getBackendLanguageLabel(backendLanguage);
1626
+ const functionsStructureLine = backendLanguage === 'typescript'
1627
+ ? `│ └── src/ # HTTP trigger handlers with Cosmos DB bindings`
1628
+ : backendLanguage === 'csharp'
1629
+ ? `│ ├── Crud/ # C# HTTP trigger handlers\n│ └── generated/ # OpenAPI-derived C# schema assets`
1630
+ : `│ ├── blueprints/ # Python HTTP trigger handlers\n│ └── generated/ # OpenAPI-derived Python schema assets`;
1631
+ const backendSchemaNote = backendLanguage === 'typescript'
1632
+ ? `- The shared package (\`@${projectName}/shared\`) is consumed by both Next.js and Azure Functions as a workspace dependency.`
1633
+ : `- The frontend/BFF source of truth stays in \`shared/models/\` as Zod schemas.\n- \`swallowkit scaffold\` exports OpenAPI into \`functions/openapi/\` and generates ${backendLanguageLabel} schema assets into \`functions/generated/\` for backend use.`;
1634
+ const backendRulesNote = backendLanguage === 'typescript'
1635
+ ? `- All CRUD operations and business logic live in \`functions/src/\`.\n- Use Azure Functions Cosmos DB **input/output bindings** (\`extraInputs\`/\`extraOutputs\`) for reads and writes.\n- Use the Cosmos DB SDK client directly **only** for delete operations (bindings do not support delete).\n- Validate all data against Zod schemas before writing to Cosmos DB.\n- The backend auto-generates \`id\` (UUID), \`createdAt\`, and \`updatedAt\` — never trust client-sent values for these fields.`
1636
+ : `- All business logic lives in \`functions/\` and the generated handlers perform real Cosmos DB CRUD.\n- Keep Zod schemas in \`shared/models/\` as the source of truth.\n- Regenerate backend contracts with \`swallowkit scaffold shared/models/<name>.ts\` whenever a schema changes.\n- Use the generated OpenAPI-derived models in \`functions/generated/\` to keep backend contracts aligned.\n- The backend should still own \`id\`, \`createdAt\`, and \`updatedAt\`.`;
1637
+
1638
+ // ── 1. AGENTS.md (Codex / generic agents) ──────────────────────────
1639
+
1640
+ const agentsMd = `# AGENTS.md
1641
+
1642
+ This project was generated by **SwallowKit**.
1643
+ All coding agents **must** follow the architecture and conventions described below.
1644
+
1645
+ ## Architecture Overview
1646
+
1647
+ This is a full-stack application deployed on Azure with a TypeScript frontend/BFF and an Azure Functions backend in ${backendLanguageLabel}.
1648
+
1649
+ \`\`\`
1650
+ Frontend (React / Next.js App Router)
1651
+ ↓ fetch('/api/{model}', ...)
1652
+ BFF Layer (Next.js API Routes)
1653
+ ↓ HTTP → Azure Functions
1654
+ Backend (Azure Functions)
1655
+
1656
+ Azure Cosmos DB (Document Database)
1657
+ \`\`\`
1658
+
1659
+ ### Project Structure
1660
+
1661
+ \`\`\`
1662
+ ${projectName}/
1663
+ ├── app/ # Next.js App Router
1664
+ │ ├── api/ # BFF API routes (proxy to Azure Functions)
1665
+ │ └── {model}/ # UI pages per model (list, detail, create, edit)
1666
+ ├── functions/ # Azure Functions (backend)
1667
+ ${functionsStructureLine}
1668
+ ├── shared/ # Shared workspace package
1669
+ │ ├── models/ # Zod schema definitions (single source of truth)
1670
+ │ └── index.ts # Re-exports all models
1671
+ ├── lib/
1672
+ │ └── api/ # API client utilities (backend.ts, call-function.ts)
1673
+ ├── components/ # Shared React components
1674
+ ├── infra/ # Bicep infrastructure-as-code files
1675
+ │ ├── main.bicep
1676
+ │ └── modules/
1677
+ └── .github/workflows/ # CI/CD workflows (if configured)
1678
+ \`\`\`
1679
+
1680
+ ## Critical Design Principles
1681
+
1682
+ ### 1. Next.js API Routes Are Strictly a BFF (Backend for Frontend)
1683
+
1684
+ - \`app/api/\` routes exist **only** to proxy requests to Azure Functions.
1685
+ - **Never** place business logic, database access, or direct Cosmos DB calls in Next.js API routes.
1686
+ - The BFF layer may validate input/output with Zod schemas before forwarding to Functions.
1687
+ - Use the \`callFunction\` helper (\`lib/api/call-function.ts\`) or the \`api\` client (\`lib/api/backend.ts\`) to call Azure Functions.
1688
+
1689
+ Example BFF route pattern:
1690
+
1691
+ \`\`\`typescript
1692
+ // app/api/{model}/route.ts
1693
+ import { callFunction } from '@/lib/api/call-function';
1694
+ import { ModelSchema } from '@${projectName}/shared';
1695
+ import { z } from 'zod/v4';
1696
+
1697
+ export async function GET() {
1698
+ return callFunction({
1699
+ method: 'GET',
1700
+ path: '/api/{model}',
1701
+ responseSchema: z.array(ModelSchema),
1702
+ });
1703
+ }
1704
+
1705
+ export async function POST(request: NextRequest) {
1706
+ const body = await request.json();
1707
+ return callFunction({
1708
+ method: 'POST',
1709
+ path: '/api/{model}',
1710
+ body,
1711
+ inputSchema: ModelSchema.omit({ id: true, createdAt: true, updatedAt: true }),
1712
+ responseSchema: ModelSchema,
1713
+ successStatus: 201,
1714
+ });
1715
+ }
1716
+ \`\`\`
1717
+
1718
+ ### 2. Zod Schemas Are the Single Source of Truth
1719
+
1720
+ - All data models are defined **once** as Zod schemas in \`shared/models/\`.
1721
+ - TypeScript types are derived with \`z.infer<typeof Schema>\` — never define types separately.
1722
+ - ${backendSchemaNote}
1723
+
1724
+ Model definition pattern:
1725
+
1726
+ \`\`\`typescript
1727
+ // shared/models/{model}.ts
1728
+ import { z } from 'zod/v4';
1729
+
1730
+ export const Todo = z.object({
1731
+ id: z.string(),
1732
+ name: z.string().min(1),
1733
+ // ... your fields
1734
+ createdAt: z.string().optional(),
1735
+ updatedAt: z.string().optional(),
1736
+ });
1737
+
1738
+ export type Todo = z.infer<typeof Todo>;
1739
+ export const displayName = 'Todo';
1740
+ \`\`\`
1741
+
1742
+ Key rules:
1743
+ - Use the **Zod official pattern**: the schema constant and the TypeScript type share the same name.
1744
+ - \`id\`, \`createdAt\`, and \`updatedAt\` are auto-managed by the backend. Mark them as \`optional()\` in the schema.
1745
+ - Always re-export models from \`shared/index.ts\`.
1746
+
1747
+ ### 3. Azure Functions Own All Business Logic and Data Access
1748
+
1749
+ - ${backendRulesNote}
1750
+
1751
+ ${backendLanguage === 'typescript' ? 'Azure Functions handler pattern:' : `Generated ${backendLanguageLabel} handlers live under \`functions/\`. Re-run \`swallowkit scaffold shared/models/<name>.ts\` after schema changes to keep generated CRUD handlers and \`functions/generated/\` in sync.`}
1752
+
1753
+ ${backendLanguage === 'typescript' ? `\`\`\`typescript
1754
+ // functions/src/{model}.ts
1755
+ import { app } from '@azure/functions';
1756
+ import { ModelSchema } from '@${projectName}/shared';
1757
+
1758
+ const containerName = 'Models'; // PascalCase + 's'
1759
+
1760
+ app.http('{model}-get-all', {
1761
+ methods: ['GET'],
1762
+ route: '{model}',
1763
+ authLevel: 'anonymous',
1764
+ extraInputs: [{ type: 'cosmosDB', name: 'cosmosInput', containerName, ... }],
1765
+ handler: async (request, context) => {
1766
+ const documents = context.extraInputs.get('cosmosInput');
1767
+ const validated = z.array(ModelSchema).parse(documents);
1768
+ return { status: 200, jsonBody: validated };
1769
+ },
1770
+ });
1771
+ \`\`\`` : ''}
1772
+
1773
+ ## Naming Conventions
1774
+
1775
+ | Item | Convention | Example |
1776
+ |------|-----------|---------|
1777
+ | Model schema file | \`shared/models/{kebab-case}.ts\` | \`shared/models/todo.ts\` |
1778
+ | Schema/type name | PascalCase (same name for both) | \`export const Todo = z.object({...}); export type Todo = z.infer<typeof Todo>;\` |
1779
+ | Functions handler file | backend-language specific under \`functions/\` | \`${backendLanguage === 'typescript' ? 'functions/src/todo.ts' : backendLanguage === 'csharp' ? 'functions/Crud/TodoFunctions.cs' : 'functions/blueprints/todo.py'}\` |
1780
+ | Functions handler name | \`{camelCase}-{operation}\` | \`todo-get-all\`, \`todo-create\` |
1781
+ | API route path | \`/api/{camelCase}\` | \`/api/todo\`, \`/api/todo/{id}\` |
1782
+ | BFF route file | \`app/api/{kebab-case}/route.ts\` | \`app/api/todo/route.ts\` |
1783
+ | BFF detail route | \`app/api/{kebab-case}/[id]/route.ts\` | \`app/api/todo/[id]/route.ts\` |
1784
+ | UI page directory | \`app/{kebab-case}/\` | \`app/todo/page.tsx\` |
1785
+ | React component | PascalCase | \`TodoForm.tsx\` |
1786
+ | Cosmos DB container | PascalCase + 's' | \`Todos\` |
1787
+ | Cosmos DB partition key | \`/id\` (default) | Custom: \`export const partitionKey = '/field'\` |
1788
+ | Bicep container file | \`infra/containers/{kebab-case}-container.bicep\` | \`infra/containers/todo-container.bicep\` |
1789
+
1790
+ ## Adding New Models (SwallowKit CLI Skills)
1791
+
1792
+ Use the SwallowKit CLI — do **not** manually create model files or CRUD boilerplate.
1793
+
1794
+ ### Skill: Create a new data model
1795
+
1796
+ \`\`\`bash
1797
+ npx swallowkit create-model <name>
1798
+ # Multiple models at once:
1799
+ npx swallowkit create-model user post comment
1800
+ \`\`\`
1801
+
1802
+ Creates \`shared/models/<name>.ts\` with a Zod schema template including \`id\`, \`createdAt\`, \`updatedAt\`.
1803
+ Edit the generated file to add your domain-specific fields, then run scaffold.
1804
+
1805
+ ### Skill: Generate full CRUD from a model
1806
+
1807
+ \`\`\`bash
1808
+ npx swallowkit scaffold shared/models/<name>.ts
1809
+ \`\`\`
1810
+
1811
+ Generates:
1812
+ - Azure Functions handlers (${backendLanguage === 'typescript' ? '`functions/src/<name>.ts`' : '`functions/` language-specific CRUD files + `functions/generated/` schema assets'})
1813
+ - BFF API routes (\`app/api/<name>/route.ts\`, \`app/api/<name>/[id]/route.ts\`)
1814
+ - UI pages (\`app/<name>/page.tsx\`, detail, create, edit pages)
1815
+ - Cosmos DB Bicep container config (\`infra/containers/<name>-container.bicep\`)
1816
+
1817
+ ### Skill: Start development servers
1818
+
1819
+ \`\`\`bash
1820
+ npx swallowkit dev
1821
+ \`\`\`
1822
+
1823
+ Runs Next.js (http://localhost:3000) and Azure Functions (http://localhost:7071) concurrently.
1824
+ Checks for Cosmos DB Emulator availability.
1825
+
1826
+ ### Skill: Provision Azure resources
1827
+
1828
+ \`\`\`bash
1829
+ npx swallowkit provision --resource-group <name> --location <region>
1830
+ \`\`\`
1831
+
1832
+ Deploys Bicep infrastructure: Static Web Apps, Functions, Cosmos DB, Storage, Managed Identity.
1833
+
1834
+ ### Typical workflow for "add a new feature/model"
1835
+
1836
+ 1. \`npx swallowkit create-model <name>\`
1837
+ 2. Edit \`shared/models/<name>.ts\` — add fields
1838
+ 3. \`npx swallowkit scaffold shared/models/<name>.ts\`
1839
+ 4. \`npx swallowkit dev\` — verify at http://localhost:3000/<name>
1840
+
1841
+ ## Do NOT
1842
+
1843
+ - **Do not** put business logic or database calls in \`app/api/\` routes. They are BFF only.
1844
+ - **Do not** define TypeScript interfaces/types separately from Zod schemas. Always derive types with \`z.infer<>\`.
1845
+ - **Do not** manually duplicate model definitions across layers. Use the shared package.
1846
+ - **Do not** manually create CRUD boilerplate. Use \`swallowkit scaffold\`.
1847
+ - **Do not** hardcode Cosmos DB connection strings. Use Managed Identity (\`CosmosDBConnection__accountEndpoint\`) in production and emulator settings locally.
1848
+ - By default, all containers use \`/id\` as the partition key. To use a custom partition key, add \`export const partitionKey = '/yourField'\` to the model file. The scaffold command will apply it across all layers.
1849
+
1850
+ ## Technology Stack
1851
+
1852
+ - **Frontend**: Next.js (App Router), React, TypeScript, Tailwind CSS
1853
+ - **BFF**: Next.js API Routes (proxy only)
1854
+ - **Backend**: Azure Functions (${backendLanguageLabel})
1855
+ - **Database**: Azure Cosmos DB (NoSQL)
1856
+ - **Schema**: Zod (shared across all layers via workspace package)
1857
+ - **Infrastructure**: Bicep (IaC)
1858
+ - **Hosting**: Azure Static Web Apps (frontend) + Azure Functions Flex Consumption (backend)
1859
+ - **Auth**: Azure Managed Identity (no connection strings in production)
1860
+ - **Monitoring**: Application Insights
1861
+ `;
1862
+
1863
+ fs.writeFileSync(path.join(projectDir, 'AGENTS.md'), agentsMd);
1864
+ console.log(' ✅ AGENTS.md (Codex / generic agents)');
1865
+
1866
+ // ── 2. CLAUDE.md (Claude Code) ─────────────────────────────────────
1867
+
1868
+ const claudeMd = `# CLAUDE.md
1869
+
1870
+ This file is for Claude Code. Read AGENTS.md in the project root for the full architecture, conventions, and rules.
1871
+
1872
+ ## Quick Reference
1873
+
1874
+ - **Architecture**: Next.js (frontend) → BFF (API routes, proxy only) → Azure Functions (backend) → Cosmos DB
1875
+ - **Schema**: Zod schemas in \`shared/models/\` are the single source of truth. Never define types separately.
1876
+ - **BFF rule**: \`app/api/\` routes must ONLY proxy to Azure Functions via \`callFunction()\`. No business logic.
1877
+ - **Backend language**: ${backendLanguageLabel}
1878
+ - **Backend rule**: Regenerate backend contracts with \`swallowkit scaffold\` after schema changes and keep \`functions/generated/\` in sync.
1879
+
1880
+ ## SwallowKit CLI Commands
1881
+
1882
+ | Task | Command |
1883
+ |------|---------|
1884
+ | Create model | \`npx swallowkit create-model <name>\` |
1885
+ | Generate CRUD | \`npx swallowkit scaffold shared/models/<name>.ts\` |
1886
+ | Dev servers | \`npx swallowkit dev\` |
1887
+ | Provision Azure | \`npx swallowkit provision --resource-group <rg> --location <region>\` |
1888
+
1889
+ ## Workflow: Add a new model
1890
+
1891
+ 1. \`npx swallowkit create-model <name>\`
1892
+ 2. Edit \`shared/models/<name>.ts\` — add your fields
1893
+ 3. \`npx swallowkit scaffold shared/models/<name>.ts\`
1894
+ 4. \`npx swallowkit dev\` — verify at http://localhost:3000/<name>
1895
+ `;
1896
+
1897
+ fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), claudeMd);
1898
+ console.log(' ✅ CLAUDE.md (Claude Code)');
1899
+
1900
+ // ── 3. .github/copilot-instructions.md (GitHub Copilot) ────────────
1901
+
1902
+ const ghDir = path.join(projectDir, '.github');
1903
+ fs.mkdirSync(ghDir, { recursive: true });
1904
+
1905
+ const copilotInstructions = `# Copilot Instructions
1906
+
1907
+ This project was generated by **SwallowKit**. See \`AGENTS.md\` in the project root for the full specification.
1908
+
1909
+ ## Architecture (3-layer)
1910
+
1911
+ \`\`\`
1912
+ Frontend (Next.js App Router) → BFF (Next.js API Routes) → Backend (Azure Functions) → Cosmos DB
1913
+ \`\`\`
1914
+
1915
+ ## Key Rules
1916
+
1917
+ 1. **BFF is proxy only** — \`app/api/\` routes call Azure Functions via \`callFunction()\`. No business logic, no direct DB access.
1918
+ 2. **Zod = single source of truth** — Models live in \`shared/models/\`. Types are derived with \`z.infer<>\`. Never define types separately.
1919
+ 3. **Backend owns data** — All CRUD and business logic stay in \`functions/\`, and generated contract assets under \`functions/generated/\` must stay aligned with \`shared/models/\`.
1920
+ 4. **Use the CLI** — Run \`npx swallowkit create-model <name>\` then \`npx swallowkit scaffold shared/models/<name>.ts\` to add models. Do not create boilerplate manually.
1921
+
1922
+ ## Naming
1923
+
1924
+ - Schema/type: PascalCase, same name for both (\`export const Todo = z.object({...}); export type Todo = z.infer<typeof Todo>;\`)
1925
+ - Files: kebab-case (\`shared/models/todo.ts\`, backend handlers under \`functions/\`)
1926
+ - Cosmos DB containers: PascalCase + 's' (\`Todos\`), partition key default \`/id\` (customizable via \`export const partitionKey\`)
1927
+
1928
+ ## Managed Fields
1929
+
1930
+ \`id\`, \`createdAt\`, \`updatedAt\` are auto-managed by the backend. Define them as \`optional()\` in schemas. Never trust client-sent values.
1931
+ `;
1932
+
1933
+ fs.writeFileSync(path.join(ghDir, 'copilot-instructions.md'), copilotInstructions);
1934
+ console.log(' ✅ .github/copilot-instructions.md (GitHub Copilot)');
1935
+
1936
+ // ── 4. .github/instructions/*.instructions.md (Copilot layer-specific) ──
1937
+
1938
+ const instructionsDir = path.join(ghDir, 'instructions');
1939
+ fs.mkdirSync(instructionsDir, { recursive: true });
1940
+
1941
+ // 4a. shared/models — Zod schema layer
1942
+ const sharedModelsInstructions = `---
1943
+ applyTo: "shared/models/**"
1944
+ ---
1945
+
1946
+ # Shared Models — Zod Schema Rules
1947
+
1948
+ Files in this directory are the **single source of truth** for data models across the entire application.
1949
+
1950
+ ## Rules
1951
+
1952
+ - Define Zod schemas using \`zod/v4\` (\`import { z } from 'zod/v4'\`).
1953
+ - Use the **Zod official pattern**: the schema constant and the TypeScript type share the same name.
1954
+ \`\`\`typescript
1955
+ export const Todo = z.object({ ... });
1956
+ export type Todo = z.infer<typeof Todo>;
1957
+ \`\`\`
1958
+ - Always include \`id: z.string()\`, \`createdAt: z.string().optional()\`, \`updatedAt: z.string().optional()\`. These are managed by the backend.
1959
+ - Export a \`displayName\` string constant for UI display.
1960
+ - Re-export every model from \`shared/index.ts\`.
1961
+ - For relationships, use **nested schemas** (import and embed the related schema), not ID references.
1962
+ - After editing a model, run \`npx swallowkit scaffold shared/models/<name>.ts\` to regenerate CRUD code.
1963
+ `;
1964
+
1965
+ fs.writeFileSync(
1966
+ path.join(instructionsDir, 'shared-models.instructions.md'),
1967
+ sharedModelsInstructions
1968
+ );
1969
+
1970
+ // 4b. app/api — BFF layer
1971
+ const bffInstructions = `---
1972
+ applyTo: "app/api/**"
1973
+ ---
1974
+
1975
+ # BFF API Routes — Rules
1976
+
1977
+ Files in \`app/api/\` are the **BFF (Backend for Frontend)** layer. They exist solely to proxy requests to Azure Functions.
1978
+
1979
+ ## Rules
1980
+
1981
+ - **Never** put business logic, database access, or direct Cosmos DB calls here.
1982
+ - Use \`callFunction()\` from \`@/lib/api/call-function\` to forward requests to Azure Functions.
1983
+ - You may validate input/output with Zod schemas before forwarding.
1984
+ - Import schemas from \`@${projectName}/shared\`.
1985
+
1986
+ ## Pattern
1987
+
1988
+ \`\`\`typescript
1989
+ import { callFunction } from '@/lib/api/call-function';
1990
+ import { ModelSchema } from '@${projectName}/shared';
1991
+ import { z } from 'zod/v4';
1992
+
1993
+ export async function GET() {
1994
+ return callFunction({
1995
+ method: 'GET',
1996
+ path: '/api/{model}',
1997
+ responseSchema: z.array(ModelSchema),
1998
+ });
1999
+ }
2000
+ \`\`\`
2001
+ `;
2002
+
2003
+ fs.writeFileSync(
2004
+ path.join(instructionsDir, 'bff-routes.instructions.md'),
2005
+ bffInstructions
2006
+ );
2007
+
2008
+ // 4c. functions — Azure Functions backend layer
2009
+ const functionsInstructions = `---
2010
+ applyTo: "functions/**"
2011
+ ---
2012
+
2013
+ # Azure Functions — Backend Rules
2014
+
2015
+ Files in \`functions/\` contain all business logic and data access for this application.
2016
+
2017
+ ## Rules
2018
+
2019
+ - Keep backend contracts aligned with \`shared/models/\` by rerunning \`swallowkit scaffold\` after schema changes.
2020
+ - For TypeScript backends, use Cosmos DB **input/output bindings** (\`extraInputs\`/\`extraOutputs\`) for reads and writes.
2021
+ - For C#/Python backends, consume the generated OpenAPI-derived assets in \`functions/generated/\`.
2022
+ - Auto-generate \`id\` (UUID), \`createdAt\`, and \`updatedAt\` on the backend. Never trust client-sent values.
2023
+ - Container names are PascalCase + 's' (e.g., \`Todos\`). Partition key defaults to \`/id\` but can be customized per model.
2024
+
2025
+ ## Handler Pattern
2026
+
2027
+ \`\`\`typescript
2028
+ import { app } from '@azure/functions';
2029
+ import { ModelSchema } from '@${projectName}/shared';
2030
+
2031
+ app.http('{model}-get-all', {
2032
+ methods: ['GET'],
2033
+ route: '{model}',
2034
+ authLevel: 'anonymous',
2035
+ extraInputs: [cosmosInput],
2036
+ handler: async (request, context) => {
2037
+ const documents = context.extraInputs.get(cosmosInput);
2038
+ const validated = z.array(ModelSchema).parse(documents);
2039
+ return { status: 200, jsonBody: validated };
2040
+ },
2041
+ });
2042
+ \`\`\`
2043
+ `;
2044
+
2045
+ fs.writeFileSync(
2046
+ path.join(instructionsDir, 'azure-functions.instructions.md'),
2047
+ functionsInstructions
2048
+ );
2049
+
2050
+ console.log(' ✅ .github/instructions/ (Copilot layer-specific instructions)');
2051
+ console.log(' - shared-models.instructions.md');
2052
+ console.log(' - bff-routes.instructions.md');
2053
+ console.log(' - azure-functions.instructions.md');
2054
+
2055
+ console.log('\n✅ AI agent files created\n');
2056
+ console.log(' Supported agents:');
2057
+ console.log(' - OpenAI Codex → AGENTS.md');
2058
+ console.log(' - Claude Code → CLAUDE.md (+ AGENTS.md)');
2059
+ console.log(' - GitHub Copilot → .github/copilot-instructions.md');
2060
+ console.log(' - GitHub Copilot (edit) → .github/instructions/*.instructions.md');
2061
+ console.log('');
2062
+ }
2063
+
2064
+ async function createInfrastructure(
2065
+ projectDir: string,
2066
+ projectName: string,
2067
+ azureConfig: AzureConfig,
2068
+ backendLanguage: BackendLanguage
2069
+ ) {
2070
+ console.log('📦 Creating infrastructure files (Bicep)...\n');
2071
+
2072
+ const infraDir = path.join(projectDir, 'infra');
2073
+ const modulesDir = path.join(infraDir, 'modules');
2074
+ fs.mkdirSync(modulesDir, { recursive: true });
2075
+
2076
+ const enableVNet = azureConfig.vnetOption !== 'none';
2077
+ const functionsRuntime = getFunctionsRuntimeConfig(backendLanguage);
2078
+
2079
+ // main.bicep
2080
+ const mainBicep = `targetScope = 'resourceGroup'
2081
+
2082
+ @description('Project name')
2083
+ param projectName string
2084
+
2085
+ @description('Location for Functions and Cosmos DB')
2086
+ param location string = resourceGroup().location
2087
+
2088
+ @description('Location for Static Web App (must be explicitly provided)')
2089
+ param swaLocation string
2090
+
2091
+ @description('Cosmos DB mode')
2092
+ @allowed(['freetier', 'serverless'])
2093
+ param cosmosDbMode string = '${azureConfig.cosmosDbMode}'
2094
+
2095
+ @description('Enable VNet integration')
2096
+ param enableVNet bool = ${enableVNet}
2097
+
2098
+ // Shared Log Analytics Workspace (in Functions region for data residency)
2099
+ module logAnalytics 'modules/loganalytics.bicep' = {
2100
+ name: 'logAnalytics'
2101
+ params: {
2102
+ name: 'log-\${projectName}'
2103
+ location: location
2104
+ }
2105
+ }
2106
+
2107
+ // Application Insights for Static Web App (must be in same region as SWA)
2108
+ module appInsightsSwa 'modules/appinsights.bicep' = {
2109
+ name: 'appInsightsSwa'
2110
+ params: {
2111
+ name: 'appi-\${projectName}-swa'
2112
+ location: swaLocation
2113
+ logAnalyticsWorkspaceId: logAnalytics.outputs.id
2114
+ }
2115
+ }
2116
+
2117
+ // Application Insights for Functions (in same region as Functions)
2118
+ module appInsightsFunctions 'modules/appinsights.bicep' = {
2119
+ name: 'appInsightsFunctions'
2120
+ params: {
2121
+ name: 'appi-\${projectName}-func'
2122
+ location: location
2123
+ logAnalyticsWorkspaceId: logAnalytics.outputs.id
2124
+ }
2125
+ }
2126
+
2127
+ // Static Web App
2128
+ module staticWebApp 'modules/staticwebapp.bicep' = {
2129
+ name: 'staticWebApp'
2130
+ params: {
2131
+ name: 'swa-\${projectName}'
2132
+ location: swaLocation
2133
+ sku: 'Standard'
2134
+ appInsightsConnectionString: appInsightsSwa.outputs.connectionString
2135
+ }
2136
+ }
2137
+
2138
+ // VNet (conditional)
2139
+ module vnet 'modules/vnet.bicep' = if (enableVNet) {
2140
+ name: 'vnet'
2141
+ params: {
2142
+ name: 'vnet-\${projectName}'
2143
+ location: location
2144
+ }
2145
+ }
2146
+
2147
+ // Cosmos DB (conditional based on mode) - Deploy BEFORE Functions
2148
+ module cosmosDbFreeTier 'modules/cosmosdb-freetier.bicep' = if (cosmosDbMode == 'freetier') {
2149
+ name: 'cosmosDb'
2150
+ params: {
2151
+ accountName: 'cosmos-\${projectName}'
2152
+ databaseName: '\${projectName}Database'
2153
+ location: location
2154
+ publicNetworkAccess: enableVNet ? 'Disabled' : 'Enabled'
2155
+ }
2156
+ }
2157
+
2158
+ module cosmosDbServerless 'modules/cosmosdb-serverless.bicep' = if (cosmosDbMode == 'serverless') {
2159
+ name: 'cosmosDb'
2160
+ params: {
2161
+ accountName: 'cosmos-\${projectName}'
2162
+ databaseName: '\${projectName}Database'
2163
+ location: location
2164
+ publicNetworkAccess: enableVNet ? 'Disabled' : 'Enabled'
2165
+ }
2166
+ }
2167
+
2168
+ // Cosmos DB Private Endpoint (conditional)
2169
+ module cosmosPrivateEndpoint 'modules/private-endpoint-cosmos.bicep' = if (enableVNet) {
2170
+ name: 'cosmosPrivateEndpoint'
2171
+ params: {
2172
+ name: 'pe-cosmos-\${projectName}'
2173
+ location: location
2174
+ cosmosAccountId: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.id : cosmosDbServerless.outputs.id
2175
+ cosmosAccountName: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.accountName : cosmosDbServerless.outputs.accountName
2176
+ subnetId: vnet.outputs.privateEndpointSubnetId
2177
+ vnetId: vnet.outputs.id
2178
+ }
2179
+ dependsOn: [
2180
+ cosmosDbFreeTier
2181
+ cosmosDbServerless
2182
+ vnet
2183
+ ]
2184
+ }
2185
+
2186
+ // Azure Functions (Flex Consumption) - Deploy AFTER Cosmos DB
2187
+ module functionsFlex 'modules/functions-flex.bicep' = {
2188
+ name: 'functionsApp'
2189
+ params: {
2190
+ name: 'func-\${projectName}'
2191
+ location: location
2192
+ storageAccountName: 'stg\${uniqueString(resourceGroup().id, projectName)}'
2193
+ appInsightsConnectionString: appInsightsFunctions.outputs.connectionString
2194
+ swaDefaultHostname: staticWebApp.outputs.defaultHostname
2195
+ cosmosDbEndpoint: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.endpoint : cosmosDbServerless.outputs.endpoint
2196
+ cosmosDbDatabaseName: cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.databaseName : cosmosDbServerless.outputs.databaseName
2197
+ functionsRuntimeName: '${functionsRuntime.name}'
2198
+ functionsRuntimeVersion: '${functionsRuntime.version}'
2199
+ enableVNet: enableVNet
2200
+ vnetSubnetId: enableVNet ? vnet.outputs.functionsSubnetId : ''
2201
+ }
2202
+ dependsOn: [
2203
+ cosmosDbFreeTier
2204
+ cosmosDbServerless
2205
+ cosmosPrivateEndpoint
2206
+ ]
2207
+ }
2208
+
2209
+ // Cosmos DB role assignment for Functions (after Functions is created)
2210
+ module cosmosDbRoleAssignmentFreeTier 'modules/cosmosdb-role-assignment.bicep' = if (cosmosDbMode == 'freetier') {
2211
+ name: 'cosmosDbRoleAssignment'
2212
+ params: {
2213
+ cosmosAccountName: cosmosDbFreeTier.outputs.accountName
2214
+ functionsPrincipalId: functionsFlex.outputs.principalId
2215
+ }
2216
+ dependsOn: [
2217
+ functionsFlex
2218
+ ]
2219
+ }
2220
+
2221
+ module cosmosDbRoleAssignmentServerless 'modules/cosmosdb-role-assignment.bicep' = if (cosmosDbMode == 'serverless') {
2222
+ name: 'cosmosDbRoleAssignment'
2223
+ params: {
2224
+ cosmosAccountName: cosmosDbServerless.outputs.accountName
2225
+ functionsPrincipalId: functionsFlex.outputs.principalId
2226
+ }
2227
+ dependsOn: [
2228
+ functionsFlex
2229
+ ]
2230
+ }
2231
+
2232
+ // Update SWA config with Functions hostname (after Functions deployment)
2233
+ module staticWebAppConfig 'modules/staticwebapp-config.bicep' = {
2234
+ name: 'staticWebAppConfig'
2235
+ params: {
2236
+ staticWebAppName: staticWebApp.outputs.name
2237
+ functionsDefaultHostname: functionsFlex.outputs.defaultHostname
2238
+ appInsightsConnectionString: appInsightsSwa.outputs.connectionString
2239
+ }
2240
+ dependsOn: [
2241
+ functionsFlex
2242
+ ]
2243
+ }
2244
+
2245
+ output staticWebAppName string = staticWebApp.outputs.name
2246
+ output staticWebAppUrl string = staticWebApp.outputs.defaultHostname
2247
+ output functionsAppName string = functionsFlex.outputs.name
2248
+ output functionsAppUrl string = functionsFlex.outputs.defaultHostname
2249
+ output cosmosDbAccountName string = cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.accountName : cosmosDbServerless.outputs.accountName
2250
+ output cosmosDbEndpoint string = cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.endpoint : cosmosDbServerless.outputs.endpoint
2251
+ output cosmosDatabaseName string = cosmosDbMode == 'freetier' ? cosmosDbFreeTier.outputs.databaseName : cosmosDbServerless.outputs.databaseName
2252
+ output logAnalyticsWorkspaceName string = logAnalytics.outputs.name
2253
+ output logAnalyticsWorkspaceId string = logAnalytics.outputs.id
2254
+ output appInsightsSwaName string = appInsightsSwa.outputs.name
2255
+ output appInsightsSwaConnectionString string = appInsightsSwa.outputs.connectionString
2256
+ output appInsightsFunctionsName string = appInsightsFunctions.outputs.name
2257
+ output appInsightsFunctionsConnectionString string = appInsightsFunctions.outputs.connectionString
2258
+ output vnetEnabled bool = enableVNet
2259
+ output vnetName string = enableVNet ? vnet.outputs.name : ''
2260
+ `;
2261
+
2262
+ fs.writeFileSync(path.join(infraDir, 'main.bicep'), mainBicep);
2263
+
2264
+ // main.parameters.json
2265
+ const params = `{
2266
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
2267
+ "contentVersion": "1.0.0.0",
2268
+ "parameters": {
2269
+ "projectName": {
2270
+ "value": "${projectName}"
2271
+ },
2272
+ "cosmosDbMode": {
2273
+ "value": "${azureConfig.cosmosDbMode}"
2274
+ },
2275
+ "enableVNet": {
2276
+ "value": ${enableVNet}
2277
+ }
2278
+ }
2279
+ }
2280
+ `;
2281
+ fs.writeFileSync(path.join(infraDir, 'main.parameters.json'), params);
2282
+
2283
+ // modules/staticwebapp.bicep
2284
+ const staticWebAppBicep = `@description('Static Web App name')
2285
+ param name string
2286
+
2287
+ @description('Location for the Static Web App')
2288
+ param location string
2289
+
2290
+ @description('SKU name (Free or Standard)')
2291
+ @allowed([
2292
+ 'Free'
2293
+ 'Standard'
2294
+ ])
2295
+ param sku string = 'Standard'
2296
+
2297
+ @description('Application Insights connection string')
2298
+ param appInsightsConnectionString string
2299
+
2300
+ resource staticWebApp 'Microsoft.Web/staticSites@2023-01-01' = {
2301
+ name: name
2302
+ location: location
2303
+ sku: {
2304
+ name: sku
2305
+ tier: sku
2306
+ }
2307
+ properties: {
2308
+ buildProperties: {
2309
+ skipGithubActionWorkflowGeneration: true
2310
+ }
2311
+ }
2312
+ }
2313
+
2314
+ // Link Application Insights to Static Web App (for both client and server-side telemetry)
2315
+ resource staticWebAppConfig 'Microsoft.Web/staticSites/config@2023-01-01' = {
2316
+ parent: staticWebApp
2317
+ name: 'appsettings'
2318
+ properties: {
2319
+ APPLICATIONINSIGHTS_CONNECTION_STRING: appInsightsConnectionString
2320
+ ApplicationInsightsAgent_EXTENSION_VERSION: '~3'
2321
+ }
2322
+ }
2323
+
2324
+ output id string = staticWebApp.id
2325
+ output name string = staticWebApp.name
2326
+ output defaultHostname string = staticWebApp.properties.defaultHostname
2327
+ `;
2328
+ fs.writeFileSync(path.join(modulesDir, 'staticwebapp.bicep'), staticWebAppBicep);
2329
+
2330
+ // modules/staticwebapp-config.bicep (for updating config after Functions deployment)
2331
+ const staticWebAppConfigBicep = `@description('Static Web App name')
2332
+ param staticWebAppName string
2333
+
2334
+ @description('Functions App default hostname for backend API calls')
2335
+ param functionsDefaultHostname string
2336
+
2337
+ @description('Application Insights connection string for SWA')
2338
+ param appInsightsConnectionString string
2339
+
2340
+ resource staticWebApp 'Microsoft.Web/staticSites@2023-01-01' existing = {
2341
+ name: staticWebAppName
2342
+ }
2343
+
2344
+ resource staticWebAppConfig 'Microsoft.Web/staticSites/config@2023-01-01' = {
2345
+ parent: staticWebApp
2346
+ name: 'appsettings'
2347
+ properties: {
2348
+ APPLICATIONINSIGHTS_CONNECTION_STRING: appInsightsConnectionString
2349
+ ApplicationInsightsAgent_EXTENSION_VERSION: '~3'
2350
+ BACKEND_FUNCTIONS_BASE_URL: 'https://\${functionsDefaultHostname}'
2351
+ }
2352
+ }
2353
+
2354
+ output configName string = staticWebAppConfig.name
2355
+ `;
2356
+ fs.writeFileSync(path.join(modulesDir, 'staticwebapp-config.bicep'), staticWebAppConfigBicep);
2357
+
2358
+ // modules/loganalytics.bicep (Shared Log Analytics Workspace)
2359
+ const logAnalyticsBicep = `@description('Log Analytics workspace name')
2360
+ param name string
2361
+
2362
+ @description('Location for Log Analytics workspace')
2363
+ param location string
2364
+
2365
+ resource logAnalytics 'Microsoft.OperationalInsights/workspaces@2023-09-01' = {
2366
+ name: name
2367
+ location: location
2368
+ properties: {
2369
+ sku: {
2370
+ name: 'PerGB2018'
2371
+ }
2372
+ retentionInDays: 30
2373
+ }
2374
+ }
2375
+
2376
+ output id string = logAnalytics.id
2377
+ output name string = logAnalytics.name
2378
+ `;
2379
+ fs.writeFileSync(path.join(modulesDir, 'loganalytics.bicep'), logAnalyticsBicep);
2380
+
2381
+ // modules/appinsights.bicep (Application Insights only, connects to shared Log Analytics)
2382
+ const appInsightsBicep = `@description('Application Insights name')
2383
+ param name string
2384
+
2385
+ @description('Location for Application Insights')
2386
+ param location string
2387
+
2388
+ @description('Log Analytics workspace resource ID')
2389
+ param logAnalyticsWorkspaceId string
2390
+
2391
+ // Application Insights
2392
+ resource appInsights 'Microsoft.Insights/components@2020-02-02' = {
2393
+ name: name
2394
+ location: location
2395
+ kind: 'web'
2396
+ properties: {
2397
+ Application_Type: 'web'
2398
+ WorkspaceResourceId: logAnalyticsWorkspaceId
2399
+ RetentionInDays: 30
2400
+ }
2401
+ }
2402
+
2403
+ output id string = appInsights.id
2404
+ output name string = appInsights.name
2405
+ output connectionString string = appInsights.properties.ConnectionString
2406
+ output instrumentationKey string = appInsights.properties.InstrumentationKey
2407
+ `;
2408
+ fs.writeFileSync(path.join(modulesDir, 'appinsights.bicep'), appInsightsBicep);
2409
+
2410
+ // modules/functions-flex.bicep (Flex Consumption)
2411
+ const functionsFlexBicep = `@description('Functions App name')
2412
+ param name string
2413
+
2414
+ @description('Location for the Functions App')
2415
+ param location string
2416
+
2417
+ @description('Storage account name for Functions')
2418
+ param storageAccountName string
2419
+
2420
+ @description('Application Insights connection string')
2421
+ param appInsightsConnectionString string
2422
+
2423
+ @description('Static Web App default hostname for CORS')
2424
+ param swaDefaultHostname string
2425
+
2426
+ @description('Cosmos DB endpoint')
2427
+ param cosmosDbEndpoint string
2428
+
2429
+ @description('Cosmos DB database name')
2430
+ param cosmosDbDatabaseName string
2431
+
2432
+ @description('Enable VNet integration')
2433
+ param enableVNet bool = false
2434
+
2435
+ @description('VNet subnet ID for Functions (required if enableVNet is true)')
2436
+ param vnetSubnetId string = ''
2437
+
2438
+ @description('Functions runtime name')
2439
+ param functionsRuntimeName string
2440
+
2441
+ @description('Functions runtime version')
2442
+ param functionsRuntimeVersion string
2443
+
2444
+ // Storage Account for Functions
2445
+ resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
2446
+ name: storageAccountName
2447
+ location: location
2448
+ sku: {
2449
+ name: 'Standard_LRS'
2450
+ }
2451
+ kind: 'StorageV2'
2452
+ properties: {
2453
+ supportsHttpsTrafficOnly: true
2454
+ minimumTlsVersion: 'TLS1_2'
2455
+ }
2456
+ }
2457
+
2458
+ // Blob Service for deployment package container
2459
+ resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01' = {
2460
+ parent: storageAccount
2461
+ name: 'default'
2462
+ }
2463
+
2464
+ // Deployment package container
2465
+ resource deploymentContainer 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = {
2466
+ parent: blobService
2467
+ name: 'deploymentpackage'
2468
+ properties: {
2469
+ publicAccess: 'None'
2470
+ }
2471
+ }
2472
+
2473
+ // App Service Plan (Flex Consumption)
2474
+ resource hostingPlan 'Microsoft.Web/serverfarms@2023-12-01' = {
2475
+ name: '\${name}-plan'
2476
+ location: location
2477
+ sku: {
2478
+ name: 'FC1'
2479
+ tier: 'FlexConsumption'
2480
+ }
2481
+ properties: {
2482
+ reserved: true // Required for Linux
2483
+ }
2484
+ }
2485
+
2486
+ // Azure Functions App
2487
+ resource functionApp 'Microsoft.Web/sites@2023-12-01' = {
2488
+ name: name
2489
+ location: location
2490
+ kind: 'functionapp,linux'
2491
+ identity: {
2492
+ type: 'SystemAssigned'
2493
+ }
2494
+ properties: {
2495
+ serverFarmId: hostingPlan.id
2496
+ reserved: true
2497
+ virtualNetworkSubnetId: enableVNet ? vnetSubnetId : null
2498
+ vnetContentShareEnabled: enableVNet
2499
+ functionAppConfig: {
2500
+ deployment: {
2501
+ storage: {
2502
+ type: 'blobContainer'
2503
+ value: '\${storageAccount.properties.primaryEndpoints.blob}deploymentpackage'
2504
+ authentication: {
2505
+ type: 'SystemAssignedIdentity'
2506
+ }
2507
+ }
2508
+ }
2509
+ scaleAndConcurrency: {
2510
+ maximumInstanceCount: 100
2511
+ instanceMemoryMB: 2048
2512
+ }
2513
+ runtime: {
2514
+ name: functionsRuntimeName
2515
+ version: functionsRuntimeVersion
2516
+ }
2517
+ }
2518
+ siteConfig: {
2519
+ appSettings: [
2520
+ {
2521
+ name: 'AzureWebJobsStorage__accountName'
2522
+ value: storageAccount.name
2523
+ }
2524
+ {
2525
+ name: 'FUNCTIONS_EXTENSION_VERSION'
2526
+ value: '~4'
2527
+ }
2528
+ {
2529
+ name: 'APPLICATIONINSIGHTS_CONNECTION_STRING'
2530
+ value: appInsightsConnectionString
2531
+ }
2532
+ {
2533
+ name: 'CosmosDBConnection__accountEndpoint'
2534
+ value: cosmosDbEndpoint
2535
+ }
2536
+ {
2537
+ name: 'COSMOS_DB_DATABASE_NAME'
2538
+ value: cosmosDbDatabaseName
2539
+ }
2540
+ ]
2541
+ cors: {
2542
+ allowedOrigins: [
2543
+ 'https://\${swaDefaultHostname}'
2544
+ ]
2545
+ }
2546
+ ipSecurityRestrictions: [
2547
+ {
2548
+ action: 'Allow'
2549
+ ipAddress: 'AzureCloud'
2550
+ tag: 'ServiceTag'
2551
+ priority: 100
2552
+ }
2553
+ ]
2554
+ }
2555
+ httpsOnly: true
2556
+ }
2557
+ }
2558
+
2559
+ // Role Assignment: Storage Blob Data Contributor
2560
+ resource blobDataContributorRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
2561
+ name: guid(functionApp.id, storageAccount.id, 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')
2562
+ scope: storageAccount
2563
+ properties: {
2564
+ roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')
2565
+ principalId: functionApp.identity.principalId
2566
+ principalType: 'ServicePrincipal'
2567
+ }
2568
+ }
2569
+
2570
+ output id string = functionApp.id
2571
+ output name string = functionApp.name
2572
+ output defaultHostname string = functionApp.properties.defaultHostName
2573
+ output principalId string = functionApp.identity.principalId
2574
+ `;
2575
+ fs.writeFileSync(path.join(modulesDir, 'functions-flex.bicep'), functionsFlexBicep);
2576
+
2577
+ // modules/cosmosdb-freetier.bicep (Free Tier)
2578
+ const cosmosDbFreeTierBicep = `@description('Cosmos DB account name')
2579
+ param accountName string
2580
+
2581
+ @description('Database name')
2582
+ param databaseName string
2583
+
2584
+ @description('Location for Cosmos DB')
2585
+ param location string
2586
+
2587
+ @description('Public network access')
2588
+ @allowed(['Enabled', 'Disabled'])
2589
+ param publicNetworkAccess string = 'Enabled'
2590
+
2591
+ // Cosmos DB Account (Free Tier)
2592
+ resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {
2593
+ name: accountName
2594
+ location: location
2595
+ kind: 'GlobalDocumentDB'
2596
+ properties: {
2597
+ databaseAccountOfferType: 'Standard'
2598
+ enableAutomaticFailover: false
2599
+ enableFreeTier: true
2600
+ publicNetworkAccess: publicNetworkAccess
2601
+ disableLocalAuth: true
2602
+ consistencyPolicy: {
2603
+ defaultConsistencyLevel: 'Session'
2604
+ }
2605
+ locations: [
2606
+ {
2607
+ locationName: location
2608
+ failoverPriority: 0
2609
+ isZoneRedundant: false
2610
+ }
2611
+ ]
2612
+ disableKeyBasedMetadataWriteAccess: true
2613
+ }
2614
+ }
2615
+
2616
+ // Cosmos DB Database
2617
+ resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15' = {
2618
+ parent: cosmosAccount
2619
+ name: databaseName
2620
+ properties: {
2621
+ resource: {
2622
+ id: databaseName
2623
+ }
2624
+ options: {
2625
+ throughput: 1000
2626
+ }
2627
+ }
2628
+ }
2629
+
2630
+ output id string = cosmosAccount.id
2631
+ output accountName string = cosmosAccount.name
2632
+ output endpoint string = cosmosAccount.properties.documentEndpoint
2633
+ output databaseName string = database.name
2634
+ `;
2635
+ fs.writeFileSync(path.join(modulesDir, 'cosmosdb-freetier.bicep'), cosmosDbFreeTierBicep);
2636
+
2637
+ // modules/cosmosdb-serverless.bicep (Serverless)
2638
+ const cosmosDbServerlessBicep = `@description('Cosmos DB account name')
2639
+ param accountName string
2640
+
2641
+ @description('Database name')
2642
+ param databaseName string
2643
+
2644
+ @description('Location for Cosmos DB')
2645
+ param location string
2646
+
2647
+ @description('Public network access')
2648
+ @allowed(['Enabled', 'Disabled'])
2649
+ param publicNetworkAccess string = 'Enabled'
2650
+
2651
+ // Cosmos DB Account (Serverless)
2652
+ resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {
2653
+ name: accountName
2654
+ location: location
2655
+ kind: 'GlobalDocumentDB'
2656
+ properties: {
2657
+ databaseAccountOfferType: 'Standard'
2658
+ enableAutomaticFailover: false
2659
+ publicNetworkAccess: publicNetworkAccess
2660
+ disableLocalAuth: true
2661
+ consistencyPolicy: {
2662
+ defaultConsistencyLevel: 'Session'
2663
+ }
2664
+ locations: [
2665
+ {
2666
+ locationName: location
2667
+ failoverPriority: 0
2668
+ isZoneRedundant: false
2669
+ }
2670
+ ]
2671
+ capabilities: [
2672
+ {
2673
+ name: 'EnableServerless'
2674
+ }
2675
+ ]
2676
+ disableKeyBasedMetadataWriteAccess: true
2677
+ }
2678
+ }
2679
+
2680
+ // Cosmos DB Database
2681
+ resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15' = {
2682
+ parent: cosmosAccount
2683
+ name: databaseName
2684
+ properties: {
2685
+ resource: {
2686
+ id: databaseName
2687
+ }
2688
+ }
2689
+ }
2690
+
2691
+ output id string = cosmosAccount.id
2692
+ output accountName string = cosmosAccount.name
2693
+ output endpoint string = cosmosAccount.properties.documentEndpoint
2694
+ output databaseName string = database.name
2695
+ `;
2696
+ fs.writeFileSync(path.join(modulesDir, 'cosmosdb-serverless.bicep'), cosmosDbServerlessBicep);
2697
+
2698
+ // modules/cosmosdb-role-assignment.bicep (Role Assignment Module)
2699
+ const cosmosDbRoleAssignmentBicep = `@description('Cosmos DB account name')
2700
+ param cosmosAccountName string
2701
+
2702
+ @description('Functions App Managed Identity Principal ID')
2703
+ param functionsPrincipalId string
2704
+
2705
+ resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' existing = {
2706
+ name: cosmosAccountName
2707
+ }
2708
+
2709
+ // Built-in Cosmos DB Data Contributor role definition
2710
+ var cosmosDbDataContributorRoleId = '00000000-0000-0000-0000-000000000002'
2711
+
2712
+ // Role assignment for Functions to access Cosmos DB
2713
+ resource roleAssignment 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2023-11-15' = {
2714
+ parent: cosmosAccount
2715
+ name: guid(cosmosAccount.id, functionsPrincipalId, cosmosDbDataContributorRoleId)
2716
+ properties: {
2717
+ roleDefinitionId: '\${cosmosAccount.id}/sqlRoleDefinitions/\${cosmosDbDataContributorRoleId}'
2718
+ principalId: functionsPrincipalId
2719
+ scope: cosmosAccount.id
2720
+ }
2721
+ }
2722
+
2723
+ output roleAssignmentId string = roleAssignment.id
2724
+ `;
2725
+ fs.writeFileSync(path.join(modulesDir, 'cosmosdb-role-assignment.bicep'), cosmosDbRoleAssignmentBicep);
2726
+
2727
+ // VNet modules (only generate if VNet is enabled)
2728
+ if (enableVNet) {
2729
+ // modules/vnet.bicep
2730
+ const vnetBicep = `@description('VNet name')
2731
+ param name string
2732
+
2733
+ @description('Location for VNet')
2734
+ param location string
2735
+
2736
+ resource vnet 'Microsoft.Network/virtualNetworks@2023-09-01' = {
2737
+ name: name
2738
+ location: location
2739
+ properties: {
2740
+ addressSpace: {
2741
+ addressPrefixes: [
2742
+ '10.0.0.0/16'
2743
+ ]
2744
+ }
2745
+ subnets: [
2746
+ {
2747
+ name: 'snet-functions'
2748
+ properties: {
2749
+ addressPrefix: '10.0.1.0/24'
2750
+ delegations: [
2751
+ {
2752
+ name: 'delegation'
2753
+ properties: {
2754
+ serviceName: 'Microsoft.App/environments'
2755
+ }
2756
+ }
2757
+ ]
2758
+ }
2759
+ }
2760
+ {
2761
+ name: 'snet-private-endpoints'
2762
+ properties: {
2763
+ addressPrefix: '10.0.2.0/24'
2764
+ privateEndpointNetworkPolicies: 'Disabled'
2765
+ }
2766
+ }
2767
+ ]
2768
+ }
2769
+ }
2770
+
2771
+ output id string = vnet.id
2772
+ output name string = vnet.name
2773
+ output functionsSubnetId string = vnet.properties.subnets[0].id
2774
+ output privateEndpointSubnetId string = vnet.properties.subnets[1].id
2775
+ `;
2776
+ fs.writeFileSync(path.join(modulesDir, 'vnet.bicep'), vnetBicep);
2777
+
2778
+ // modules/private-endpoint-cosmos.bicep
2779
+ const cosmosPrivateEndpointBicep = `@description('Private endpoint name')
2780
+ param name string
2781
+
2782
+ @description('Location')
2783
+ param location string
2784
+
2785
+ @description('Cosmos DB account resource ID')
2786
+ param cosmosAccountId string
2787
+
2788
+ @description('Cosmos DB account name')
2789
+ param cosmosAccountName string
2790
+
2791
+ @description('Subnet ID for private endpoint')
2792
+ param subnetId string
2793
+
2794
+ @description('VNet ID for DNS zone link')
2795
+ param vnetId string
2796
+
2797
+ // Private DNS Zone for Cosmos DB
2798
+ resource privateDnsZone 'Microsoft.Network/privateDnsZones@2020-06-01' = {
2799
+ name: 'privatelink.documents.azure.com'
2800
+ location: 'global'
2801
+ }
2802
+
2803
+ // Link DNS Zone to VNet
2804
+ resource privateDnsZoneVnetLink 'Microsoft.Network/privateDnsZones/virtualNetworkLinks@2020-06-01' = {
2805
+ parent: privateDnsZone
2806
+ name: '\${cosmosAccountName}-vnet-link'
2807
+ location: 'global'
2808
+ properties: {
2809
+ virtualNetwork: {
2810
+ id: vnetId
2811
+ }
2812
+ registrationEnabled: false
2813
+ }
2814
+ }
2815
+
2816
+ // Private Endpoint for Cosmos DB
2817
+ resource privateEndpoint 'Microsoft.Network/privateEndpoints@2023-09-01' = {
2818
+ name: name
2819
+ location: location
2820
+ properties: {
2821
+ subnet: {
2822
+ id: subnetId
2823
+ }
2824
+ privateLinkServiceConnections: [
2825
+ {
2826
+ name: '\${cosmosAccountName}-connection'
2827
+ properties: {
2828
+ privateLinkServiceId: cosmosAccountId
2829
+ groupIds: [
2830
+ 'Sql'
2831
+ ]
2832
+ }
2833
+ }
2834
+ ]
2835
+ }
2836
+ }
2837
+
2838
+ // DNS Zone Group
2839
+ resource privateDnsZoneGroup 'Microsoft.Network/privateEndpoints/privateDnsZoneGroups@2023-09-01' = {
2840
+ parent: privateEndpoint
2841
+ name: 'default'
2842
+ properties: {
2843
+ privateDnsZoneConfigs: [
2844
+ {
2845
+ name: 'cosmos-dns-config'
2846
+ properties: {
2847
+ privateDnsZoneId: privateDnsZone.id
2848
+ }
2849
+ }
2850
+ ]
2851
+ }
2852
+ }
2853
+
2854
+ output privateEndpointId string = privateEndpoint.id
2855
+ output privateDnsZoneId string = privateDnsZone.id
2856
+ `;
2857
+ fs.writeFileSync(path.join(modulesDir, 'private-endpoint-cosmos.bicep'), cosmosPrivateEndpointBicep);
2858
+
2859
+ console.log('✅ VNet modules created\n');
2860
+ }
2861
+
2862
+ console.log('✅ Infrastructure files created\n');
2863
+ }
2864
+
2865
+ function getGitHubFunctionsWorkflow(pm: PackageManager, backendLanguage: BackendLanguage): string {
2866
+ const pmCmd = getCommands(pm);
2867
+ const pnpmSetupStep = getCiSetupStep(pm);
2868
+
2869
+ const commonSetup = ` - uses: actions/checkout@v4
2870
+
2871
+ - name: Setup Node.js
2872
+ uses: actions/setup-node@v4
2873
+ with:
2874
+ node-version: '22'
2875
+ ${pnpmSetupStep ? `\n${pnpmSetupStep}\n` : ''}
2876
+ - name: Install dependencies
2877
+ run: |
2878
+ ${pmCmd.ci}
2879
+
2880
+ - name: Build shared package
2881
+ run: |
2882
+ ${pmCmd.runFilter('shared')} build
2883
+ `;
2884
+
2885
+ if (backendLanguage === 'typescript') {
2886
+ return `name: Deploy Azure Functions
2887
+
2888
+ on:
2889
+ push:
2890
+ branches:
2891
+ - main
2892
+ paths:
2893
+ - 'functions/**'
2894
+ - 'shared/**'
2895
+ pull_request:
2896
+ branches:
2897
+ - main
2898
+ paths:
2899
+ - 'functions/**'
2900
+ - 'shared/**'
2901
+ workflow_dispatch:
2902
+
2903
+ jobs:
2904
+ build-and-deploy:
2905
+ runs-on: ubuntu-latest
2906
+ name: Build and Deploy Functions
2907
+
2908
+ steps:
2909
+ ${commonSetup} - name: Build Functions
2910
+ run: |
2911
+ ${pmCmd.runFilter('functions')} build
2912
+
2913
+ - name: Prepare functions for deployment
2914
+ run: |
2915
+ SHARED_PKG_NAME=$(node -p "require('./shared/package.json').name")
2916
+ mkdir -p /tmp/fn-deps
2917
+ node -e "const p=JSON.parse(require('fs').readFileSync('./functions/package.json','utf8'));Object.keys(p.dependencies).filter(k=>k.endsWith('/shared')).forEach(k=>delete p.dependencies[k]);require('fs').writeFileSync('/tmp/fn-deps/package.json',JSON.stringify(p,null,2));"
2918
+ cd /tmp/fn-deps && ${pmCmd.installProd} && cd -
2919
+ rm -rf ./functions/node_modules
2920
+ mv /tmp/fn-deps/node_modules ./functions/node_modules
2921
+ SHARED_DEST="./functions/node_modules/$SHARED_PKG_NAME"
2922
+ mkdir -p "$SHARED_DEST"
2923
+ cp -r ./shared/dist "$SHARED_DEST/dist"
2924
+ cp ./shared/package.json "$SHARED_DEST/package.json"
2925
+
2926
+ - name: Deploy to Azure Functions
2927
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
2928
+ uses: Azure/functions-action@v1
2929
+ with:
2930
+ app-name: \${{ secrets.AZURE_FUNCTIONAPP_NAME }}
2931
+ package: './functions'
2932
+ publish-profile: \${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }}
2933
+ sku: flexconsumption
2934
+ `;
2935
+ }
2936
+
2937
+ if (backendLanguage === 'csharp') {
2938
+ return `name: Deploy Azure Functions
2939
+
2940
+ on:
2941
+ push:
2942
+ branches:
2943
+ - main
2944
+ paths:
2945
+ - 'functions/**'
2946
+ - 'shared/**'
2947
+ pull_request:
2948
+ branches:
2949
+ - main
2950
+ paths:
2951
+ - 'functions/**'
2952
+ - 'shared/**'
2953
+ workflow_dispatch:
2954
+
2955
+ jobs:
2956
+ build-and-deploy:
2957
+ runs-on: ubuntu-latest
2958
+ name: Build and Deploy Functions
2959
+
2960
+ steps:
2961
+ ${commonSetup} - name: Setup .NET
2962
+ uses: actions/setup-dotnet@v4
2963
+ with:
2964
+ dotnet-version: '8.0.x'
2965
+
2966
+ - name: Publish Functions
2967
+ run: |
2968
+ dotnet publish ./functions -c Release -o ./functions/publish
2969
+
2970
+ - name: Deploy to Azure Functions
2971
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
2972
+ uses: Azure/functions-action@v1
2973
+ with:
2974
+ app-name: \${{ secrets.AZURE_FUNCTIONAPP_NAME }}
2975
+ package: './functions/publish'
2976
+ publish-profile: \${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }}
2977
+ sku: flexconsumption
2978
+ `;
2979
+ }
2980
+
2981
+ return `name: Deploy Azure Functions
2982
+
2983
+ on:
2984
+ push:
2985
+ branches:
2986
+ - main
2987
+ paths:
2988
+ - 'functions/**'
2989
+ - 'shared/**'
2990
+ pull_request:
2991
+ branches:
2992
+ - main
2993
+ paths:
2994
+ - 'functions/**'
2995
+ - 'shared/**'
2996
+ workflow_dispatch:
2997
+
2998
+ jobs:
2999
+ build-and-deploy:
3000
+ runs-on: ubuntu-latest
3001
+ name: Build and Deploy Functions
3002
+
3003
+ steps:
3004
+ ${commonSetup} - name: Setup Python
3005
+ uses: actions/setup-python@v5
3006
+ with:
3007
+ python-version: '3.11'
3008
+
3009
+ - name: Install Functions dependencies
3010
+ run: |
3011
+ python -m pip install --upgrade pip
3012
+ python -m pip install -r ./functions/requirements.txt --target "./functions/.python_packages/lib/site-packages"
3013
+
3014
+ - name: Deploy to Azure Functions
3015
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
3016
+ uses: Azure/functions-action@v1
3017
+ with:
3018
+ app-name: \${{ secrets.AZURE_FUNCTIONAPP_NAME }}
3019
+ package: './functions'
3020
+ publish-profile: \${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }}
3021
+ sku: flexconsumption
3022
+ `;
3023
+ }
3024
+
3025
+ function getAzureFunctionsPipeline(pm: PackageManager, backendLanguage: BackendLanguage): string {
3026
+ const pmCmd = getCommands(pm);
3027
+ const azPipelinesSetup = getAzurePipelinesSetup(pm);
3028
+ const commonSetup = ` - task: NodeTool@0
3029
+ inputs:
3030
+ versionSpec: '22.x'
3031
+ displayName: 'Install Node.js'
3032
+ ${azPipelinesSetup ? `\n${azPipelinesSetup}\n` : ''}
3033
+ - script: |
3034
+ ${pmCmd.ci}
3035
+ displayName: 'Install workspace dependencies'
3036
+
3037
+ - script: |
3038
+ ${pmCmd.runFilter('shared')} build
3039
+ displayName: 'Build shared package'
3040
+ `;
3041
+
3042
+ if (backendLanguage === 'typescript') {
3043
+ return `trigger:
3044
+ branches:
3045
+ include:
3046
+ - main
3047
+ paths:
3048
+ include:
3049
+ - functions/**
3050
+ - shared/**
3051
+
3052
+ pr:
3053
+ branches:
3054
+ include:
3055
+ - main
3056
+ paths:
3057
+ include:
3058
+ - functions/**
3059
+ - shared/**
3060
+
3061
+ pool:
3062
+ vmImage: 'ubuntu-latest'
3063
+
3064
+ variables:
3065
+ - group: azure-deployment
3066
+
3067
+ steps:
3068
+ ${commonSetup} - script: |
3069
+ ${pmCmd.runFilter('functions')} build
3070
+ displayName: 'Build Functions'
3071
+
3072
+ - script: |
3073
+ SHARED_PKG_NAME=$(node -p "require('./shared/package.json').name")
3074
+ mkdir -p /tmp/fn-deps
3075
+ node -e "const p=JSON.parse(require('fs').readFileSync('./functions/package.json','utf8'));Object.keys(p.dependencies).filter(k=>k.endsWith('/shared')).forEach(k=>delete p.dependencies[k]);require('fs').writeFileSync('/tmp/fn-deps/package.json',JSON.stringify(p,null,2));"
3076
+ cd /tmp/fn-deps && ${pmCmd.installProd} && cd -
3077
+ rm -rf ./functions/node_modules
3078
+ mv /tmp/fn-deps/node_modules ./functions/node_modules
3079
+ SHARED_DEST="./functions/node_modules/$SHARED_PKG_NAME"
3080
+ mkdir -p "$SHARED_DEST"
3081
+ cp -r ./shared/dist "$SHARED_DEST/dist"
3082
+ cp ./shared/package.json "$SHARED_DEST/package.json"
3083
+ displayName: 'Prepare functions for deployment'
3084
+
3085
+ - task: ArchiveFiles@2
3086
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3087
+ inputs:
3088
+ rootFolderOrFile: '$(System.DefaultWorkingDirectory)/functions'
3089
+ includeRootFolder: false
3090
+ archiveType: 'zip'
3091
+ archiveFile: '$(Build.ArtifactStagingDirectory)/functions.zip'
3092
+ displayName: 'Archive Functions'
3093
+
3094
+ - task: PublishBuildArtifacts@1
3095
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3096
+ inputs:
3097
+ PathtoPublish: '$(Build.ArtifactStagingDirectory)/functions.zip'
3098
+ ArtifactName: 'functions'
3099
+ displayName: 'Publish Functions artifact'
3100
+
3101
+ - task: AzureFunctionApp@2
3102
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3103
+ inputs:
3104
+ azureSubscription: '$(AZURE_SUBSCRIPTION)'
3105
+ appType: 'functionAppLinux'
3106
+ appName: '$(AZURE_FUNCTIONAPP_NAME)'
3107
+ package: '$(Build.ArtifactStagingDirectory)/functions.zip'
3108
+ displayName: 'Deploy to Azure Functions'
3109
+ `;
3110
+ }
3111
+
3112
+ if (backendLanguage === 'csharp') {
3113
+ return `trigger:
3114
+ branches:
3115
+ include:
3116
+ - main
3117
+ paths:
3118
+ include:
3119
+ - functions/**
3120
+ - shared/**
3121
+
3122
+ pr:
3123
+ branches:
3124
+ include:
3125
+ - main
3126
+ paths:
3127
+ include:
3128
+ - functions/**
3129
+ - shared/**
3130
+
3131
+ pool:
3132
+ vmImage: 'ubuntu-latest'
3133
+
3134
+ variables:
3135
+ - group: azure-deployment
3136
+
3137
+ steps:
3138
+ ${commonSetup} - task: UseDotNet@2
3139
+ inputs:
3140
+ version: '8.0.x'
3141
+ displayName: 'Install .NET SDK'
3142
+
3143
+ - script: |
3144
+ dotnet publish ./functions -c Release -o ./functions/publish
3145
+ displayName: 'Publish Functions'
3146
+
3147
+ - task: ArchiveFiles@2
3148
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3149
+ inputs:
3150
+ rootFolderOrFile: '$(System.DefaultWorkingDirectory)/functions/publish'
3151
+ includeRootFolder: false
3152
+ archiveType: 'zip'
3153
+ archiveFile: '$(Build.ArtifactStagingDirectory)/functions.zip'
3154
+ displayName: 'Archive Functions'
3155
+
3156
+ - task: AzureFunctionApp@2
3157
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3158
+ inputs:
3159
+ azureSubscription: '$(AZURE_SUBSCRIPTION)'
3160
+ appType: 'functionAppLinux'
3161
+ appName: '$(AZURE_FUNCTIONAPP_NAME)'
3162
+ package: '$(Build.ArtifactStagingDirectory)/functions.zip'
3163
+ displayName: 'Deploy to Azure Functions'
3164
+ `;
3165
+ }
3166
+
3167
+ return `trigger:
3168
+ branches:
3169
+ include:
3170
+ - main
3171
+ paths:
3172
+ include:
3173
+ - functions/**
3174
+ - shared/**
3175
+
3176
+ pr:
3177
+ branches:
3178
+ include:
3179
+ - main
3180
+ paths:
3181
+ include:
3182
+ - functions/**
3183
+ - shared/**
3184
+
3185
+ pool:
3186
+ vmImage: 'ubuntu-latest'
3187
+
3188
+ variables:
3189
+ - group: azure-deployment
3190
+
3191
+ steps:
3192
+ ${commonSetup} - task: UsePythonVersion@0
3193
+ inputs:
3194
+ versionSpec: '3.11'
3195
+ displayName: 'Install Python'
3196
+
3197
+ - script: |
3198
+ python -m pip install --upgrade pip
3199
+ python -m pip install -r ./functions/requirements.txt --target "./functions/.python_packages/lib/site-packages"
3200
+ displayName: 'Install Functions dependencies'
3201
+
3202
+ - task: ArchiveFiles@2
3203
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3204
+ inputs:
3205
+ rootFolderOrFile: '$(System.DefaultWorkingDirectory)/functions'
3206
+ includeRootFolder: false
3207
+ archiveType: 'zip'
3208
+ archiveFile: '$(Build.ArtifactStagingDirectory)/functions.zip'
3209
+ displayName: 'Archive Functions'
3210
+
3211
+ - task: AzureFunctionApp@2
3212
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3213
+ inputs:
3214
+ azureSubscription: '$(AZURE_SUBSCRIPTION)'
3215
+ appType: 'functionAppLinux'
3216
+ appName: '$(AZURE_FUNCTIONAPP_NAME)'
3217
+ package: '$(Build.ArtifactStagingDirectory)/functions.zip'
3218
+ displayName: 'Deploy to Azure Functions'
3219
+ `;
3220
+ }
3221
+
3222
+ async function createGitHubActionsWorkflows(
3223
+ projectDir: string,
3224
+ azureConfig: AzureConfig,
3225
+ pm: PackageManager,
3226
+ backendLanguage: BackendLanguage
3227
+ ) {
3228
+ console.log('📦 Creating GitHub Actions workflows...\n');
3229
+ const workflowsDir = path.join(projectDir, '.github', 'workflows');
3230
+ fs.mkdirSync(workflowsDir, { recursive: true });
3231
+
3232
+ // deploy-swa.yml
3233
+ const swaWorkflow = `name: Deploy Static Web App
3234
+
3235
+ on:
3236
+ push:
3237
+ branches:
3238
+ - main
3239
+ paths:
3240
+ - 'app/**'
3241
+ - 'components/**'
3242
+ - 'lib/**'
3243
+ - 'shared/**'
3244
+ - 'public/**'
3245
+ - 'package.json'
3246
+ - 'next.config.js'
3247
+ - 'next.config.ts'
3248
+ workflow_dispatch:
3249
+ pull_request:
3250
+ branches:
3251
+ - main
3252
+ paths:
3253
+ - 'app/**'
3254
+ - 'components/**'
3255
+ - 'lib/**'
3256
+ - 'shared/**'
3257
+ - 'public/**'
3258
+ - 'package.json'
3259
+ - 'next.config.js'
3260
+ - 'next.config.ts'
3261
+
3262
+ jobs:
3263
+ build-and-deploy:
3264
+ runs-on: ubuntu-latest
3265
+ name: Build and Deploy Static Web App
3266
+
3267
+ steps:
3268
+ - uses: actions/checkout@v4
3269
+ with:
3270
+ submodules: true
3271
+
3272
+ - name: Deploy to Azure Static Web Apps
3273
+ if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main'
3274
+ uses: Azure/static-web-apps-deploy@v1
3275
+ with:
3276
+ azure_static_web_apps_api_token: \${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
3277
+ repo_token: \${{ secrets.GITHUB_TOKEN }}
3278
+ action: 'upload'
3279
+ app_location: '/'
3280
+ api_location: ''
3281
+ output_location: ''
3282
+ env:
3283
+ NEXT_TURBOPACK_EXPERIMENTAL_USE_SYSTEM_TLS_CERTS: '1'
3284
+ `;
3285
+ fs.writeFileSync(path.join(workflowsDir, 'deploy-swa.yml'), swaWorkflow);
3286
+
3287
+ // deploy-functions.yml
3288
+ const functionsWorkflow = getGitHubFunctionsWorkflow(pm, backendLanguage);
3289
+ fs.writeFileSync(path.join(workflowsDir, 'deploy-functions.yml'), functionsWorkflow);
3290
+
3291
+ console.log('✅ GitHub Actions workflows created\n');
3292
+ }
3293
+
3294
+ async function createAzurePipelines(projectDir: string, pm: PackageManager, backendLanguage: BackendLanguage) {
3295
+ console.log('📦 Creating Azure Pipelines...\n');
3296
+
3297
+ const pmCmd = getCommands(pm);
3298
+ const azPipelinesSetup = getAzurePipelinesSetup(pm);
3299
+ const pipelinesDir = path.join(projectDir, 'pipelines');
3300
+ fs.mkdirSync(pipelinesDir, { recursive: true });
3301
+
3302
+ // swa.yml
3303
+ const swaPipeline = `trigger:
3304
+ branches:
3305
+ include:
3306
+ - main
3307
+ paths:
3308
+ include:
3309
+ - app/**
3310
+ - components/**
3311
+ - lib/**
3312
+ - shared/**
3313
+ - public/**
3314
+ - package.json
3315
+ - next.config.js
3316
+
3317
+ pr:
3318
+ branches:
3319
+ include:
3320
+ - main
3321
+ paths:
3322
+ include:
3323
+ - app/**
3324
+ - components/**
3325
+ - lib/**
3326
+ - shared/**
3327
+ - public/**
3328
+ - package.json
3329
+ - next.config.js
3330
+
3331
+ pool:
3332
+ vmImage: 'ubuntu-latest'
3333
+
3334
+ variables:
3335
+ - group: azure-deployment
3336
+
3337
+ steps:
3338
+ - task: NodeTool@0
3339
+ inputs:
3340
+ versionSpec: '22.x'
3341
+ displayName: 'Install Node.js'
3342
+ ${azPipelinesSetup ? `\n${azPipelinesSetup}\n` : ''}
3343
+ - script: |
3344
+ ${pmCmd.ci}
3345
+ displayName: 'Install dependencies'
3346
+
3347
+ - script: |
3348
+ ${pmCmd.run} build
3349
+ env:
3350
+ NODE_ENV: production
3351
+ displayName: 'Build Next.js app'
3352
+
3353
+ - task: AzureStaticWebApp@0
3354
+ condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
3355
+ inputs:
3356
+ app_location: '.'
3357
+ output_location: '.next/standalone'
3358
+ skip_app_build: true
3359
+ azure_static_web_apps_api_token: $(AZURE_STATIC_WEB_APPS_API_TOKEN)
3360
+ displayName: 'Deploy to Azure Static Web Apps'
3361
+ `;
3362
+ fs.writeFileSync(path.join(pipelinesDir, 'swa.yml'), swaPipeline);
3363
+
3364
+ // functions.yml
3365
+ const functionsPipeline = getAzureFunctionsPipeline(pm, backendLanguage);
3366
+ fs.writeFileSync(path.join(pipelinesDir, 'functions.yml'), functionsPipeline);
3367
+
3368
+ console.log('✅ Azure Pipelines created\n');
3369
+ }
3370
+
3371
+