@akanjs/devkit 3.3.0-rc.9 → 3.3.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (362) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +7 -1
  3. package/README.md +7 -1
  4. package/akanApp/akanApp.host.test.ts +3 -1
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +307 -18
  13. package/akanConfig/akanConfig.ts +104 -210
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +233 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/types.ts +4 -0
  23. package/app/appBin.test.ts +63 -0
  24. package/app/appBin.ts +50 -0
  25. package/app/applicationBuildReporter.test.ts +51 -1
  26. package/app/applicationBuildReporter.ts +6 -1
  27. package/app/applicationBuildRunner.test.ts +438 -7
  28. package/app/applicationBuildRunner.ts +237 -37
  29. package/app/clientServerBoundary.test.ts +115 -0
  30. package/app/clientServerBoundary.ts +89 -0
  31. package/app/dictionarySizes.test.ts +40 -0
  32. package/app/dictionarySizes.ts +95 -0
  33. package/app/routeFilesReport.test.ts +59 -0
  34. package/app/routeFilesReport.ts +46 -0
  35. package/app/routeJsBudget.ts +18 -4
  36. package/artifact/implicitRootLayout.test.ts +19 -0
  37. package/artifact/implicitRootLayout.ts +16 -2
  38. package/artifact/implicitRootLayoutRender.test.tsx +7 -2
  39. package/artifact/storeBootstrap.test.ts +28 -0
  40. package/artifact/storeBootstrap.ts +64 -8
  41. package/biome.base.json +7 -5
  42. package/codeAgent/index.ts +1 -34
  43. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  44. package/codeAgent/skills/akan-debug/SKILL.md +11 -5
  45. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  46. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  47. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  48. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  49. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  50. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  51. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  52. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  56. package/commandDecorators/command.ts +28 -12
  57. package/commandDecorators/commandBuilder.ts +8 -1
  58. package/commandDecorators/commandDecorators.test.ts +70 -3
  59. package/commandDecorators/helpFormatter.ts +14 -12
  60. package/context/akanContext.ts +2 -0
  61. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  62. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  63. package/docs/apiReference.test.ts +25 -0
  64. package/docs/apiReference.ts +38 -5
  65. package/docs/declarationReader.ts +30 -0
  66. package/docs/errorCodeReference.test.ts +26 -0
  67. package/docs/errorCodeScan.ts +23 -6
  68. package/executors/appExecutor.ts +26 -12
  69. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  70. package/executors/clientRuntimeKeys.fixture.json +393 -0
  71. package/executors/clientRuntimeKeys.test.ts +1692 -0
  72. package/executors/executor.ts +14 -6
  73. package/executors/executors.test.ts +155 -1
  74. package/executors/pkgExecutor.ts +2 -1
  75. package/executors/sysExecutor.ts +112 -8
  76. package/executors/workspaceExecutor.ts +7 -4
  77. package/frontendBuild/allRoutesBuilder.ts +99 -7
  78. package/frontendBuild/autoImportSync.ts +3 -2
  79. package/frontendBuild/buildRouteClient.test.ts +684 -6
  80. package/frontendBuild/clientBuildTypes.ts +26 -0
  81. package/frontendBuild/clientEntriesBundler.test.ts +79 -0
  82. package/frontendBuild/clientEntriesBundler.ts +70 -1
  83. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  84. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  85. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  86. package/frontendBuild/clientEntryGroups.ts +61 -0
  87. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  88. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  89. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  90. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  91. package/frontendBuild/csrDevPatcher.ts +37 -11
  92. package/frontendBuild/csrDevTypes.ts +9 -0
  93. package/frontendBuild/cssCandidateCache.test.ts +12 -0
  94. package/frontendBuild/cssCandidateCache.ts +5 -3
  95. package/frontendBuild/cssCompiler.test.ts +14 -0
  96. package/frontendBuild/devBarrelImports.test.ts +127 -0
  97. package/frontendBuild/devBarrelImports.ts +81 -21
  98. package/frontendBuild/devChangePlanner.ts +0 -1
  99. package/frontendBuild/devRegistryBundler.ts +4 -2
  100. package/frontendBuild/devRouteRuntime.test.ts +493 -0
  101. package/frontendBuild/devRouteRuntime.ts +167 -0
  102. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  103. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  104. package/frontendBuild/dictionaryConstants.ts +136 -0
  105. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  106. package/frontendBuild/dictionaryPackState.ts +131 -0
  107. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  108. package/frontendBuild/dictionaryPacking.ts +160 -0
  109. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  110. package/frontendBuild/dictionaryRoutes.ts +227 -0
  111. package/frontendBuild/frontendBuild.test.ts +5 -3
  112. package/frontendBuild/hmrWatcher.test.ts +3 -1
  113. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  114. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  115. package/frontendBuild/plainStylesheet.test.ts +2 -2
  116. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  117. package/frontendBuild/precompressArtifacts.ts +34 -8
  118. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  119. package/frontendBuild/renderedEntries.ts +144 -0
  120. package/frontendBuild/routeClientBuilder.ts +407 -43
  121. package/frontendBuild/routeHandoffs.test.ts +155 -0
  122. package/frontendBuild/routeHandoffs.ts +117 -0
  123. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  124. package/frontendBuild/routeModulePreloads.ts +20 -11
  125. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  126. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  127. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  128. package/frontendBuild/routeRuntimePays.ts +117 -0
  129. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  130. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  131. package/frontendBuild/ssrDevBundler.ts +66 -11
  132. package/frontendBuild/vendorFileImports.test.ts +254 -0
  133. package/frontendBuild/vendorFileImports.ts +163 -0
  134. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  135. package/frontendBuild/vendorNarrowing.ts +38 -2
  136. package/frontendBuild/vendorSpecifiers.ts +2 -0
  137. package/frontendBuild/workerChunks.ts +61 -0
  138. package/guideline/agentAssets.ts +1 -1
  139. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  140. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  141. package/incrementalBuilder/builderWatch.ts +11 -1
  142. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  143. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  144. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  145. package/incrementalBuilder/pendingMetadata.ts +19 -0
  146. package/integration/devResourceProbe.ts +14 -0
  147. package/integration/devStability.integration.test.ts +46 -21
  148. package/integration/renderAdmissionSoak.test.ts +39 -34
  149. package/integration/renderAdmissionSoak.ts +6 -0
  150. package/integration/ssrMemoryProbe.ts +5 -0
  151. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  152. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  153. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  154. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  155. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  156. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  157. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  158. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  159. package/lint/biomeBase.test.ts +50 -3
  160. package/lint/biomeBase.ts +1 -1
  161. package/lint/biomeCheck.test.ts +173 -0
  162. package/lint/biomeCheck.ts +132 -0
  163. package/lint/linter.test.ts +16 -11
  164. package/lint/no-arbitrary-color.grit +5 -0
  165. package/lint/no-conditional-st-hook.grit +5 -1
  166. package/lint/no-daisyui-legacy-class.grit +8 -0
  167. package/lint/no-document-cookie.grit +3 -0
  168. package/lint/no-inline-color.grit +10 -2
  169. package/lint/no-oversized-list-limit.grit +2 -0
  170. package/lint/no-raw-palette-class.grit +7 -0
  171. package/lint/no-unpublished-form-setter.grit +2 -0
  172. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  173. package/lint/no-web-storage.grit +3 -0
  174. package/lint/withheldEnvFile.ts +17 -0
  175. package/mobile/desktopBin.ts +2 -2
  176. package/mobile/desktopServerStage.test.ts +18 -3
  177. package/mobile/desktopServerStage.ts +7 -2
  178. package/mobile/nativeApp.test.ts +13 -5
  179. package/mobile/nativeApp.ts +9 -4
  180. package/mobile/nativeConfig.test.ts +27 -7
  181. package/mobile/nativeConfig.ts +19 -9
  182. package/mobile/nativePublicEnv.ts +1 -1
  183. package/mobile/serverBundleSecrets.ts +43 -0
  184. package/package.json +11 -12
  185. package/packageExports.test.ts +3 -2
  186. package/preview/PreviewView.ts +43 -6
  187. package/preview/previewView.test.ts +31 -0
  188. package/quality/dictionaryKeys.test.ts +356 -0
  189. package/quality/dictionaryKeys.ts +488 -0
  190. package/quality/maintainabilityContract.test.ts +4 -1
  191. package/quality/objectImportReport.test.ts +36 -0
  192. package/quality/objectImportReport.ts +105 -0
  193. package/quality/qualityScanner.ts +1 -1
  194. package/quality/routeRuntimeReport.test.ts +91 -0
  195. package/quality/routeRuntimeReport.ts +121 -0
  196. package/quality/runtimeConstantFacts.ts +71 -0
  197. package/quality/runtimeConstantGraph.ts +123 -0
  198. package/quality/runtimeConstantReads.ts +116 -0
  199. package/quality/runtimeImports.test.ts +190 -0
  200. package/quality/runtimeImports.ts +233 -0
  201. package/quality/runtimeKeyNames.ts +46 -0
  202. package/quality/runtimeLexicalScope.ts +132 -0
  203. package/quality/runtimeMarkerReach.test.ts +86 -0
  204. package/quality/runtimeMarkerReach.ts +255 -0
  205. package/quality/runtimeModuleFacts.ts +290 -0
  206. package/quality/runtimeNameTable.test.ts +172 -0
  207. package/quality/runtimeNameTable.ts +477 -0
  208. package/quality/runtimeScopeReport.test.ts +123 -0
  209. package/quality/runtimeScopeReport.ts +167 -0
  210. package/quality/runtimeSliceKey.ts +269 -0
  211. package/quality/runtimeSyntax.ts +133 -0
  212. package/quality/runtimeTable.fixture.ts +189 -0
  213. package/quality/runtimeUse.test.ts +737 -0
  214. package/quality/runtimeUse.ts +696 -0
  215. package/quality/runtimeUseReadable.test.ts +393 -0
  216. package/quality/ssrScanner.test.ts +13 -0
  217. package/quality/ssrScanner.ts +1 -1
  218. package/quality/translatorBindings.ts +187 -0
  219. package/test/fakeTerminal.ts +45 -0
  220. package/test/secretEnvFixture.ts +147 -0
  221. package/test/testHelpers.ts +11 -0
  222. package/transforms/barrelAnalyzer.ts +24 -2
  223. package/transforms/barrelImportsPlugin.ts +121 -32
  224. package/transforms/exportReach.test.ts +162 -0
  225. package/transforms/exportReach.ts +308 -0
  226. package/transforms/frameworkObjects.fixture.tsx +58 -0
  227. package/transforms/frameworkObjects.test.ts +57 -0
  228. package/transforms/modelReference.test.ts +197 -0
  229. package/transforms/modelReference.ts +39 -0
  230. package/transforms/moduleParts.test.ts +225 -0
  231. package/transforms/moduleParts.ts +418 -0
  232. package/transforms/objectImportEdits.ts +150 -0
  233. package/transforms/objectMemberImports.test.ts +631 -0
  234. package/transforms/objectMemberImports.ts +571 -0
  235. package/transforms/objectMemberLookup.ts +150 -0
  236. package/transforms/objectModule.test.ts +307 -0
  237. package/transforms/objectModule.ts +482 -0
  238. package/transforms/objectModuleAnalyzer.ts +104 -0
  239. package/transforms/partImports.test.ts +76 -0
  240. package/transforms/partImports.ts +110 -0
  241. package/transforms/partModules.test.ts +189 -0
  242. package/transforms/partModules.ts +90 -0
  243. package/transforms/partPurity.ts +124 -0
  244. package/transforms/reactIconImports.test.ts +231 -0
  245. package/transforms/reactIconImports.ts +325 -0
  246. package/transforms/routeConstants.ts +122 -0
  247. package/transforms/routeRuntime.test.ts +834 -0
  248. package/transforms/routeRuntime.ts +703 -0
  249. package/transforms/routeRuntimeEdits.ts +92 -0
  250. package/transforms/routeRuntimeGraph.ts +66 -0
  251. package/transforms/routeRuntimePlan.ts +244 -0
  252. package/transforms/secretEnvDeclaration.test.ts +211 -0
  253. package/transforms/secretEnvDeclaration.ts +219 -0
  254. package/transforms/secretEnvFile.test.ts +117 -0
  255. package/transforms/secretEnvFile.ts +132 -0
  256. package/transforms/secretEnvName.test.ts +54 -0
  257. package/transforms/secretEnvName.ts +29 -0
  258. package/transforms/secretEnvSource.test.ts +152 -0
  259. package/transforms/secretEnvSource.ts +197 -0
  260. package/transforms/serverEnvEvaluationError.ts +11 -0
  261. package/transforms/serverEnvPlugin.test.ts +157 -1
  262. package/transforms/serverEnvPlugin.ts +123 -19
  263. package/transforms/serverEnvProfile.test.ts +129 -2
  264. package/transforms/serverEnvProfile.ts +133 -43
  265. package/transforms/serverEnvSecrets.test.ts +268 -0
  266. package/transforms/signalDescriptors.test.ts +280 -0
  267. package/transforms/signalDescriptors.ts +230 -0
  268. package/transforms/thisFreeExports.ts +87 -0
  269. package/transforms/transforms.test.ts +184 -2
  270. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  271. package/tunnel/createTunnel.ts +5 -1
  272. package/tunnel/ssh2Module.test.ts +37 -0
  273. package/tunnel/ssh2Module.ts +28 -0
  274. package/tunnel/sshTunnel.ts +4 -2
  275. package/typecheck/projectTypecheck.test.ts +32 -1
  276. package/typecheck/projectTypecheck.ts +3 -3
  277. package/typecheck/typeChecker.test.ts +50 -0
  278. package/typecheck/typeChecker.ts +14 -8
  279. package/typecheck/withheldDiagnostics.ts +44 -0
  280. package/util/devInstallCommand.ts +7 -0
  281. package/util/jsonFormatter.test.ts +13 -9
  282. package/workflow/executor.ts +6 -2
  283. package/workflow/index.ts +1 -0
  284. package/workflow/plan.ts +36 -7
  285. package/workflow/types.ts +1 -1
  286. package/workflow/uiTarget.ts +50 -0
  287. package/workspace/envSeed.test.ts +30 -1
  288. package/workspace/envSeed.ts +30 -1
  289. package/workspace/mainCheckout.test.ts +55 -0
  290. package/workspace/mainCheckout.ts +38 -0
  291. package/workspace/scanInfo.test.ts +39 -0
  292. package/workspace/scanInfo.ts +55 -6
  293. package/workspace/slicePlanner.ts +2 -1
  294. package/workspace/workspaceLayout.test.ts +22 -1
  295. package/workspace/workspaceLayout.ts +3 -3
  296. package/CHANGELOG.md +0 -2904
  297. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  298. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  299. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  300. package/codeAgent/agent/CodeAgent.ts +0 -626
  301. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  302. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  303. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  304. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  305. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  306. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  307. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  308. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  309. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  310. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  311. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  312. package/codeAgent/agent/CodeMailbox.ts +0 -148
  313. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  314. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  315. package/codeAgent/agent/SubagentPool.ts +0 -219
  316. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  317. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  318. package/codeAgent/agent/akanCodeModel.ts +0 -47
  319. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  320. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  321. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  322. package/codeAgent/agent/codeAgent.test.ts +0 -337
  323. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  324. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  325. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  326. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  327. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  328. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  329. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  330. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  331. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  332. package/codeAgent/agent/consoleToStderr.ts +0 -8
  333. package/codeAgent/agent/jsonLines.ts +0 -29
  334. package/codeAgent/agent/stringArg.ts +0 -5
  335. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  336. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  337. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  338. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  339. package/codeAgent/tools/AkanCli.ts +0 -51
  340. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  341. package/codeAgent/tools/AkanEditScope.ts +0 -53
  342. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  343. package/codeAgent/tools/AkanToolPack.ts +0 -86
  344. package/codeAgent/tools/AkanVerifier.ts +0 -30
  345. package/codeAgent/tools/AskToolPack.ts +0 -99
  346. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  347. package/codeAgent/tools/MailToolPack.ts +0 -76
  348. package/codeAgent/tools/McpClient.ts +0 -209
  349. package/codeAgent/tools/McpOAuth.ts +0 -233
  350. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  351. package/codeAgent/tools/McpServerConfig.ts +0 -131
  352. package/codeAgent/tools/McpSignIn.ts +0 -158
  353. package/codeAgent/tools/McpTokenStore.ts +0 -128
  354. package/codeAgent/tools/McpToolPack.ts +0 -206
  355. package/codeAgent/tools/SessionToolPack.ts +0 -91
  356. package/codeAgent/tools/WebToolPack.ts +0 -315
  357. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  358. package/codeAgent/tools/askToolPack.test.ts +0 -116
  359. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  360. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  361. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  362. package/piDependencyPins.test.ts +0 -45
@@ -0,0 +1,219 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { Logger } from "akanjs/common";
4
+ import type { SecretEnvEntry, SecretEnvKind } from "akanjs/server/lifecycle/secretEnv";
5
+ import { SecretEnvName } from "./secretEnvName";
6
+ import { type SecretEnvMode, SecretEnvSource } from "./secretEnvSource";
7
+ import { ServerEnvEvaluationError } from "./serverEnvEvaluationError";
8
+ import { type EnvEvaluated, ServerEnvProfile, type ServerEnvSource } from "./serverEnvProfile";
9
+
10
+ export interface SecretEnvVariable extends SecretEnvEntry {
11
+ path: string;
12
+ value: string;
13
+ }
14
+
15
+ interface Variables {
16
+ readonly [name: string]: string;
17
+ }
18
+
19
+ interface Loaded extends EnvEvaluated {
20
+ variables: Variables;
21
+ }
22
+
23
+ interface Computed {
24
+ at: string;
25
+ segments: string[];
26
+ value: string;
27
+ }
28
+
29
+ interface MarkedVariable extends SecretEnvVariable {
30
+ literal: unknown;
31
+ underSecret: boolean;
32
+ }
33
+
34
+ interface Found {
35
+ variables: MarkedVariable[];
36
+ computed: Computed[];
37
+ plain: { at: string; value: string }[];
38
+ }
39
+
40
+ export interface SecretEnvMoved {
41
+ path: string;
42
+ name: string;
43
+ /** One secret string the variable holds: the value, an item of its array, or the password of a URL in it. */
44
+ value: string;
45
+ /** Keys of the env that hold the same string and stay in the build as written. */
46
+ twins: string[];
47
+ }
48
+
49
+ export interface SecretEnvDeclared {
50
+ variables: SecretEnvVariable[];
51
+ /** Keys whose secret value the env computes or imports, and does not read from the process env itself. */
52
+ unmoved: string[];
53
+ moved: SecretEnvMoved[];
54
+ }
55
+
56
+ //* Evaluated with each secret literal marked as a build replaces it, so the list is the reads the built server holds.
57
+ export class SecretEnvDeclaration {
58
+ //? Lowercase letters and digits, which `encodeURIComponent` and a URL's parts keep as they are.
59
+ static readonly #unset = "akanownenvunset7q3x9";
60
+ static readonly #set = "akanownenvset5k8w2";
61
+
62
+ static async of(envDir: string, environment: string): Promise<SecretEnvDeclared> {
63
+ const file = path.join(envDir, "env.server.ts");
64
+ if (!existsSync(file))
65
+ throw new Error(`${file} is missing: \`akan sync\` writes the app's env files where it has none.`);
66
+ const loaded = await SecretEnvDeclaration.#loaded(file, envDir, environment);
67
+ const found: Found = { variables: [], computed: [], plain: [] };
68
+ SecretEnvDeclaration.#collect(loaded.value, "", [], false, found);
69
+ const variables = new Map<string, MarkedVariable>();
70
+ for (const variable of found.variables) {
71
+ const taken = variables.get(variable.name);
72
+ if (taken && taken.path !== variable.path)
73
+ throw new Error(
74
+ `${file} holds \`${taken.path}\` and \`${variable.path}\`, secrets a build would both read from the environment variable ${variable.name}. Rename one of the keys.`,
75
+ );
76
+ variables.set(variable.name, variable);
77
+ }
78
+ const computed = await SecretEnvDeclaration.#notRead(found.computed, file, envDir, environment, loaded);
79
+ return {
80
+ variables: [...variables.values()].map(({ name, kind, path: at, value, ahead }) => ({
81
+ name,
82
+ kind,
83
+ path: at,
84
+ value,
85
+ ...(ahead ? { ahead } : {}),
86
+ })),
87
+ unmoved: [...new Set(computed.map(({ at }) => at))],
88
+ moved: [...variables.values()].flatMap(({ name, path: at, literal, underSecret }) =>
89
+ ServerEnvProfile.movedTexts(literal, underSecret).map((value) => ({
90
+ path: at,
91
+ name,
92
+ value,
93
+ twins: [
94
+ ...new Set(
95
+ found.plain
96
+ .filter((plain) => plain.value === value || (value.length >= 8 && plain.value.includes(value)))
97
+ .map((plain) => plain.at),
98
+ ),
99
+ ],
100
+ })),
101
+ ),
102
+ };
103
+ }
104
+
105
+ static async #evaluate(file: string, envDir: string, environment: string, variables: Variables) {
106
+ return await ServerEnvProfile.evaluateReads(
107
+ file,
108
+ path.dirname(envDir),
109
+ (envFile) => SecretEnvDeclaration.source(envFile, "mark"),
110
+ { environment, loads: ServerEnvProfile.envModulePattern, variables },
111
+ );
112
+ }
113
+
114
+ //* With no variable of the shell first, so the list is the same from any shell and a value is what the bundle
115
+ //* carries with none set. An env file that cannot load so (`process.env.HOSTS!.split(",")`) loads with the shell's.
116
+ static async #loaded(file: string, envDir: string, environment: string): Promise<Loaded> {
117
+ try {
118
+ return { ...(await SecretEnvDeclaration.#evaluate(file, envDir, environment, {})), variables: {} };
119
+ } catch (error) {
120
+ if (!(error instanceof ServerEnvEvaluationError) || error.reason === "timedOut") throw error;
121
+ }
122
+ const variables = Object.fromEntries(
123
+ Object.entries(process.env).flatMap(([name, value]) => (value === undefined ? [] : [[name, value]])),
124
+ );
125
+ return { ...(await SecretEnvDeclaration.#evaluate(file, envDir, environment, variables)), variables };
126
+ }
127
+
128
+ //* Leaves out what the env file reads from the process env itself, which the bundle holds as a read: a value a
129
+ //* variable of the shell gave, and one that changes with a variable the file asked for.
130
+ static async #notRead(computed: Computed[], file: string, envDir: string, environment: string, loaded: Loaded) {
131
+ const given = Object.values(loaded.variables).filter((value) => value !== "");
132
+ const kept = computed.filter(
133
+ ({ value }) => !given.some((own) => own === value || (own.length >= 8 && value.includes(own))),
134
+ );
135
+ if (!kept.length) return kept;
136
+ const names = loaded.reads.filter((name) => SecretEnvName.refusal(name) === null);
137
+ const probe = async (probed: string[]) =>
138
+ await SecretEnvDeclaration.#evaluate(file, envDir, environment, {
139
+ ...loaded.variables,
140
+ ...Object.fromEntries(
141
+ probed.map((name) => [
142
+ name,
143
+ Object.hasOwn(loaded.variables, name)
144
+ ? `${loaded.variables[name]}${SecretEnvDeclaration.#set}`
145
+ : SecretEnvDeclaration.#unset,
146
+ ]),
147
+ ),
148
+ }).then(
149
+ ({ value }) => [value],
150
+ (error: unknown) => {
151
+ if (error instanceof ServerEnvEvaluationError) return [];
152
+ throw error;
153
+ },
154
+ );
155
+ //? All names at once, and one at a time when that cannot load: `new URL(process.env.BASE ?? "…")` throws on a probe.
156
+ const all = names.length ? await probe(names) : [];
157
+ const probes = all.length ? all : (await Promise.all(names.slice(0, 32).map((name) => probe([name])))).flat();
158
+ return kept.filter(
159
+ ({ segments, value }) =>
160
+ !probes.some((probed) =>
161
+ SecretEnvDeclaration.#followsRead(
162
+ value,
163
+ segments.reduce<unknown>(
164
+ (node, key) => (node as { [key: string]: unknown } | null | undefined)?.[key],
165
+ probed,
166
+ ),
167
+ ),
168
+ ),
169
+ );
170
+ }
171
+
172
+ //* `"Bearer " + process.env.TOKEN` reads "Bearer undefined" with the variable unset and holds the probe with it set.
173
+ static #followsRead(value: string, probed: unknown) {
174
+ if (typeof probed !== "string") return false;
175
+ const lower = probed.toLowerCase();
176
+ if (!lower.includes(SecretEnvDeclaration.#set) && !lower.includes(SecretEnvDeclaration.#unset)) return false;
177
+ const given = probed.replace(new RegExp(SecretEnvDeclaration.#set, "gi"), "");
178
+ const unset = new RegExp(SecretEnvDeclaration.#unset, "gi");
179
+ return ["undefined", "", "null"].some((gone) => given.replace(unset, gone) === value);
180
+ }
181
+
182
+ static async source(file: string, mode: SecretEnvMode): Promise<ServerEnvSource> {
183
+ const contents = await Bun.file(file).text();
184
+ const name = path.basename(file, ".ts").slice("env.server.".length);
185
+ if (name === "type" || name === "example") return { loader: "ts", contents };
186
+ return { loader: "ts", contents: SecretEnvSource.rewrite(file, contents, mode) };
187
+ }
188
+
189
+ static #collect(value: unknown, at: string, segments: string[], underSecret: boolean, found: Found): void {
190
+ if (typeof value === "string") {
191
+ found.plain.push({ at, value });
192
+ if (ServerEnvProfile.isSecret(value, underSecret)) found.computed.push({ at, segments, value });
193
+ return;
194
+ }
195
+ if (!value || typeof value !== "object") return;
196
+ if (Array.isArray(value)) {
197
+ for (const [index, item] of value.entries())
198
+ SecretEnvDeclaration.#collect(item, at, [...segments, String(index)], underSecret, found);
199
+ return;
200
+ }
201
+ const mark = (value as { [key: string]: unknown })[SecretEnvSource.markKey];
202
+ if (Array.isArray(mark)) {
203
+ const [name, kind, literal, ahead] = mark as [string, SecretEnvKind, unknown, string[]?];
204
+ //? A string a build moved is a secret wherever it sits: a credential URL is one under a plain key too.
205
+ const held = underSecret || typeof literal === "string";
206
+ const value = typeof literal === "string" ? literal : JSON.stringify(literal);
207
+ found.variables.push({ name, kind, path: at, value, ...(ahead ? { ahead } : {}), literal, underSecret: held });
208
+ return;
209
+ }
210
+ for (const [key, child] of Object.entries(value))
211
+ SecretEnvDeclaration.#collect(
212
+ child,
213
+ at ? `${at}.${key}` : key,
214
+ [...segments, key],
215
+ underSecret || Logger.isSecretKey(key),
216
+ found,
217
+ );
218
+ }
219
+ }
@@ -0,0 +1,117 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { parseEnvFile } from "../executors";
5
+ import { isKeptToUser, secretEnvSentinels, writeSecretEnvFixture } from "../test/secretEnvFixture";
6
+ import { tempDirs } from "../test/testHelpers";
7
+ import { SecretEnvDeclaration } from "./secretEnvDeclaration";
8
+ import { SecretEnvFile } from "./secretEnvFile";
9
+
10
+ const makeTempRoot = tempDirs("akan-devkit-secret-env-file-");
11
+
12
+ const declare = async () => {
13
+ const root = await makeTempRoot();
14
+ const { envDir } = await writeSecretEnvFixture(root);
15
+ const { variables } = await SecretEnvDeclaration.of(envDir, "main");
16
+ return { root, variables, values: Object.fromEntries(variables.map(({ name, value }) => [name, value])) };
17
+ };
18
+
19
+ describe("SecretEnvFile", () => {
20
+ test("a Kubernetes Secret decodes to the values the env file evaluates to, byte for byte", async () => {
21
+ const { variables, values } = await declare();
22
+ const manifest = Bun.YAML.parse(SecretEnvFile.render("k8s", variables, "app-env")) as {
23
+ apiVersion: string;
24
+ kind: string;
25
+ metadata: { name: string };
26
+ type: string;
27
+ data: { [name: string]: string };
28
+ };
29
+ expect({ ...manifest, data: undefined }).toEqual({
30
+ apiVersion: "v1",
31
+ kind: "Secret",
32
+ metadata: { name: "app-env" },
33
+ type: "Opaque",
34
+ data: undefined,
35
+ });
36
+ const decoded = Object.fromEntries(
37
+ Object.entries(manifest.data).map(([name, value]) => [name, Buffer.from(value, "base64").toString("utf8")]),
38
+ );
39
+ expect(decoded).toEqual(values);
40
+ expect(decoded.PUSH_NOTI__FIREBASE__PRIVATE_KEY).toBe(secretEnvSentinels.pem);
41
+ expect(JSON.parse(decoded.DISCORD__TOKENS ?? "")).toEqual(secretEnvSentinels.bots);
42
+ });
43
+
44
+ test("a Secret of no variable is still one a deployment can reference, and a name Kubernetes refuses is refused", () => {
45
+ expect(Bun.YAML.parse(SecretEnvFile.render("k8s", [], "app-env"))).toMatchObject({ kind: "Secret", data: {} });
46
+ expect(() => SecretEnvFile.render("k8s", [], "App_Env")).toThrow(
47
+ "--name App_Env is not a name a Kubernetes Secret can take",
48
+ );
49
+ });
50
+
51
+ test("a dotenv file reads back to the same strings, through this package's reader and through Bun's own loader", async () => {
52
+ const { root, variables, values } = await declare();
53
+ const file = path.join(root, "secrets.env");
54
+ await writeFile(file, SecretEnvFile.render("dotenv", variables, "unused"));
55
+ expect(parseEnvFile(file)).toEqual(values);
56
+ const loaded = Bun.spawnSync(
57
+ [
58
+ process.execPath,
59
+ `--env-file=${file}`,
60
+ "-e",
61
+ `console.log(JSON.stringify(Object.fromEntries(${JSON.stringify(Object.keys(values))}.map((name) => [name, process.env[name]]))))`,
62
+ ],
63
+ { cwd: root, env: { PATH: process.env.PATH ?? "", HOME: "/home/fixture", USER: "fixture" } },
64
+ );
65
+ expect(JSON.parse(loaded.stdout.toString())).toEqual(values);
66
+ });
67
+
68
+ test("refuses a value no dotenv line carries unchanged, naming the variable alone", () => {
69
+ const value = 'sentinel-line-one\n"quoted" \\n';
70
+ const failure = (() => {
71
+ try {
72
+ SecretEnvFile.render("dotenv", [{ name: "FIXTURE__KEY", kind: "multiline", path: "fixture.key", value }], "");
73
+ return "";
74
+ } catch (error) {
75
+ return (error as Error).message;
76
+ }
77
+ })();
78
+ expect(failure).toBe(
79
+ "FIXTURE__KEY holds a mix of line breaks, quotes and backslashes no dotenv line carries unchanged. Write it with --format k8s, which keeps every byte.",
80
+ );
81
+ });
82
+
83
+ test("writes a file its user alone can read, and replaces an existing one only when told to", async () => {
84
+ const root = await makeTempRoot();
85
+ const file = path.join(root, "out/secrets.yaml");
86
+ await SecretEnvFile.write(file, "first\n", { workspaceRoot: root });
87
+ expect(await isKeptToUser(file)).toBe(true);
88
+ await expect(SecretEnvFile.write(file, "second\n", { workspaceRoot: root })).rejects.toThrow(
89
+ `--out ${file} exists. Pass --force to replace it.`,
90
+ );
91
+ expect(await readFile(file, "utf8")).toBe("first\n");
92
+ await writeFile(file, "loose\n", { mode: 0o644 });
93
+ await SecretEnvFile.write(file, "second\n", { workspaceRoot: root, force: true });
94
+ expect(await readFile(file, "utf8")).toBe("second\n");
95
+ expect(await isKeptToUser(file)).toBe(true);
96
+ });
97
+
98
+ test("refuses a path under dist/, which an image copies, and one git would track", async () => {
99
+ const root = await makeTempRoot();
100
+ await mkdir(path.join(root, "dist/apps/demo"), { recursive: true });
101
+ const built = path.join(root, "dist/apps/demo/.env");
102
+ await expect(SecretEnvFile.write(built, "x\n", { workspaceRoot: root })).rejects.toThrow(
103
+ `--out ${built} is under dist/, and an image copies the whole of dist/apps/<app>, so the secrets would ship in it. Write the file outside dist/.`,
104
+ );
105
+ expect(await Bun.file(built).exists()).toBe(false);
106
+
107
+ expect(Bun.spawnSync(["git", "init", "-q", root]).exitCode).toBe(0);
108
+ await writeFile(path.join(root, ".gitignore"), "local/\n");
109
+ const tracked = path.join(root, "secrets.env");
110
+ await expect(SecretEnvFile.write(tracked, "x\n", { workspaceRoot: root })).rejects.toThrow(
111
+ `--out ${tracked} is inside a git repository that does not ignore it, so the secrets could be committed.`,
112
+ );
113
+ expect(await Bun.file(tracked).exists()).toBe(false);
114
+ await SecretEnvFile.write(path.join(root, "local/secrets.env"), "x\n", { workspaceRoot: root });
115
+ expect(await readFile(path.join(root, "local/secrets.env"), "utf8")).toBe("x\n");
116
+ });
117
+ });
@@ -0,0 +1,132 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
5
+ import type { SecretEnvDeclared, SecretEnvVariable } from "./secretEnvDeclaration";
6
+
7
+ export type SecretEnvFormat = "k8s" | "dotenv";
8
+
9
+ export interface SecretEnvWrite {
10
+ workspaceRoot: string;
11
+ force?: boolean;
12
+ }
13
+
14
+ export class SecretEnvFile {
15
+ static readonly formats = ["k8s", "dotenv"] as const;
16
+
17
+ static listing({ variables, unmoved }: SecretEnvDeclared): string {
18
+ if (!variables.length && !unmoved.length) return "The server env holds no secret value, so a build reads none.";
19
+ const rows = [
20
+ ["VARIABLE", "KIND", "SHELL", "ENV FILE KEY"],
21
+ ...variables.map(({ name, kind, path: at }) => [name, kind, SecretEnv.read(name) ? "set" : "unset", at]),
22
+ ];
23
+ const widths = [0, 1, 2].map((column) => Math.max(...rows.map((row) => row[column]?.length ?? 0)));
24
+ const table = variables.length
25
+ ? rows.map((row) =>
26
+ row
27
+ .map((cell, column) => cell.padEnd(widths[column] ?? 0))
28
+ .join(" ")
29
+ .trimEnd(),
30
+ )
31
+ : [];
32
+ return [...table, ...(unmoved.length ? [SecretEnvFile.unmovedNote(unmoved)] : [])].join("\n");
33
+ }
34
+
35
+ static unmovedNote(unmoved: readonly string[]): string {
36
+ if (!unmoved.length) return "";
37
+ return `\`akan build\` stops at ${unmoved.join(", ")}: ${unmoved.length === 1 ? "a secret value" : "secret values"} the env file computes or imports. Write the string at the key, or read it there yourself as \`process.env.<NAME>\`.`;
38
+ }
39
+
40
+ static unmovedStop(app: string, environment: string, envFile: string, unmoved: readonly string[]): string {
41
+ const one = unmoved.length === 1;
42
+ return `The server env of ${app} (${environment}) holds ${one ? "a secret value" : `${unmoved.length} secret values`} this build cannot leave out, so it stops here: ${unmoved.join(", ")} (${envFile} and what it imports).\nA build turns a secret written as a string at its key into a read from the server's process env, and ${one ? "this one is" : "these are"} computed or imported. Write the string at the key, or read it there yourself as \`process.env.<NAME>\` and set that variable where the server is deployed.`;
43
+ }
44
+
45
+ static render(format: SecretEnvFormat, variables: readonly SecretEnvVariable[], name: string): string {
46
+ return format === "k8s" ? SecretEnvFile.#k8s(variables, name) : SecretEnvFile.#dotenv(variables);
47
+ }
48
+
49
+ static #k8s(variables: readonly SecretEnvVariable[], name: string) {
50
+ if (name.length > 253 || !/^[a-z0-9](?:[-a-z0-9.]*[a-z0-9])?$/.test(name))
51
+ throw new Error(
52
+ `--name ${name} is not a name a Kubernetes Secret can take: lowercase letters, digits, "-" and ".", starting and ending with a letter or digit.`,
53
+ );
54
+ const data = variables.map(({ name: key, value }) => ` ${key}: ${Buffer.from(value, "utf8").toString("base64")}`);
55
+ return [
56
+ "apiVersion: v1",
57
+ "kind: Secret",
58
+ "metadata:",
59
+ ` name: ${name}`,
60
+ "type: Opaque",
61
+ ...(data.length ? ["data:", ...data] : ["data: {}"]),
62
+ "",
63
+ ].join("\n");
64
+ }
65
+
66
+ static #dotenv(variables: readonly SecretEnvVariable[]) {
67
+ return variables.map(({ name, value }) => `${name}=${SecretEnvFile.#dotenvValue(name, value)}\n`).join("");
68
+ }
69
+
70
+ //? As Bun's .env loader reads a value back (1.4.4): it expands `$NAME` inside every kind of quote and takes `\$` for
71
+ //? a dollar; only double quotes turn `\n` into a line break, and they keep `\"` and `\\` as two characters each.
72
+ static #dotenvValue(name: string, value: string) {
73
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) return value;
74
+ const dollars = value.replaceAll("$", "\\$");
75
+ if (!/[\r\n]/.test(value) && !value.endsWith("\\"))
76
+ for (const quote of ["'", "`"]) if (!value.includes(quote)) return `${quote}${dollars}${quote}`;
77
+ if (!value.includes('"') && !value.includes("\\"))
78
+ return `"${dollars.replaceAll("\r", "\\r").replaceAll("\n", "\\n")}"`;
79
+ throw new Error(
80
+ `${name} holds a mix of line breaks, quotes and backslashes no dotenv line carries unchanged. Write it with --format k8s, which keeps every byte.`,
81
+ );
82
+ }
83
+
84
+ static async write(file: string, contents: string, { workspaceRoot, force = false }: SecretEnvWrite) {
85
+ const target = path.resolve(file);
86
+ const inWorkspace = path.relative(path.resolve(workspaceRoot), target);
87
+ if (inWorkspace.split(path.sep)[0] === "dist")
88
+ throw new Error(
89
+ `--out ${file} is under dist/, and an image copies the whole of dist/apps/<app>, so the secrets would ship in it. Write the file outside dist/.`,
90
+ );
91
+ if (SecretEnvFile.#gitWouldTrack(target))
92
+ throw new Error(
93
+ `--out ${file} is inside a git repository that does not ignore it, so the secrets could be committed. Write it to a git-ignored path or outside the repository.`,
94
+ );
95
+ if (existsSync(target)) {
96
+ if (!force) throw new Error(`--out ${file} exists. Pass --force to replace it.`);
97
+ await rm(target);
98
+ }
99
+ await mkdir(path.dirname(target), { recursive: true });
100
+ await writeFile(target, "", { mode: 0o600, flag: "wx" });
101
+ if (process.platform === "win32" && !SecretEnvFile.#keepToUser(target)) {
102
+ await rm(target, { force: true });
103
+ throw new Error(
104
+ `--out ${file} could not be kept to this user alone, so nothing was written. Write it on a drive that keeps access lists (NTFS).`,
105
+ );
106
+ }
107
+ await writeFile(target, contents);
108
+ }
109
+
110
+ //? Windows keeps no mode bits: a new file takes its folder's access list, which outside the user's profile lets
111
+ //? every local user read it. The SID, not the name, since a local and a domain account can share a name.
112
+ static #keepToUser(target: string) {
113
+ try {
114
+ const sid = /S-1-[0-9-]+/.exec(Bun.spawnSync(["whoami", "/user", "/fo", "csv", "/nh"]).stdout.toString())?.[0];
115
+ if (!sid) return false;
116
+ return Bun.spawnSync(["icacls", target, "/inheritance:r", "/grant:r", `*${sid}:F`]).exitCode === 0;
117
+ } catch {
118
+ return false;
119
+ }
120
+ }
121
+
122
+ static #gitWouldTrack(target: string) {
123
+ let dir = path.dirname(target);
124
+ while (!existsSync(dir) && dir !== path.dirname(dir)) dir = path.dirname(dir);
125
+ try {
126
+ //? Exit 0 is ignored, 1 is not ignored, and 128 is no repository at all.
127
+ return Bun.spawnSync(["git", "check-ignore", "-q", "--", target], { cwd: dir }).exitCode === 1;
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
132
+ }
@@ -0,0 +1,54 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { SecretEnvName } from "./secretEnvName";
3
+
4
+ describe("SecretEnvName", () => {
5
+ test("names a secret after its key path, one upper snake case segment per key", () => {
6
+ const names = Object.fromEntries(
7
+ [
8
+ "security.sso.google.clientSecret",
9
+ "security.sso.kakao.clientID",
10
+ "objectStorage.secretAccessKey",
11
+ "mailer.auth.pass",
12
+ "iapVerify.google.private_key",
13
+ "rootAdminInfo.password",
14
+ "llm.apiKey",
15
+ "storage.s3Key",
16
+ "push-noti.apns.keyId",
17
+ ].map((at) => [at, SecretEnvName.of(at.split("."))]),
18
+ );
19
+ expect(names).toEqual({
20
+ "security.sso.google.clientSecret": "SECURITY__SSO__GOOGLE__CLIENT_SECRET",
21
+ "security.sso.kakao.clientID": "SECURITY__SSO__KAKAO__CLIENT_ID",
22
+ "objectStorage.secretAccessKey": "OBJECT_STORAGE__SECRET_ACCESS_KEY",
23
+ "mailer.auth.pass": "MAILER__AUTH__PASS",
24
+ "iapVerify.google.private_key": "IAP_VERIFY__GOOGLE__PRIVATE_KEY",
25
+ "rootAdminInfo.password": "ROOT_ADMIN_INFO__PASSWORD",
26
+ "llm.apiKey": "LLM__API_KEY",
27
+ "storage.s3Key": "STORAGE__S3_KEY",
28
+ "push-noti.apns.keyId": "PUSH_NOTI__APNS__KEY_ID",
29
+ });
30
+ });
31
+
32
+ test("keeps the names the framework already reads from the process env", () => {
33
+ expect(SecretEnvName.of(["security", "jwtSecret"])).toBe("JWT_SECRET");
34
+ expect(SecretEnvName.of(["database", "postgres", "url"])).toBe("POSTGRES_URL");
35
+ expect(SecretEnvName.of(["database", "postgres", "password"])).toBe("POSTGRES_PASSWORD");
36
+ expect(SecretEnvName.of(["database", "postgres", "insightUrl"])).toBe("POSTGRES_INSIGHT_URL");
37
+ });
38
+
39
+ test("refuses a name the platform sets, one akan or Bun keeps, and one no environment variable can take", () => {
40
+ for (const name of ["PATH", "HOME", "HOSTNAME", "PORT", "USER", "PWD", "TZ", "NODE_ENV"])
41
+ expect(SecretEnvName.refusal(name)).toBe("a variable the platform sets");
42
+ expect(SecretEnvName.refusal(SecretEnvName.of(["akan", "token"]))).toBe(
43
+ "a name akan and Bun keep for their own settings",
44
+ );
45
+ expect(SecretEnvName.refusal(SecretEnvName.of(["bun", "apiKey"]))).toBe(
46
+ "a name akan and Bun keep for their own settings",
47
+ );
48
+ expect(SecretEnvName.refusal(SecretEnvName.of(["2fa", "secret"]))).toBe(
49
+ "which is not a name an environment variable can take",
50
+ );
51
+ expect(SecretEnvName.refusal("JWT_SECRET")).toBeNull();
52
+ expect(SecretEnvName.refusal("SECURITY__SSO__GOOGLE__CLIENT_SECRET")).toBeNull();
53
+ });
54
+ });
@@ -0,0 +1,29 @@
1
+ export class SecretEnvName {
2
+ //? What the database adaptor and the util lib's JWT secret already read from the process env, ahead of the env file.
3
+ static readonly #existing: { readonly [path: string]: string } = {
4
+ "security.jwtSecret": "JWT_SECRET",
5
+ "database.postgres.url": "POSTGRES_URL",
6
+ "database.postgres.password": "POSTGRES_PASSWORD",
7
+ "database.postgres.insightUrl": "POSTGRES_INSIGHT_URL",
8
+ };
9
+ //? Kubernetes sets HOSTNAME to the pod's name, and a shell, Docker or Bun the rest: a secret read there takes theirs.
10
+ static readonly #platform = new Set(["PATH", "HOME", "HOSTNAME", "PORT", "USER", "PWD", "TZ", "NODE_ENV"]);
11
+
12
+ static of(keys: readonly string[]): string {
13
+ return SecretEnvName.#existing[keys.join(".")] ?? keys.map((key) => SecretEnvName.#segment(key)).join("__");
14
+ }
15
+
16
+ static #segment(key: string) {
17
+ return key
18
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
19
+ .replace(/[^A-Za-z0-9]/g, "_")
20
+ .toUpperCase();
21
+ }
22
+
23
+ static refusal(name: string): string | null {
24
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) return "which is not a name an environment variable can take";
25
+ if (SecretEnvName.#platform.has(name)) return "a variable the platform sets";
26
+ if (/^(?:AKAN|BUN)_/.test(name)) return "a name akan and Bun keep for their own settings";
27
+ return null;
28
+ }
29
+ }