swallowkit 1.0.0-beta.4 → 1.0.0-beta.41

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