everything-dev 1.26.1 → 1.28.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 (166) hide show
  1. package/dist/api-contract.cjs.map +1 -1
  2. package/dist/api-contract.mjs.map +1 -1
  3. package/dist/cli/catalog.cjs.map +1 -1
  4. package/dist/cli/catalog.mjs.map +1 -1
  5. package/dist/cli/framework-version.cjs.map +1 -1
  6. package/dist/cli/framework-version.mjs.map +1 -1
  7. package/dist/cli/infra.cjs +1 -1
  8. package/dist/cli/infra.cjs.map +1 -1
  9. package/dist/cli/infra.mjs +1 -1
  10. package/dist/cli/infra.mjs.map +1 -1
  11. package/dist/cli/init.cjs +127 -121
  12. package/dist/cli/init.cjs.map +1 -1
  13. package/dist/cli/init.d.cts +6 -6
  14. package/dist/cli/init.d.cts.map +1 -1
  15. package/dist/cli/init.d.mts +6 -6
  16. package/dist/cli/init.d.mts.map +1 -1
  17. package/dist/cli/init.mjs +125 -121
  18. package/dist/cli/init.mjs.map +1 -1
  19. package/dist/cli/parse.cjs.map +1 -1
  20. package/dist/cli/parse.mjs.map +1 -1
  21. package/dist/cli/prompts.cjs +29 -25
  22. package/dist/cli/prompts.cjs.map +1 -1
  23. package/dist/cli/prompts.mjs +28 -25
  24. package/dist/cli/prompts.mjs.map +1 -1
  25. package/dist/cli/status.cjs.map +1 -1
  26. package/dist/cli/status.mjs.map +1 -1
  27. package/dist/cli/sync.cjs +46 -93
  28. package/dist/cli/sync.cjs.map +1 -1
  29. package/dist/cli/sync.mjs +49 -96
  30. package/dist/cli/sync.mjs.map +1 -1
  31. package/dist/cli/timing.cjs.map +1 -1
  32. package/dist/cli/timing.mjs.map +1 -1
  33. package/dist/cli/upgrade.cjs +41 -20
  34. package/dist/cli/upgrade.cjs.map +1 -1
  35. package/dist/cli/upgrade.mjs +43 -22
  36. package/dist/cli/upgrade.mjs.map +1 -1
  37. package/dist/cli.cjs +187 -12
  38. package/dist/cli.cjs.map +1 -1
  39. package/dist/cli.mjs +187 -12
  40. package/dist/cli.mjs.map +1 -1
  41. package/dist/components/dev-view.cjs.map +1 -1
  42. package/dist/components/dev-view.mjs.map +1 -1
  43. package/dist/components/streaming-view.cjs.map +1 -1
  44. package/dist/components/streaming-view.mjs.map +1 -1
  45. package/dist/config.cjs.map +1 -1
  46. package/dist/config.mjs.map +1 -1
  47. package/dist/contract.cjs +174 -173
  48. package/dist/contract.cjs.map +1 -1
  49. package/dist/contract.d.cts +48 -44
  50. package/dist/contract.d.cts.map +1 -1
  51. package/dist/contract.d.mts +48 -44
  52. package/dist/contract.d.mts.map +1 -1
  53. package/dist/contract.mjs +3 -1
  54. package/dist/contract.mjs.map +1 -1
  55. package/dist/dev-logs.cjs.map +1 -1
  56. package/dist/dev-logs.mjs.map +1 -1
  57. package/dist/dev-session.cjs +0 -1
  58. package/dist/dev-session.mjs +1 -1
  59. package/dist/fastkv.cjs.map +1 -1
  60. package/dist/fastkv.mjs.map +1 -1
  61. package/dist/index.cjs +2 -4
  62. package/dist/index.d.cts +3 -3
  63. package/dist/index.d.mts +3 -3
  64. package/dist/index.mjs +1 -2
  65. package/dist/integrity.cjs.map +1 -1
  66. package/dist/integrity.mjs.map +1 -1
  67. package/dist/internal/manifest-normalizer.cjs.map +1 -1
  68. package/dist/internal/manifest-normalizer.mjs.map +1 -1
  69. package/dist/merge.cjs.map +1 -1
  70. package/dist/merge.mjs.map +1 -1
  71. package/dist/near-cli.cjs +1 -1
  72. package/dist/near-cli.cjs.map +1 -1
  73. package/dist/near-cli.mjs +1 -1
  74. package/dist/near-cli.mjs.map +1 -1
  75. package/dist/orchestrator.cjs +1 -1
  76. package/dist/orchestrator.cjs.map +1 -1
  77. package/dist/orchestrator.mjs +1 -1
  78. package/dist/orchestrator.mjs.map +1 -1
  79. package/dist/plugin.cjs +182 -171
  80. package/dist/plugin.cjs.map +1 -1
  81. package/dist/plugin.d.cts +72 -39
  82. package/dist/plugin.d.cts.map +1 -1
  83. package/dist/plugin.d.mts +71 -39
  84. package/dist/plugin.d.mts.map +1 -1
  85. package/dist/plugin.mjs +170 -160
  86. package/dist/plugin.mjs.map +1 -1
  87. package/dist/sdk.cjs +2 -2
  88. package/dist/sdk.d.cts +1 -1
  89. package/dist/sdk.d.mts +1 -1
  90. package/dist/sdk.mjs +1 -1
  91. package/dist/service-descriptor.d.cts +34 -0
  92. package/dist/service-descriptor.d.cts.map +1 -0
  93. package/dist/service-descriptor.d.mts +36 -0
  94. package/dist/service-descriptor.d.mts.map +1 -0
  95. package/dist/shared.cjs.map +1 -1
  96. package/dist/shared.mjs.map +1 -1
  97. package/dist/types.cjs +184 -184
  98. package/dist/types.cjs.map +1 -1
  99. package/dist/types.d.cts +5 -5
  100. package/dist/types.d.mts +5 -5
  101. package/dist/types.mjs +1 -1
  102. package/dist/types.mjs.map +1 -1
  103. package/dist/ui/types.d.cts +1 -0
  104. package/dist/ui/types.d.cts.map +1 -1
  105. package/dist/ui/types.d.mts +1 -0
  106. package/dist/ui/types.d.mts.map +1 -1
  107. package/dist/utils/banner.cjs.map +1 -1
  108. package/dist/utils/banner.mjs.map +1 -1
  109. package/dist/utils/run.cjs.map +1 -1
  110. package/dist/utils/run.mjs.map +1 -1
  111. package/package.json +3 -3
  112. package/skills/init-upgrade/SKILL.md +22 -16
  113. package/skills/publish-sync/SKILL.md +7 -18
  114. package/dist/utils/path-match.cjs +0 -18
  115. package/dist/utils/path-match.cjs.map +0 -1
  116. package/dist/utils/path-match.mjs +0 -17
  117. package/dist/utils/path-match.mjs.map +0 -1
  118. package/src/api-contract.ts +0 -623
  119. package/src/app.ts +0 -193
  120. package/src/cli/catalog.ts +0 -49
  121. package/src/cli/framework-version.ts +0 -61
  122. package/src/cli/help.ts +0 -13
  123. package/src/cli/infra.ts +0 -190
  124. package/src/cli/init.ts +0 -1202
  125. package/src/cli/parse.ts +0 -147
  126. package/src/cli/prompts.ts +0 -135
  127. package/src/cli/snapshot.ts +0 -46
  128. package/src/cli/status.ts +0 -99
  129. package/src/cli/sync.ts +0 -518
  130. package/src/cli/timing.ts +0 -63
  131. package/src/cli/upgrade.ts +0 -828
  132. package/src/cli.ts +0 -516
  133. package/src/components/dev-view.tsx +0 -352
  134. package/src/components/streaming-view.ts +0 -177
  135. package/src/config.ts +0 -893
  136. package/src/contract.meta.ts +0 -140
  137. package/src/contract.ts +0 -325
  138. package/src/dev-logs.ts +0 -92
  139. package/src/dev-session.ts +0 -283
  140. package/src/fastkv.ts +0 -181
  141. package/src/index.ts +0 -8
  142. package/src/integrity.ts +0 -138
  143. package/src/internal/manifest-normalizer.ts +0 -290
  144. package/src/merge.ts +0 -187
  145. package/src/mf.ts +0 -147
  146. package/src/near-cli.ts +0 -259
  147. package/src/network.ts +0 -3
  148. package/src/orchestrator.ts +0 -493
  149. package/src/plugin.ts +0 -1821
  150. package/src/sdk.ts +0 -14
  151. package/src/service-descriptor.ts +0 -281
  152. package/src/shared.ts +0 -249
  153. package/src/sidebar.ts +0 -140
  154. package/src/types.ts +0 -330
  155. package/src/ui/head.ts +0 -83
  156. package/src/ui/index.ts +0 -5
  157. package/src/ui/metadata.ts +0 -95
  158. package/src/ui/router.ts +0 -88
  159. package/src/ui/runtime.ts +0 -42
  160. package/src/ui/types.ts +0 -64
  161. package/src/utils/banner.ts +0 -21
  162. package/src/utils/linkify.ts +0 -11
  163. package/src/utils/path-match.ts +0 -16
  164. package/src/utils/run.ts +0 -31
  165. package/src/utils/save-config.ts +0 -20
  166. package/src/utils/theme.ts +0 -39
@@ -1 +1 @@
1
- {"version":3,"file":"api-contract.cjs","names":[],"sources":["../src/api-contract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport type { RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nconst REMOTE_FETCH_TIMEOUT_MS = 10_000;\n\nexport interface ApiPluginManifest {\n schemaVersion: 1;\n kind: \"every-plugin/manifest\";\n plugin: {\n name: string;\n version: string;\n };\n runtime: {\n remoteEntry: string;\n };\n contract?: {\n kind: \"orpc\";\n types: {\n path: string;\n exportName: string;\n typeName: string;\n sha256?: string;\n };\n };\n additionalExports?: Array<{\n path: string;\n exports: string[];\n sha256?: string;\n }>;\n}\n\ninterface ContractSource {\n key: string;\n importName: string;\n sourceFilePath: string;\n generatedPath?: string;\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction trimTrailingSlash(input: string): string {\n return input.replace(/\\/$/, \"\");\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return input.replace(/[^A-Za-z0-9_]/g, \"_\").replace(/^[^A-Za-z_]+/, \"_\");\n}\n\nfunction toImportPath(fromFile: string, targetFile: string): string {\n const rel = relative(dirname(fromFile), targetFile).replace(/\\\\/g, \"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nfunction writeFileIfChanged(filePath: string, content: string) {\n try {\n if (readFileSync(filePath, \"utf8\") === content) return false;\n } catch {\n // file does not exist yet\n }\n\n writeFileSync(filePath, content);\n return true;\n}\n\nfunction getApiPluginManifestUrl(apiBaseUrl: string): string {\n return `${trimTrailingSlash(apiBaseUrl)}/plugin.manifest.json`;\n}\n\nasync function fetchWithTimeout(url: string): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), REMOTE_FETCH_TIMEOUT_MS);\n\n try {\n return await fetch(url, { signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Timed out fetching ${url} after ${REMOTE_FETCH_TIMEOUT_MS}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function fetchApiPluginManifest(apiBaseUrl: string): Promise<ApiPluginManifest> {\n const response = await fetchWithTimeout(getApiPluginManifestUrl(apiBaseUrl));\n if (!response.ok) {\n throw new Error(\n `Failed to fetch API plugin manifest: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as ApiPluginManifest;\n if (manifest.schemaVersion !== 1 || manifest.kind !== \"every-plugin/manifest\") {\n throw new Error(\"Unsupported API plugin manifest format\");\n }\n\n return manifest;\n}\n\nfunction localApiContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"api\", \"src\", \"contract.ts\");\n return {\n key: \"api\",\n importName: \"BaseApiContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nfunction localAuthContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"plugins\", \"auth\", \"src\", \"contract.ts\");\n return {\n key: \"auth\",\n importName: \"authContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nasync function remoteContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n name: string;\n baseUrl: string;\n generatedSubdir: string;\n}): Promise<ContractSource> {\n const manifest = await fetchApiPluginManifest(opts.baseUrl);\n if (!manifest.contract) {\n throw new Error(\n `Plugin manifest for ${manifest.plugin.name} does not advertise contract types`,\n );\n }\n\n const contractUrl = `${trimTrailingSlash(opts.baseUrl)}/${manifest.contract.types.path.replace(/^\\.\\//, \"\")}`;\n const contractResponse = await fetchWithTimeout(contractUrl);\n if (!contractResponse.ok) {\n throw new Error(\n `Failed to fetch contract types: ${contractResponse.status} ${contractResponse.statusText}`,\n );\n }\n\n const contractTypes = await contractResponse.text();\n if (manifest.contract.types.sha256 && manifest.contract.types.sha256 !== sha256(contractTypes)) {\n throw new Error(\"Fetched contract types failed checksum verification\");\n }\n\n const generatedPath = join(opts.runtimeDir, opts.generatedSubdir, \"contract.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, contractTypes);\n\n return {\n key: opts.name,\n importName: `${sanitizeIdentifier(opts.name)}Contract`,\n sourceFilePath: generatedPath,\n generatedPath,\n };\n}\n\nasync function fetchAuthExportTypes(opts: {\n baseUrl: string;\n runtimeDir: string;\n manifest: ApiPluginManifest;\n}): Promise<string | null> {\n if (!opts.manifest.additionalExports || opts.manifest.additionalExports.length === 0) {\n return null;\n }\n\n const authExportEntry = opts.manifest.additionalExports.find(\n (entry) => entry.path.includes(\"auth-export\") || entry.path.endsWith(\"auth-export.d.ts\"),\n );\n\n if (!authExportEntry) {\n return null;\n }\n\n const exportUrl = `${trimTrailingSlash(opts.baseUrl)}/${authExportEntry.path.replace(/^\\.\\//, \"\")}`;\n const response = await fetchWithTimeout(exportUrl);\n if (!response.ok) {\n console.warn(`[API Contract] Failed to fetch auth export types: ${response.status}`);\n return null;\n }\n\n const content = await response.text();\n if (authExportEntry.sha256 && authExportEntry.sha256 !== sha256(content)) {\n console.warn(\"[API Contract] Auth export types checksum mismatch\");\n return null;\n }\n\n const generatedPath = join(opts.runtimeDir, \"auth\", \"auth-export.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, content);\n\n return generatedPath;\n}\n\nfunction writeAuthTypesGen(targetPath: string, authExportPath: string) {\n const exportImportPath = toImportPath(targetPath, authExportPath);\n const content = [\n `export type {`,\n ` Auth,`,\n ` AuthOrganizationContext,`,\n ` AuthOrganization,`,\n ` AuthOrganizationSummary,`,\n ` AuthOrganizationMember,`,\n ` AuthApiKey,`,\n ` AuthInvitation,`,\n ` GetActiveMemberInput,`,\n ` GetOrganizationInput,`,\n ` ListMembersInput,`,\n ` ListInvitationsInput,`,\n ` ListApiKeysInput,`,\n ` AuthServices,`,\n ` createAuthInstance,`,\n `} from \"${exportImportPath}\";`,\n `import type { InferOutput, ContractType as AuthContract } from \"${toImportPath(targetPath, join(dirname(authExportPath), \"contract.d.ts\"))}\";`,\n `import type { Auth as BaseAuth } from \"${exportImportPath}\";`,\n \"\",\n 'type RawAuthSession = InferOutput<\"getSession\">;',\n 'type RawAuthRequestContext = InferOutput<\"getContext\">;',\n 'type RawAuthActiveMember = InferOutput<\"getActiveMember\">;',\n \"\",\n 'export type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {',\n \" role?: string | null;\",\n \" isAnonymous?: boolean | null;\",\n \" walletAddress?: string | null;\",\n \" banned?: boolean | null;\",\n \"};\",\n 'export type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {',\n \" activeOrganizationId?: string | null;\",\n \"};\",\n \"export type AuthSession = {\",\n \" user: AuthSessionUser | null;\",\n \" session: AuthSessionData | null;\",\n \"};\",\n \"export type AuthRequestContext = RawAuthRequestContext;\",\n \"export type AuthActiveMember = RawAuthActiveMember;\",\n 'export type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];',\n \"export type AuthContractType = AuthContract;\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nfunction writeFallbackAuthTypesGen(targetPath: string) {\n const content = [\n 'import type { Auth } from \"better-auth\";',\n 'export type { Auth } from \"better-auth\";',\n 'export type AuthSession = Auth[\"$Infer\"][\"Session\"];',\n \"export type AuthSessionData = AuthSession;\",\n 'export type AuthSessionUser = NonNullable<AuthSession[\"user\"]>;',\n \"export interface AuthOrganizationContext {\",\n \" activeOrganizationId: string | null;\",\n \" organization: { id: string; name: string; slug: string; logo?: string | null; metadata?: Record<string, unknown> } | null;\",\n \" member: { id: string; role: string } | null;\",\n \" isPersonal: boolean;\",\n \" hasOrganization: boolean;\",\n \"}\",\n \"export interface AuthRequestContext {\",\n \" user: AuthSessionUser | null;\",\n \" userId: string | null;\",\n \" isAuthenticated: boolean;\",\n ' authMethod: \"session\" | \"apiKey\" | \"anonymous\" | \"none\";',\n \" near: {\",\n \" primaryAccountId: string | null;\",\n \" linkedAccounts: Array<{ accountId: string; network: string; publicKey: string; isPrimary: boolean }>;\",\n \" hasNearAccount: boolean;\",\n \" };\",\n \" organization: AuthOrganizationContext;\",\n \" organizations?: Array<{ id: string; role: string; name?: string; slug?: string }>;\",\n \"}\",\n \"export type AuthActiveMember = { id: string | null; role: string | null; organizationId: string | null };\",\n \"export type AuthOrganization = {\",\n \" id: string;\",\n \" name: string;\",\n \" slug: string;\",\n \" logo?: string | null;\",\n \" metadata?: Record<string, unknown> | null;\",\n \" createdAt: Date;\",\n \"};\",\n 'export type AuthOrganizationSummary = NonNullable<AuthOrganizationContext[\"organization\"]>;',\n 'export type AuthOrganizationMember = NonNullable<AuthOrganizationContext[\"member\"]>;',\n \"export type AuthApiKey = {\",\n \" id: string;\",\n \" name: string | null;\",\n \" prefix: string | null;\",\n \" start: string | null;\",\n \" expiresAt: Date | null;\",\n \" createdAt: Date;\",\n \" updatedAt: Date;\",\n \" metadata: unknown | null;\",\n \" permissions: Record<string, string[]> | null;\",\n \"};\",\n \"export type AuthInvitation = {\",\n \" id: string;\",\n \" organizationId: string;\",\n \" email: string;\",\n \" role: string | null;\",\n \" status: string;\",\n \" expiresAt: Date;\",\n \" inviterId: string;\",\n \"};\",\n \"export type GetActiveMemberInput = { organizationId?: string };\",\n \"export type GetOrganizationInput = { id: string };\",\n \"export type ListMembersInput = { organizationId: string };\",\n \"export type ListInvitationsInput = { organizationId: string };\",\n \"export type ListApiKeysInput = { organizationId?: string };\",\n \"export type createAuthInstance = never;\",\n \"export interface AuthServices {\",\n \" auth: Auth;\",\n \" db: unknown;\",\n \" driver: { close(): Promise<void> };\",\n \" handler: (req: Request) => Promise<Response>;\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nasync function resolveContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n key: string;\n source: RuntimePluginConfig | { url: string; localPath?: string; name: string } | null;\n baseUrl: string;\n generatedSubdir: string;\n localSourceFactory?: (configDir: string) => ContractSource;\n}): Promise<ContractSource> {\n if (opts.key === \"api\") {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"BaseApiContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return localApiContractSource(opts.configDir);\n }\n }\n\n if (opts.key === \"auth\" && opts.localSourceFactory) {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"authContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return opts.localSourceFactory(opts.configDir);\n }\n }\n\n if (\n opts.source &&\n \"localPath\" in opts.source &&\n opts.source.localPath != null &&\n opts.source.localPath !== \"\"\n ) {\n return {\n key: opts.key,\n importName: `${sanitizeIdentifier(opts.key)}Contract`,\n sourceFilePath: join(opts.source.localPath, \"src\", \"contract.ts\"),\n };\n }\n\n return remoteContractSource({\n configDir: opts.configDir,\n runtimeDir: opts.runtimeDir,\n name: opts.key,\n baseUrl: opts.baseUrl,\n generatedSubdir: opts.generatedSubdir,\n });\n}\n\nfunction writeGeneratedFiles(opts: {\n configDir: string;\n sources: ContractSource[];\n pluginKeys: string[];\n authSource: ContractSource | null;\n authExportPath?: string | null;\n}) {\n const baseSource = opts.sources.find((source) => source.key === \"api\");\n const pluginSources = opts.pluginKeys\n .map((key) => opts.sources.find((entry) => entry.key === key))\n .filter((source): source is ContractSource => Boolean(source));\n\n if (!baseSource) {\n throw new Error(\"API contract source is required to generate the aggregate contract\");\n }\n\n // --- Generate ui/src/lib/api-types.gen.ts ---\n const uiContractPath = join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n const uiLines: string[] = [];\n\n for (const source of opts.sources) {\n const importPath = toImportPath(uiContractPath, source.sourceFilePath);\n uiLines.push(`import type { ContractType as ${source.importName} } from \"${importPath}\";`);\n }\n\n uiLines.push(\"\");\n\n const compositeParts: string[] = [];\n if (opts.authSource) {\n compositeParts.push(`auth: ${opts.authSource.importName}`);\n }\n for (const source of pluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key) ? source.key : JSON.stringify(source.key);\n compositeParts.push(`${key}: ${source.importName}`);\n }\n\n if (compositeParts.length === 0) {\n uiLines.push(`export type ApiContract = ${baseSource.importName};`);\n } else {\n uiLines.push(`export type ApiContract = ${baseSource.importName} & {`);\n for (const part of compositeParts) {\n uiLines.push(` ${part};`);\n }\n uiLines.push(\"};\");\n }\n mkdirSync(dirname(uiContractPath), { recursive: true });\n writeFileIfChanged(uiContractPath, `${uiLines.join(\"\\n\")}\\n`);\n\n // --- Generate api/src/lib/plugins-types.gen.ts ---\n // Includes both plugin contracts AND auth as a unified PluginsClient type\n const pluginsClientPath = join(opts.configDir, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n const pluginsClientLines: string[] = [];\n\n for (const source of pluginSources) {\n const importPath = toImportPath(pluginsClientPath, source.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${source.importName} } from \"${importPath}\";`,\n );\n }\n\n if (opts.authSource) {\n const authImportPath = toImportPath(pluginsClientPath, opts.authSource.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${opts.authSource.importName} } from \"${authImportPath}\";`,\n );\n }\n\n pluginsClientLines.push(\n 'import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";',\n );\n pluginsClientLines.push(\n \"type ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\",\n );\n pluginsClientLines.push(\"\");\n\n const allPluginSources = [...pluginSources];\n if (opts.authSource) {\n allPluginSources.push({ ...opts.authSource, key: \"auth\" });\n }\n\n if (allPluginSources.length === 0) {\n pluginsClientLines.push(\"export type PluginsClient = Record<string, never>;\");\n } else {\n pluginsClientLines.push(\"export type PluginsClient = {\");\n for (const source of allPluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key)\n ? source.key\n : JSON.stringify(source.key);\n pluginsClientLines.push(` ${key}: ClientFactory<${source.importName}>;`);\n }\n pluginsClientLines.push(\"};\");\n }\n\n mkdirSync(dirname(pluginsClientPath), { recursive: true });\n writeFileIfChanged(pluginsClientPath, `${pluginsClientLines.join(\"\\n\")}\\n`);\n\n // --- Generate */src/lib/auth-types.gen.ts ---\n const authTypeTargets = [join(opts.configDir, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\")];\n const apiLibDir = join(opts.configDir, \"api\", \"src\", \"lib\");\n if (existsSync(apiLibDir)) {\n authTypeTargets.push(join(apiLibDir, \"auth-types.gen.ts\"));\n }\n const hostLibDir = join(opts.configDir, \"host\", \"src\", \"lib\");\n if (existsSync(join(opts.configDir, \"host\", \"src\"))) {\n authTypeTargets.push(join(hostLibDir, \"auth-types.gen.ts\"));\n }\n\n if (opts.authExportPath) {\n for (const authTypesPath of authTypeTargets) {\n writeAuthTypesGen(authTypesPath, opts.authExportPath);\n }\n } else if (opts.authSource) {\n for (const authTypesPath of authTypeTargets) {\n writeFallbackAuthTypesGen(authTypesPath);\n }\n }\n\n return uiContractPath;\n}\n\nexport async function syncApiContractBridge(opts: {\n configDir: string;\n runtimeConfig: RuntimeConfig;\n apiBaseUrl: string;\n}): Promise<{\n bridgePath: string;\n generatedPath: string | null;\n manifest: ApiPluginManifest | null;\n source: \"local\" | \"remote\";\n}> {\n const runtimeDir = join(opts.configDir, \".bos\", \"generated\");\n const pluginEntries = Object.entries(opts.runtimeConfig.plugins ?? {}).sort(([a], [b]) =>\n a.localeCompare(b),\n );\n const sources: ContractSource[] = [];\n let manifest: ApiPluginManifest | null = null;\n let generatedPath: string | null = null;\n let authSource: ContractSource | null = null;\n let authExportPath: string | null = null;\n\n const baseSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"api\",\n source: opts.runtimeConfig.api,\n baseUrl: opts.apiBaseUrl,\n generatedSubdir: \"api\",\n });\n sources.push(baseSource);\n\n if (opts.runtimeConfig.auth) {\n authSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"auth\",\n source: opts.runtimeConfig.auth,\n baseUrl: opts.runtimeConfig.auth.url,\n generatedSubdir: \"auth\",\n localSourceFactory: localAuthContractSource,\n });\n sources.push(authSource);\n if (authSource.generatedPath) {\n generatedPath = authSource.generatedPath;\n }\n\n // Fetch auth additional exports (auth-export.d.ts) for remote auth\n if (opts.runtimeConfig.auth.url && opts.runtimeConfig.auth.source !== \"local\") {\n try {\n const authManifest = await fetchApiPluginManifest(opts.runtimeConfig.auth.url);\n const fetchedAuthExportPath = await fetchAuthExportTypes({\n baseUrl: opts.runtimeConfig.auth.url,\n runtimeDir,\n manifest: authManifest,\n });\n if (fetchedAuthExportPath) {\n authExportPath = fetchedAuthExportPath;\n }\n } catch (error) {\n console.warn(\n `[API Contract] Failed to fetch auth additional exports: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n if (!authExportPath) {\n const localAuthExport = join(opts.configDir, \"plugins\", \"auth\", \"src\", \"auth-export.ts\");\n if (existsSync(localAuthExport)) {\n authExportPath = localAuthExport;\n } else {\n const generatedAuthExport = join(runtimeDir, \"auth\", \"auth-export.d.ts\");\n if (existsSync(generatedAuthExport)) {\n authExportPath = generatedAuthExport;\n }\n }\n }\n }\n\n for (const [key, plugin] of pluginEntries) {\n if (!plugin.url && !plugin.localPath) {\n console.warn(\n `[API Contract] Skipping plugin \"${key}\" — no URL resolved (local path missing and no production URL configured)`,\n );\n continue;\n }\n const source = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key,\n source: plugin,\n baseUrl: plugin.url,\n generatedSubdir: `plugins/${key}`,\n });\n sources.push(source);\n if (source.generatedPath) {\n generatedPath = source.generatedPath;\n }\n }\n\n const allPluginKeys = pluginEntries.map(([key]) => key);\n\n writeGeneratedFiles({\n configDir: opts.configDir,\n sources,\n pluginKeys: allPluginKeys,\n authSource,\n authExportPath,\n });\n\n if (opts.runtimeConfig.api.source !== \"local\") {\n manifest = await fetchApiPluginManifest(opts.apiBaseUrl);\n }\n\n return {\n bridgePath: join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\"),\n generatedPath,\n manifest,\n source: opts.runtimeConfig.api.source,\n };\n}\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AA2B,YAAY,QAAQ,mBAAmB;AACxE,gCAAe,oBAAoB,CACjC,kBAAiB;;;;AAMzB,MAAK,MAAM,CAAC,KAAK,WAAW,eAAe;AACzC,MAAI,CAAC,OAAO,OAAO,CAAC,OAAO,WAAW;AACpC,WAAQ,KACN,mCAAmC,IAAI,2EACxC;AACD;;EAEF,MAAM,SAAS,MAAM,sBAAsB;GACzC,WAAW,KAAK;GAChB;GACA;GACA,QAAQ;GACR,SAAS,OAAO;GAChB,iBAAiB,WAAW;GAC7B,CAAC;AACF,UAAQ,KAAK,OAAO;AACpB,MAAI,OAAO,cACT,iBAAgB,OAAO;;CAI3B,MAAM,gBAAgB,cAAc,KAAK,CAAC,SAAS,IAAI;AAEvD,qBAAoB;EAClB,WAAW,KAAK;EAChB;EACA,YAAY;EACZ;EACA;EACD,CAAC;AAEF,KAAI,KAAK,cAAc,IAAI,WAAW,QACpC,YAAW,MAAM,uBAAuB,KAAK,WAAW;AAG1D,QAAO;EACL,gCAAiB,KAAK,WAAW,MAAM,OAAO,OAAO,mBAAmB;EACxE;EACA;EACA,QAAQ,KAAK,cAAc,IAAI;EAChC"}
1
+ {"version":3,"file":"api-contract.cjs","names":[],"sources":["../src/api-contract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport type { RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nconst REMOTE_FETCH_TIMEOUT_MS = 10_000;\n\nexport interface ApiPluginManifest {\n schemaVersion: 1;\n kind: \"every-plugin/manifest\";\n plugin: {\n name: string;\n version: string;\n };\n runtime: {\n remoteEntry: string;\n };\n contract?: {\n kind: \"orpc\";\n types: {\n path: string;\n exportName: string;\n typeName: string;\n sha256?: string;\n };\n };\n additionalExports?: Array<{\n path: string;\n exports: string[];\n sha256?: string;\n }>;\n}\n\ninterface ContractSource {\n key: string;\n importName: string;\n sourceFilePath: string;\n generatedPath?: string;\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction trimTrailingSlash(input: string): string {\n return input.replace(/\\/$/, \"\");\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return input.replace(/[^A-Za-z0-9_]/g, \"_\").replace(/^[^A-Za-z_]+/, \"_\");\n}\n\nfunction toImportPath(fromFile: string, targetFile: string): string {\n const rel = relative(dirname(fromFile), targetFile).replace(/\\\\/g, \"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nfunction writeFileIfChanged(filePath: string, content: string) {\n try {\n if (readFileSync(filePath, \"utf8\") === content) return false;\n } catch {\n // file does not exist yet\n }\n\n writeFileSync(filePath, content);\n return true;\n}\n\nfunction getApiPluginManifestUrl(apiBaseUrl: string): string {\n return `${trimTrailingSlash(apiBaseUrl)}/plugin.manifest.json`;\n}\n\nasync function fetchWithTimeout(url: string): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), REMOTE_FETCH_TIMEOUT_MS);\n\n try {\n return await fetch(url, { signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Timed out fetching ${url} after ${REMOTE_FETCH_TIMEOUT_MS}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function fetchApiPluginManifest(apiBaseUrl: string): Promise<ApiPluginManifest> {\n const response = await fetchWithTimeout(getApiPluginManifestUrl(apiBaseUrl));\n if (!response.ok) {\n throw new Error(\n `Failed to fetch API plugin manifest: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as ApiPluginManifest;\n if (manifest.schemaVersion !== 1 || manifest.kind !== \"every-plugin/manifest\") {\n throw new Error(\"Unsupported API plugin manifest format\");\n }\n\n return manifest;\n}\n\nfunction localApiContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"api\", \"src\", \"contract.ts\");\n return {\n key: \"api\",\n importName: \"BaseApiContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nfunction localAuthContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"plugins\", \"auth\", \"src\", \"contract.ts\");\n return {\n key: \"auth\",\n importName: \"authContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nasync function remoteContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n name: string;\n baseUrl: string;\n generatedSubdir: string;\n}): Promise<ContractSource> {\n const manifest = await fetchApiPluginManifest(opts.baseUrl);\n if (!manifest.contract) {\n throw new Error(\n `Plugin manifest for ${manifest.plugin.name} does not advertise contract types`,\n );\n }\n\n const contractUrl = `${trimTrailingSlash(opts.baseUrl)}/${manifest.contract.types.path.replace(/^\\.\\//, \"\")}`;\n const contractResponse = await fetchWithTimeout(contractUrl);\n if (!contractResponse.ok) {\n throw new Error(\n `Failed to fetch contract types: ${contractResponse.status} ${contractResponse.statusText}`,\n );\n }\n\n const contractTypes = await contractResponse.text();\n if (manifest.contract.types.sha256 && manifest.contract.types.sha256 !== sha256(contractTypes)) {\n throw new Error(\"Fetched contract types failed checksum verification\");\n }\n\n const generatedPath = join(opts.runtimeDir, opts.generatedSubdir, \"contract.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, contractTypes);\n\n return {\n key: opts.name,\n importName: `${sanitizeIdentifier(opts.name)}Contract`,\n sourceFilePath: generatedPath,\n generatedPath,\n };\n}\n\nasync function fetchAuthExportTypes(opts: {\n baseUrl: string;\n runtimeDir: string;\n manifest: ApiPluginManifest;\n}): Promise<string | null> {\n if (!opts.manifest.additionalExports || opts.manifest.additionalExports.length === 0) {\n return null;\n }\n\n const authExportEntry = opts.manifest.additionalExports.find(\n (entry) => entry.path.includes(\"auth-export\") || entry.path.endsWith(\"auth-export.d.ts\"),\n );\n\n if (!authExportEntry) {\n return null;\n }\n\n const exportUrl = `${trimTrailingSlash(opts.baseUrl)}/${authExportEntry.path.replace(/^\\.\\//, \"\")}`;\n const response = await fetchWithTimeout(exportUrl);\n if (!response.ok) {\n console.warn(`[API Contract] Failed to fetch auth export types: ${response.status}`);\n return null;\n }\n\n const content = await response.text();\n if (authExportEntry.sha256 && authExportEntry.sha256 !== sha256(content)) {\n console.warn(\"[API Contract] Auth export types checksum mismatch\");\n return null;\n }\n\n const generatedPath = join(opts.runtimeDir, \"auth\", \"auth-export.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, content);\n\n return generatedPath;\n}\n\nfunction writeAuthTypesGen(targetPath: string, authExportPath: string) {\n const exportImportPath = toImportPath(targetPath, authExportPath);\n const content = [\n `export type {`,\n ` Auth,`,\n ` AuthOrganizationContext,`,\n ` AuthOrganization,`,\n ` AuthOrganizationSummary,`,\n ` AuthOrganizationMember,`,\n ` AuthApiKey,`,\n ` AuthInvitation,`,\n ` GetActiveMemberInput,`,\n ` GetOrganizationInput,`,\n ` ListMembersInput,`,\n ` ListInvitationsInput,`,\n ` ListApiKeysInput,`,\n ` AuthServices,`,\n ` createAuthInstance,`,\n `} from \"${exportImportPath}\";`,\n `import type { InferOutput, ContractType as AuthContract } from \"${toImportPath(targetPath, join(dirname(authExportPath), \"contract.d.ts\"))}\";`,\n `import type { Auth as BaseAuth } from \"${exportImportPath}\";`,\n \"\",\n 'type RawAuthSession = InferOutput<\"getSession\">;',\n 'type RawAuthRequestContext = InferOutput<\"getContext\">;',\n 'type RawAuthActiveMember = InferOutput<\"getActiveMember\">;',\n \"\",\n 'export type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {',\n \" role?: string | null;\",\n \" isAnonymous?: boolean | null;\",\n \" walletAddress?: string | null;\",\n \" banned?: boolean | null;\",\n \"};\",\n 'export type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {',\n \" activeOrganizationId?: string | null;\",\n \"};\",\n \"export type AuthSession = {\",\n \" user: AuthSessionUser | null;\",\n \" session: AuthSessionData | null;\",\n \"};\",\n \"export type AuthRequestContext = RawAuthRequestContext;\",\n \"export type AuthActiveMember = RawAuthActiveMember;\",\n 'export type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];',\n \"export type AuthContractType = AuthContract;\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nfunction writeFallbackAuthTypesGen(targetPath: string) {\n const content = [\n 'import type { Auth } from \"better-auth\";',\n 'export type { Auth } from \"better-auth\";',\n 'export type AuthSession = Auth[\"$Infer\"][\"Session\"];',\n \"export type AuthSessionData = AuthSession;\",\n 'export type AuthSessionUser = NonNullable<AuthSession[\"user\"]>;',\n \"export interface AuthOrganizationContext {\",\n \" activeOrganizationId: string | null;\",\n \" organization: { id: string; name: string; slug: string; logo?: string | null; metadata?: Record<string, unknown> } | null;\",\n \" member: { id: string; role: string } | null;\",\n \" isPersonal: boolean;\",\n \" hasOrganization: boolean;\",\n \"}\",\n \"export interface AuthRequestContext {\",\n \" user: AuthSessionUser | null;\",\n \" userId: string | null;\",\n \" isAuthenticated: boolean;\",\n ' authMethod: \"session\" | \"apiKey\" | \"anonymous\" | \"none\";',\n \" near: {\",\n \" primaryAccountId: string | null;\",\n \" linkedAccounts: Array<{ accountId: string; network: string; publicKey: string; isPrimary: boolean }>;\",\n \" hasNearAccount: boolean;\",\n \" };\",\n \" organization: AuthOrganizationContext;\",\n \" organizations?: Array<{ id: string; role: string; name?: string; slug?: string }>;\",\n \"}\",\n \"export type AuthActiveMember = { id: string | null; role: string | null; organizationId: string | null };\",\n \"export type AuthOrganization = {\",\n \" id: string;\",\n \" name: string;\",\n \" slug: string;\",\n \" logo?: string | null;\",\n \" metadata?: Record<string, unknown> | null;\",\n \" createdAt: Date;\",\n \"};\",\n 'export type AuthOrganizationSummary = NonNullable<AuthOrganizationContext[\"organization\"]>;',\n 'export type AuthOrganizationMember = NonNullable<AuthOrganizationContext[\"member\"]>;',\n \"export type AuthApiKey = {\",\n \" id: string;\",\n \" name: string | null;\",\n \" prefix: string | null;\",\n \" start: string | null;\",\n \" expiresAt: Date | null;\",\n \" createdAt: Date;\",\n \" updatedAt: Date;\",\n \" metadata: unknown | null;\",\n \" permissions: Record<string, string[]> | null;\",\n \"};\",\n \"export type AuthInvitation = {\",\n \" id: string;\",\n \" organizationId: string;\",\n \" email: string;\",\n \" role: string | null;\",\n \" status: string;\",\n \" expiresAt: Date;\",\n \" inviterId: string;\",\n \"};\",\n \"export type GetActiveMemberInput = { organizationId?: string };\",\n \"export type GetOrganizationInput = { id: string };\",\n \"export type ListMembersInput = { organizationId: string };\",\n \"export type ListInvitationsInput = { organizationId: string };\",\n \"export type ListApiKeysInput = { organizationId?: string };\",\n \"export type createAuthInstance = never;\",\n \"export interface AuthServices {\",\n \" auth: Auth;\",\n \" db: unknown;\",\n \" driver: { close(): Promise<void> };\",\n \" handler: (req: Request) => Promise<Response>;\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nasync function resolveContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n key: string;\n source: RuntimePluginConfig | { url: string; localPath?: string; name: string } | null;\n baseUrl: string;\n generatedSubdir: string;\n localSourceFactory?: (configDir: string) => ContractSource;\n}): Promise<ContractSource> {\n if (opts.key === \"api\") {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"BaseApiContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return localApiContractSource(opts.configDir);\n }\n }\n\n if (opts.key === \"auth\" && opts.localSourceFactory) {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"authContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return opts.localSourceFactory(opts.configDir);\n }\n }\n\n if (\n opts.source &&\n \"localPath\" in opts.source &&\n opts.source.localPath != null &&\n opts.source.localPath !== \"\"\n ) {\n return {\n key: opts.key,\n importName: `${sanitizeIdentifier(opts.key)}Contract`,\n sourceFilePath: join(opts.source.localPath, \"src\", \"contract.ts\"),\n };\n }\n\n return remoteContractSource({\n configDir: opts.configDir,\n runtimeDir: opts.runtimeDir,\n name: opts.key,\n baseUrl: opts.baseUrl,\n generatedSubdir: opts.generatedSubdir,\n });\n}\n\nfunction writeGeneratedFiles(opts: {\n configDir: string;\n sources: ContractSource[];\n pluginKeys: string[];\n authSource: ContractSource | null;\n authExportPath?: string | null;\n}) {\n const baseSource = opts.sources.find((source) => source.key === \"api\");\n const pluginSources = opts.pluginKeys\n .map((key) => opts.sources.find((entry) => entry.key === key))\n .filter((source): source is ContractSource => Boolean(source));\n\n if (!baseSource) {\n throw new Error(\"API contract source is required to generate the aggregate contract\");\n }\n\n // --- Generate ui/src/lib/api-types.gen.ts ---\n const uiContractPath = join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n const uiLines: string[] = [];\n\n for (const source of opts.sources) {\n const importPath = toImportPath(uiContractPath, source.sourceFilePath);\n uiLines.push(`import type { ContractType as ${source.importName} } from \"${importPath}\";`);\n }\n\n uiLines.push(\"\");\n\n const compositeParts: string[] = [];\n if (opts.authSource) {\n compositeParts.push(`auth: ${opts.authSource.importName}`);\n }\n for (const source of pluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key) ? source.key : JSON.stringify(source.key);\n compositeParts.push(`${key}: ${source.importName}`);\n }\n\n if (compositeParts.length === 0) {\n uiLines.push(`export type ApiContract = ${baseSource.importName};`);\n } else {\n uiLines.push(`export type ApiContract = ${baseSource.importName} & {`);\n for (const part of compositeParts) {\n uiLines.push(` ${part};`);\n }\n uiLines.push(\"};\");\n }\n mkdirSync(dirname(uiContractPath), { recursive: true });\n writeFileIfChanged(uiContractPath, `${uiLines.join(\"\\n\")}\\n`);\n\n // --- Generate api/src/lib/plugins-types.gen.ts ---\n // Includes both plugin contracts AND auth as a unified PluginsClient type\n const pluginsClientPath = join(opts.configDir, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n const pluginsClientLines: string[] = [];\n\n for (const source of pluginSources) {\n const importPath = toImportPath(pluginsClientPath, source.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${source.importName} } from \"${importPath}\";`,\n );\n }\n\n if (opts.authSource) {\n const authImportPath = toImportPath(pluginsClientPath, opts.authSource.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${opts.authSource.importName} } from \"${authImportPath}\";`,\n );\n }\n\n pluginsClientLines.push(\n 'import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";',\n );\n pluginsClientLines.push(\n \"type ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\",\n );\n pluginsClientLines.push(\"\");\n\n const allPluginSources = [...pluginSources];\n if (opts.authSource) {\n allPluginSources.push({ ...opts.authSource, key: \"auth\" });\n }\n\n if (allPluginSources.length === 0) {\n pluginsClientLines.push(\"export type PluginsClient = Record<string, never>;\");\n } else {\n pluginsClientLines.push(\"export type PluginsClient = {\");\n for (const source of allPluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key)\n ? source.key\n : JSON.stringify(source.key);\n pluginsClientLines.push(` ${key}: ClientFactory<${source.importName}>;`);\n }\n pluginsClientLines.push(\"};\");\n }\n\n mkdirSync(dirname(pluginsClientPath), { recursive: true });\n writeFileIfChanged(pluginsClientPath, `${pluginsClientLines.join(\"\\n\")}\\n`);\n\n // --- Generate */src/lib/auth-types.gen.ts ---\n const authTypeTargets = [join(opts.configDir, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\")];\n const apiLibDir = join(opts.configDir, \"api\", \"src\", \"lib\");\n if (existsSync(apiLibDir)) {\n authTypeTargets.push(join(apiLibDir, \"auth-types.gen.ts\"));\n }\n const hostLibDir = join(opts.configDir, \"host\", \"src\", \"lib\");\n if (existsSync(join(opts.configDir, \"host\", \"src\"))) {\n authTypeTargets.push(join(hostLibDir, \"auth-types.gen.ts\"));\n }\n\n if (opts.authExportPath) {\n for (const authTypesPath of authTypeTargets) {\n writeAuthTypesGen(authTypesPath, opts.authExportPath);\n }\n } else if (opts.authSource) {\n for (const authTypesPath of authTypeTargets) {\n writeFallbackAuthTypesGen(authTypesPath);\n }\n }\n\n return uiContractPath;\n}\n\nexport async function syncApiContractBridge(opts: {\n configDir: string;\n runtimeConfig: RuntimeConfig;\n apiBaseUrl: string;\n}): Promise<{\n bridgePath: string;\n generatedPath: string | null;\n manifest: ApiPluginManifest | null;\n source: \"local\" | \"remote\";\n}> {\n const runtimeDir = join(opts.configDir, \".bos\", \"generated\");\n const pluginEntries = Object.entries(opts.runtimeConfig.plugins ?? {}).sort(([a], [b]) =>\n a.localeCompare(b),\n );\n const sources: ContractSource[] = [];\n let manifest: ApiPluginManifest | null = null;\n let generatedPath: string | null = null;\n let authSource: ContractSource | null = null;\n let authExportPath: string | null = null;\n\n const baseSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"api\",\n source: opts.runtimeConfig.api,\n baseUrl: opts.apiBaseUrl,\n generatedSubdir: \"api\",\n });\n sources.push(baseSource);\n\n if (opts.runtimeConfig.auth) {\n authSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"auth\",\n source: opts.runtimeConfig.auth,\n baseUrl: opts.runtimeConfig.auth.url,\n generatedSubdir: \"auth\",\n localSourceFactory: localAuthContractSource,\n });\n sources.push(authSource);\n if (authSource.generatedPath) {\n generatedPath = authSource.generatedPath;\n }\n\n // Fetch auth additional exports (auth-export.d.ts) for remote auth\n if (opts.runtimeConfig.auth.url && opts.runtimeConfig.auth.source !== \"local\") {\n try {\n const authManifest = await fetchApiPluginManifest(opts.runtimeConfig.auth.url);\n const fetchedAuthExportPath = await fetchAuthExportTypes({\n baseUrl: opts.runtimeConfig.auth.url,\n runtimeDir,\n manifest: authManifest,\n });\n if (fetchedAuthExportPath) {\n authExportPath = fetchedAuthExportPath;\n }\n } catch (error) {\n console.warn(\n `[API Contract] Failed to fetch auth additional exports: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n if (!authExportPath) {\n const localAuthExport = join(opts.configDir, \"plugins\", \"auth\", \"src\", \"auth-export.ts\");\n if (existsSync(localAuthExport)) {\n authExportPath = localAuthExport;\n } else {\n const generatedAuthExport = join(runtimeDir, \"auth\", \"auth-export.d.ts\");\n if (existsSync(generatedAuthExport)) {\n authExportPath = generatedAuthExport;\n }\n }\n }\n }\n\n for (const [key, plugin] of pluginEntries) {\n if (!plugin.url && !plugin.localPath) {\n console.warn(\n `[API Contract] Skipping plugin \"${key}\" — no URL resolved (local path missing and no production URL configured)`,\n );\n continue;\n }\n const source = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key,\n source: plugin,\n baseUrl: plugin.url,\n generatedSubdir: `plugins/${key}`,\n });\n sources.push(source);\n if (source.generatedPath) {\n generatedPath = source.generatedPath;\n }\n }\n\n const allPluginKeys = pluginEntries.map(([key]) => key);\n\n writeGeneratedFiles({\n configDir: opts.configDir,\n sources,\n pluginKeys: allPluginKeys,\n authSource,\n authExportPath,\n });\n\n if (opts.runtimeConfig.api.source !== \"local\") {\n manifest = await fetchApiPluginManifest(opts.apiBaseUrl);\n }\n\n return {\n bridgePath: join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\"),\n generatedPath,\n manifest,\n source: opts.runtimeConfig.api.source,\n };\n}\n"],"mappings":";;;;;;AAKA,MAAM,0BAA0B;AAmChC,SAAS,OAAO,OAAuB;AACrC,oCAAkB,SAAS,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM;;AAGzD,SAAS,kBAAkB,OAAuB;AAChD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,mBAAmB,OAAuB;AACjD,QAAO,MAAM,QAAQ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CAGT,MAAM,UAAU,MAAM,SAAS,MAAM;AACrC,KAAI,gBAAgB,UAAU,gBAAgB,WAAW,OAAO,QAAQ,EAAE;AACxE,UAAQ,KAAK,qDAAqD;AAClE,SAAO;;CAGT,MAAM,oCAAqB,KAAK,YAAY,QAAQ,mBAAmB;AACvE,+CAAkB,cAAc,EAAE,EAAE,WAAW,MAAM,CAAC;AACtD,oBAAmB,eAAe,QAAQ;AAE1C,QAAO;;AAGT,SAAS,kBAAkB,YAAoB,gBAAwB;CACrE,MAAM,mBAAmB,aAAa,YAAY,eAAe;CACjE,MAAM,UAAU;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,iBAAiB;EAC5B,mEAAmE,aAAa,uDAAyB,eAAe,EAAE,gBAAgB,CAAC,CAAC;EAC5I,0CAA0C,iBAAiB;EAC3D;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;AACZ,+CAAkB,WAAW,EAAE,EAAE,WAAW,MAAM,CAAC;AACnD,oBAAmB,YAAY,QAAQ;;AAGzC,SAAS,0BAA0B,YAAoB;CACrD,MAAM,UAAU;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;AACZ,+CAAkB,WAAW,EAAE,EAAE,WAAW,MAAM,CAAC;AACnD,oBAAmB,Y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sB;GACzC,WAAW,KAAK;GAChB;GACA;GACA,QAAQ;GACR,SAAS,OAAO;GAChB,iBAAiB,WAAW;GAC7B,CAAC;AACF,UAAQ,KAAK,OAAO;AACpB,MAAI,OAAO,cACT,iBAAgB,OAAO;;CAI3B,MAAM,gBAAgB,cAAc,KAAK,CAAC,SAAS,IAAI;AAEvD,qBAAoB;EAClB,WAAW,KAAK;EAChB;EACA,YAAY;EACZ;EACA;EACD,CAAC;AAEF,KAAI,KAAK,cAAc,IAAI,WAAW,QACpC,YAAW,MAAM,uBAAuB,KAAK,WAAW;AAG1D,QAAO;EACL,gCAAiB,KAAK,WAAW,MAAM,OAAO,OAAO,mBAAmB;EACxE;EACA;EACA,QAAQ,KAAK,cAAc,IAAI;EAChC"}
@@ -1 +1 @@
1
- {"version":3,"file":"api-contract.mjs","names":[],"sources":["../src/api-contract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport type { RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nconst REMOTE_FETCH_TIMEOUT_MS = 10_000;\n\nexport interface ApiPluginManifest {\n schemaVersion: 1;\n kind: \"every-plugin/manifest\";\n plugin: {\n name: string;\n version: string;\n };\n runtime: {\n remoteEntry: string;\n };\n contract?: {\n kind: \"orpc\";\n types: {\n path: string;\n exportName: string;\n typeName: string;\n sha256?: string;\n };\n };\n additionalExports?: Array<{\n path: string;\n exports: string[];\n sha256?: string;\n }>;\n}\n\ninterface ContractSource {\n key: string;\n importName: string;\n sourceFilePath: string;\n generatedPath?: string;\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction trimTrailingSlash(input: string): string {\n return input.replace(/\\/$/, \"\");\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return input.replace(/[^A-Za-z0-9_]/g, \"_\").replace(/^[^A-Za-z_]+/, \"_\");\n}\n\nfunction toImportPath(fromFile: string, targetFile: string): string {\n const rel = relative(dirname(fromFile), targetFile).replace(/\\\\/g, \"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nfunction writeFileIfChanged(filePath: string, content: string) {\n try {\n if (readFileSync(filePath, \"utf8\") === content) return false;\n } catch {\n // file does not exist yet\n }\n\n writeFileSync(filePath, content);\n return true;\n}\n\nfunction getApiPluginManifestUrl(apiBaseUrl: string): string {\n return `${trimTrailingSlash(apiBaseUrl)}/plugin.manifest.json`;\n}\n\nasync function fetchWithTimeout(url: string): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), REMOTE_FETCH_TIMEOUT_MS);\n\n try {\n return await fetch(url, { signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Timed out fetching ${url} after ${REMOTE_FETCH_TIMEOUT_MS}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function fetchApiPluginManifest(apiBaseUrl: string): Promise<ApiPluginManifest> {\n const response = await fetchWithTimeout(getApiPluginManifestUrl(apiBaseUrl));\n if (!response.ok) {\n throw new Error(\n `Failed to fetch API plugin manifest: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as ApiPluginManifest;\n if (manifest.schemaVersion !== 1 || manifest.kind !== \"every-plugin/manifest\") {\n throw new Error(\"Unsupported API plugin manifest format\");\n }\n\n return manifest;\n}\n\nfunction localApiContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"api\", \"src\", \"contract.ts\");\n return {\n key: \"api\",\n importName: \"BaseApiContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nfunction localAuthContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"plugins\", \"auth\", \"src\", \"contract.ts\");\n return {\n key: \"auth\",\n importName: \"authContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nasync function remoteContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n name: string;\n baseUrl: string;\n generatedSubdir: string;\n}): Promise<ContractSource> {\n const manifest = await fetchApiPluginManifest(opts.baseUrl);\n if (!manifest.contract) {\n throw new Error(\n `Plugin manifest for ${manifest.plugin.name} does not advertise contract types`,\n );\n }\n\n const contractUrl = `${trimTrailingSlash(opts.baseUrl)}/${manifest.contract.types.path.replace(/^\\.\\//, \"\")}`;\n const contractResponse = await fetchWithTimeout(contractUrl);\n if (!contractResponse.ok) {\n throw new Error(\n `Failed to fetch contract types: ${contractResponse.status} ${contractResponse.statusText}`,\n );\n }\n\n const contractTypes = await contractResponse.text();\n if (manifest.contract.types.sha256 && manifest.contract.types.sha256 !== sha256(contractTypes)) {\n throw new Error(\"Fetched contract types failed checksum verification\");\n }\n\n const generatedPath = join(opts.runtimeDir, opts.generatedSubdir, \"contract.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, contractTypes);\n\n return {\n key: opts.name,\n importName: `${sanitizeIdentifier(opts.name)}Contract`,\n sourceFilePath: generatedPath,\n generatedPath,\n };\n}\n\nasync function fetchAuthExportTypes(opts: {\n baseUrl: string;\n runtimeDir: string;\n manifest: ApiPluginManifest;\n}): Promise<string | null> {\n if (!opts.manifest.additionalExports || opts.manifest.additionalExports.length === 0) {\n return null;\n }\n\n const authExportEntry = opts.manifest.additionalExports.find(\n (entry) => entry.path.includes(\"auth-export\") || entry.path.endsWith(\"auth-export.d.ts\"),\n );\n\n if (!authExportEntry) {\n return null;\n }\n\n const exportUrl = `${trimTrailingSlash(opts.baseUrl)}/${authExportEntry.path.replace(/^\\.\\//, \"\")}`;\n const response = await fetchWithTimeout(exportUrl);\n if (!response.ok) {\n console.warn(`[API Contract] Failed to fetch auth export types: ${response.status}`);\n return null;\n }\n\n const content = await response.text();\n if (authExportEntry.sha256 && authExportEntry.sha256 !== sha256(content)) {\n console.warn(\"[API Contract] Auth export types checksum mismatch\");\n return null;\n }\n\n const generatedPath = join(opts.runtimeDir, \"auth\", \"auth-export.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, content);\n\n return generatedPath;\n}\n\nfunction writeAuthTypesGen(targetPath: string, authExportPath: string) {\n const exportImportPath = toImportPath(targetPath, authExportPath);\n const content = [\n `export type {`,\n ` Auth,`,\n ` AuthOrganizationContext,`,\n ` AuthOrganization,`,\n ` AuthOrganizationSummary,`,\n ` AuthOrganizationMember,`,\n ` AuthApiKey,`,\n ` AuthInvitation,`,\n ` GetActiveMemberInput,`,\n ` GetOrganizationInput,`,\n ` ListMembersInput,`,\n ` ListInvitationsInput,`,\n ` ListApiKeysInput,`,\n ` AuthServices,`,\n ` createAuthInstance,`,\n `} from \"${exportImportPath}\";`,\n `import type { InferOutput, ContractType as AuthContract } from \"${toImportPath(targetPath, join(dirname(authExportPath), \"contract.d.ts\"))}\";`,\n `import type { Auth as BaseAuth } from \"${exportImportPath}\";`,\n \"\",\n 'type RawAuthSession = InferOutput<\"getSession\">;',\n 'type RawAuthRequestContext = InferOutput<\"getContext\">;',\n 'type RawAuthActiveMember = InferOutput<\"getActiveMember\">;',\n \"\",\n 'export type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {',\n \" role?: string | null;\",\n \" isAnonymous?: boolean | null;\",\n \" walletAddress?: string | null;\",\n \" banned?: boolean | null;\",\n \"};\",\n 'export type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {',\n \" activeOrganizationId?: string | null;\",\n \"};\",\n \"export type AuthSession = {\",\n \" user: AuthSessionUser | null;\",\n \" session: AuthSessionData | null;\",\n \"};\",\n \"export type AuthRequestContext = RawAuthRequestContext;\",\n \"export type AuthActiveMember = RawAuthActiveMember;\",\n 'export type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];',\n \"export type AuthContractType = AuthContract;\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nfunction writeFallbackAuthTypesGen(targetPath: string) {\n const content = [\n 'import type { Auth } from \"better-auth\";',\n 'export type { Auth } from \"better-auth\";',\n 'export type AuthSession = Auth[\"$Infer\"][\"Session\"];',\n \"export type AuthSessionData = AuthSession;\",\n 'export type AuthSessionUser = NonNullable<AuthSession[\"user\"]>;',\n \"export interface AuthOrganizationContext {\",\n \" activeOrganizationId: string | null;\",\n \" organization: { id: string; name: string; slug: string; logo?: string | null; metadata?: Record<string, unknown> } | null;\",\n \" member: { id: string; role: string } | null;\",\n \" isPersonal: boolean;\",\n \" hasOrganization: boolean;\",\n \"}\",\n \"export interface AuthRequestContext {\",\n \" user: AuthSessionUser | null;\",\n \" userId: string | null;\",\n \" isAuthenticated: boolean;\",\n ' authMethod: \"session\" | \"apiKey\" | \"anonymous\" | \"none\";',\n \" near: {\",\n \" primaryAccountId: string | null;\",\n \" linkedAccounts: Array<{ accountId: string; network: string; publicKey: string; isPrimary: boolean }>;\",\n \" hasNearAccount: boolean;\",\n \" };\",\n \" organization: AuthOrganizationContext;\",\n \" organizations?: Array<{ id: string; role: string; name?: string; slug?: string }>;\",\n \"}\",\n \"export type AuthActiveMember = { id: string | null; role: string | null; organizationId: string | null };\",\n \"export type AuthOrganization = {\",\n \" id: string;\",\n \" name: string;\",\n \" slug: string;\",\n \" logo?: string | null;\",\n \" metadata?: Record<string, unknown> | null;\",\n \" createdAt: Date;\",\n \"};\",\n 'export type AuthOrganizationSummary = NonNullable<AuthOrganizationContext[\"organization\"]>;',\n 'export type AuthOrganizationMember = NonNullable<AuthOrganizationContext[\"member\"]>;',\n \"export type AuthApiKey = {\",\n \" id: string;\",\n \" name: string | null;\",\n \" prefix: string | null;\",\n \" start: string | null;\",\n \" expiresAt: Date | null;\",\n \" createdAt: Date;\",\n \" updatedAt: Date;\",\n \" metadata: unknown | null;\",\n \" permissions: Record<string, string[]> | null;\",\n \"};\",\n \"export type AuthInvitation = {\",\n \" id: string;\",\n \" organizationId: string;\",\n \" email: string;\",\n \" role: string | null;\",\n \" status: string;\",\n \" expiresAt: Date;\",\n \" inviterId: string;\",\n \"};\",\n \"export type GetActiveMemberInput = { organizationId?: string };\",\n \"export type GetOrganizationInput = { id: string };\",\n \"export type ListMembersInput = { organizationId: string };\",\n \"export type ListInvitationsInput = { organizationId: string };\",\n \"export type ListApiKeysInput = { organizationId?: string };\",\n \"export type createAuthInstance = never;\",\n \"export interface AuthServices {\",\n \" auth: Auth;\",\n \" db: unknown;\",\n \" driver: { close(): Promise<void> };\",\n \" handler: (req: Request) => Promise<Response>;\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nasync function resolveContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n key: string;\n source: RuntimePluginConfig | { url: string; localPath?: string; name: string } | null;\n baseUrl: string;\n generatedSubdir: string;\n localSourceFactory?: (configDir: string) => ContractSource;\n}): Promise<ContractSource> {\n if (opts.key === \"api\") {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"BaseApiContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return localApiContractSource(opts.configDir);\n }\n }\n\n if (opts.key === \"auth\" && opts.localSourceFactory) {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"authContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return opts.localSourceFactory(opts.configDir);\n }\n }\n\n if (\n opts.source &&\n \"localPath\" in opts.source &&\n opts.source.localPath != null &&\n opts.source.localPath !== \"\"\n ) {\n return {\n key: opts.key,\n importName: `${sanitizeIdentifier(opts.key)}Contract`,\n sourceFilePath: join(opts.source.localPath, \"src\", \"contract.ts\"),\n };\n }\n\n return remoteContractSource({\n configDir: opts.configDir,\n runtimeDir: opts.runtimeDir,\n name: opts.key,\n baseUrl: opts.baseUrl,\n generatedSubdir: opts.generatedSubdir,\n });\n}\n\nfunction writeGeneratedFiles(opts: {\n configDir: string;\n sources: ContractSource[];\n pluginKeys: string[];\n authSource: ContractSource | null;\n authExportPath?: string | null;\n}) {\n const baseSource = opts.sources.find((source) => source.key === \"api\");\n const pluginSources = opts.pluginKeys\n .map((key) => opts.sources.find((entry) => entry.key === key))\n .filter((source): source is ContractSource => Boolean(source));\n\n if (!baseSource) {\n throw new Error(\"API contract source is required to generate the aggregate contract\");\n }\n\n // --- Generate ui/src/lib/api-types.gen.ts ---\n const uiContractPath = join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n const uiLines: string[] = [];\n\n for (const source of opts.sources) {\n const importPath = toImportPath(uiContractPath, source.sourceFilePath);\n uiLines.push(`import type { ContractType as ${source.importName} } from \"${importPath}\";`);\n }\n\n uiLines.push(\"\");\n\n const compositeParts: string[] = [];\n if (opts.authSource) {\n compositeParts.push(`auth: ${opts.authSource.importName}`);\n }\n for (const source of pluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key) ? source.key : JSON.stringify(source.key);\n compositeParts.push(`${key}: ${source.importName}`);\n }\n\n if (compositeParts.length === 0) {\n uiLines.push(`export type ApiContract = ${baseSource.importName};`);\n } else {\n uiLines.push(`export type ApiContract = ${baseSource.importName} & {`);\n for (const part of compositeParts) {\n uiLines.push(` ${part};`);\n }\n uiLines.push(\"};\");\n }\n mkdirSync(dirname(uiContractPath), { recursive: true });\n writeFileIfChanged(uiContractPath, `${uiLines.join(\"\\n\")}\\n`);\n\n // --- Generate api/src/lib/plugins-types.gen.ts ---\n // Includes both plugin contracts AND auth as a unified PluginsClient type\n const pluginsClientPath = join(opts.configDir, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n const pluginsClientLines: string[] = [];\n\n for (const source of pluginSources) {\n const importPath = toImportPath(pluginsClientPath, source.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${source.importName} } from \"${importPath}\";`,\n );\n }\n\n if (opts.authSource) {\n const authImportPath = toImportPath(pluginsClientPath, opts.authSource.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${opts.authSource.importName} } from \"${authImportPath}\";`,\n );\n }\n\n pluginsClientLines.push(\n 'import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";',\n );\n pluginsClientLines.push(\n \"type ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\",\n );\n pluginsClientLines.push(\"\");\n\n const allPluginSources = [...pluginSources];\n if (opts.authSource) {\n allPluginSources.push({ ...opts.authSource, key: \"auth\" });\n }\n\n if (allPluginSources.length === 0) {\n pluginsClientLines.push(\"export type PluginsClient = Record<string, never>;\");\n } else {\n pluginsClientLines.push(\"export type PluginsClient = {\");\n for (const source of allPluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key)\n ? source.key\n : JSON.stringify(source.key);\n pluginsClientLines.push(` ${key}: ClientFactory<${source.importName}>;`);\n }\n pluginsClientLines.push(\"};\");\n }\n\n mkdirSync(dirname(pluginsClientPath), { recursive: true });\n writeFileIfChanged(pluginsClientPath, `${pluginsClientLines.join(\"\\n\")}\\n`);\n\n // --- Generate */src/lib/auth-types.gen.ts ---\n const authTypeTargets = [join(opts.configDir, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\")];\n const apiLibDir = join(opts.configDir, \"api\", \"src\", \"lib\");\n if (existsSync(apiLibDir)) {\n authTypeTargets.push(join(apiLibDir, \"auth-types.gen.ts\"));\n }\n const hostLibDir = join(opts.configDir, \"host\", \"src\", \"lib\");\n if (existsSync(join(opts.configDir, \"host\", \"src\"))) {\n authTypeTargets.push(join(hostLibDir, \"auth-types.gen.ts\"));\n }\n\n if (opts.authExportPath) {\n for (const authTypesPath of authTypeTargets) {\n writeAuthTypesGen(authTypesPath, opts.authExportPath);\n }\n } else if (opts.authSource) {\n for (const authTypesPath of authTypeTargets) {\n writeFallbackAuthTypesGen(authTypesPath);\n }\n }\n\n return uiContractPath;\n}\n\nexport async function syncApiContractBridge(opts: {\n configDir: string;\n runtimeConfig: RuntimeConfig;\n apiBaseUrl: string;\n}): Promise<{\n bridgePath: string;\n generatedPath: string | null;\n manifest: ApiPluginManifest | null;\n source: \"local\" | \"remote\";\n}> {\n const runtimeDir = join(opts.configDir, \".bos\", \"generated\");\n const pluginEntries = Object.entries(opts.runtimeConfig.plugins ?? {}).sort(([a], [b]) =>\n a.localeCompare(b),\n );\n const sources: ContractSource[] = [];\n let manifest: ApiPluginManifest | null = null;\n let generatedPath: string | null = null;\n let authSource: ContractSource | null = null;\n let authExportPath: string | null = null;\n\n const baseSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"api\",\n source: opts.runtimeConfig.api,\n baseUrl: opts.apiBaseUrl,\n generatedSubdir: \"api\",\n });\n sources.push(baseSource);\n\n if (opts.runtimeConfig.auth) {\n authSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"auth\",\n source: opts.runtimeConfig.auth,\n baseUrl: opts.runtimeConfig.auth.url,\n generatedSubdir: \"auth\",\n localSourceFactory: localAuthContractSource,\n });\n sources.push(authSource);\n if (authSource.generatedPath) {\n generatedPath = authSource.generatedPath;\n }\n\n // Fetch auth additional exports (auth-export.d.ts) for remote auth\n if (opts.runtimeConfig.auth.url && opts.runtimeConfig.auth.source !== \"local\") {\n try {\n const authManifest = await fetchApiPluginManifest(opts.runtimeConfig.auth.url);\n const fetchedAuthExportPath = await fetchAuthExportTypes({\n baseUrl: opts.runtimeConfig.auth.url,\n runtimeDir,\n manifest: authManifest,\n });\n if (fetchedAuthExportPath) {\n authExportPath = fetchedAuthExportPath;\n }\n } catch (error) {\n console.warn(\n `[API Contract] Failed to fetch auth additional exports: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n if (!authExportPath) {\n const localAuthExport = join(opts.configDir, \"plugins\", \"auth\", \"src\", \"auth-export.ts\");\n if (existsSync(localAuthExport)) {\n authExportPath = localAuthExport;\n } else {\n const generatedAuthExport = join(runtimeDir, \"auth\", \"auth-export.d.ts\");\n if (existsSync(generatedAuthExport)) {\n authExportPath = generatedAuthExport;\n }\n }\n }\n }\n\n for (const [key, plugin] of pluginEntries) {\n if (!plugin.url && !plugin.localPath) {\n console.warn(\n `[API Contract] Skipping plugin \"${key}\" — no URL resolved (local path missing and no production URL configured)`,\n );\n continue;\n }\n const source = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key,\n source: plugin,\n baseUrl: plugin.url,\n generatedSubdir: `plugins/${key}`,\n });\n sources.push(source);\n if (source.generatedPath) {\n generatedPath = source.generatedPath;\n }\n }\n\n const allPluginKeys = pluginEntries.map(([key]) => key);\n\n writeGeneratedFiles({\n configDir: opts.configDir,\n sources,\n pluginKeys: allPluginKeys,\n authSource,\n authExportPath,\n });\n\n if (opts.runtimeConfig.api.source !== \"local\") {\n manifest = await fetchApiPluginManifest(opts.apiBaseUrl);\n }\n\n return {\n bridgePath: join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\"),\n generatedPath,\n manifest,\n source: opts.runtimeConfig.api.source,\n };\n}\n"],"mappings":";;;;;AAKA,MAAM,0BAA0B;AAmChC,SAAS,OAAO,OAAuB;AACrC,QAAO,WAAW,SAAS,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM;;AAGzD,SAAS,kBAAkB,OAAuB;AAChD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,mBAAmB,OAAuB;AACjD,QAAO,MAAM,QAAQ,kBAAkB,IAAI,CAAC,QAAQ,gBAAgB,IAAI;;AAG1E,SAAS,aAAa,UAAkB,YAA4B;CAClE,MAAM,MAAM,SAAS,QAAQ,SAAS,EAAE,WAAW,CAAC,QAAQ,OAAO,IAAI;AACvE,QAAO,IAAI,WAAW,IAAI,GAAG,MAAM,KAAK;;AAG1C,SAAS,m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B;AACvE,WAAU,QAAQ,cAAc,EAAE,EAAE,WAAW,MAAM,CAAC;AACtD,oBAAmB,eAAe,QAAQ;AAE1C,QAAO;;AAGT,SAAS,kBAAkB,YAAoB,gBAAwB;CACrE,MAAM,mBAAmB,aAAa,YAAY,eAAe;CACjE,MAAM,UAAU;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,iBAAiB;EAC5B,mEAAmE,aAAa,YAAY,KAAK,QAAQ,eAAe,EAAE,gBAAgB,CAAC,CAAC;EAC5I,0CAA0C,iBAAiB;EAC3D;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;AACZ,WAAU,QAAQ,WAAW,EAAE,EAAE,WAAW,MAAM,CAAC;AACnD,oBAAmB,YAAY,QAAQ;;AAGzC,SAAS,0BAA0B,YAAoB;CACrD,MAAM,UAAU;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;AACZ,WAAU,QAAQ,WAAW,EAAE,EAAE,WAAW,MAAM,CAAC;AACnD,oBAAmB,YAAY,QAAQ;;AAGzC,eAAe,sBAAsB,MAQT;AAC1B,KAAI,KAAK,QAAQ,OAAO;EACtB,MAAM,YAAY,KAAK,UAAU,eAAe,KAAK,SAAS,KAAK,OAAO,YAAY;AACtF,MAAI,aAAa,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AAO;GAChB,iBAAiB,WAAW;GAC7B,CAAC;AACF,UAAQ,KAAK,OAAO;AACpB,MAAI,OAAO,cACT,iBAAgB,OAAO;;CAI3B,MAAM,gBAAgB,cAAc,KAAK,CAAC,SAAS,IAAI;AAEvD,qBAAoB;EAClB,WAAW,KAAK;EAChB;EACA,YAAY;EACZ;EACA;EACD,CAAC;AAEF,KAAI,KAAK,cAAc,IAAI,WAAW,QACpC,YAAW,MAAM,uBAAuB,KAAK,WAAW;AAG1D,QAAO;EACL,YAAY,KAAK,KAAK,WAAW,MAAM,OAAO,OAAO,mBAAmB;EACxE;EACA;EACA,QAAQ,KAAK,cAAc,IAAI;EAChC"}
1
+ {"version":3,"file":"api-contract.mjs","names":[],"sources":["../src/api-contract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport type { RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nconst REMOTE_FETCH_TIMEOUT_MS = 10_000;\n\nexport interface ApiPluginManifest {\n schemaVersion: 1;\n kind: \"every-plugin/manifest\";\n plugin: {\n name: string;\n version: string;\n };\n runtime: {\n remoteEntry: string;\n };\n contract?: {\n kind: \"orpc\";\n types: {\n path: string;\n exportName: string;\n typeName: string;\n sha256?: string;\n };\n };\n additionalExports?: Array<{\n path: string;\n exports: string[];\n sha256?: string;\n }>;\n}\n\ninterface ContractSource {\n key: string;\n importName: string;\n sourceFilePath: string;\n generatedPath?: string;\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction trimTrailingSlash(input: string): string {\n return input.replace(/\\/$/, \"\");\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return input.replace(/[^A-Za-z0-9_]/g, \"_\").replace(/^[^A-Za-z_]+/, \"_\");\n}\n\nfunction toImportPath(fromFile: string, targetFile: string): string {\n const rel = relative(dirname(fromFile), targetFile).replace(/\\\\/g, \"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nfunction writeFileIfChanged(filePath: string, content: string) {\n try {\n if (readFileSync(filePath, \"utf8\") === content) return false;\n } catch {\n // file does not exist yet\n }\n\n writeFileSync(filePath, content);\n return true;\n}\n\nfunction getApiPluginManifestUrl(apiBaseUrl: string): string {\n return `${trimTrailingSlash(apiBaseUrl)}/plugin.manifest.json`;\n}\n\nasync function fetchWithTimeout(url: string): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), REMOTE_FETCH_TIMEOUT_MS);\n\n try {\n return await fetch(url, { signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Timed out fetching ${url} after ${REMOTE_FETCH_TIMEOUT_MS}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function fetchApiPluginManifest(apiBaseUrl: string): Promise<ApiPluginManifest> {\n const response = await fetchWithTimeout(getApiPluginManifestUrl(apiBaseUrl));\n if (!response.ok) {\n throw new Error(\n `Failed to fetch API plugin manifest: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as ApiPluginManifest;\n if (manifest.schemaVersion !== 1 || manifest.kind !== \"every-plugin/manifest\") {\n throw new Error(\"Unsupported API plugin manifest format\");\n }\n\n return manifest;\n}\n\nfunction localApiContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"api\", \"src\", \"contract.ts\");\n return {\n key: \"api\",\n importName: \"BaseApiContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nfunction localAuthContractSource(configDir: string): ContractSource {\n const sourcePath = join(configDir, \"plugins\", \"auth\", \"src\", \"contract.ts\");\n return {\n key: \"auth\",\n importName: \"authContract\",\n sourceFilePath: sourcePath,\n };\n}\n\nasync function remoteContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n name: string;\n baseUrl: string;\n generatedSubdir: string;\n}): Promise<ContractSource> {\n const manifest = await fetchApiPluginManifest(opts.baseUrl);\n if (!manifest.contract) {\n throw new Error(\n `Plugin manifest for ${manifest.plugin.name} does not advertise contract types`,\n );\n }\n\n const contractUrl = `${trimTrailingSlash(opts.baseUrl)}/${manifest.contract.types.path.replace(/^\\.\\//, \"\")}`;\n const contractResponse = await fetchWithTimeout(contractUrl);\n if (!contractResponse.ok) {\n throw new Error(\n `Failed to fetch contract types: ${contractResponse.status} ${contractResponse.statusText}`,\n );\n }\n\n const contractTypes = await contractResponse.text();\n if (manifest.contract.types.sha256 && manifest.contract.types.sha256 !== sha256(contractTypes)) {\n throw new Error(\"Fetched contract types failed checksum verification\");\n }\n\n const generatedPath = join(opts.runtimeDir, opts.generatedSubdir, \"contract.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, contractTypes);\n\n return {\n key: opts.name,\n importName: `${sanitizeIdentifier(opts.name)}Contract`,\n sourceFilePath: generatedPath,\n generatedPath,\n };\n}\n\nasync function fetchAuthExportTypes(opts: {\n baseUrl: string;\n runtimeDir: string;\n manifest: ApiPluginManifest;\n}): Promise<string | null> {\n if (!opts.manifest.additionalExports || opts.manifest.additionalExports.length === 0) {\n return null;\n }\n\n const authExportEntry = opts.manifest.additionalExports.find(\n (entry) => entry.path.includes(\"auth-export\") || entry.path.endsWith(\"auth-export.d.ts\"),\n );\n\n if (!authExportEntry) {\n return null;\n }\n\n const exportUrl = `${trimTrailingSlash(opts.baseUrl)}/${authExportEntry.path.replace(/^\\.\\//, \"\")}`;\n const response = await fetchWithTimeout(exportUrl);\n if (!response.ok) {\n console.warn(`[API Contract] Failed to fetch auth export types: ${response.status}`);\n return null;\n }\n\n const content = await response.text();\n if (authExportEntry.sha256 && authExportEntry.sha256 !== sha256(content)) {\n console.warn(\"[API Contract] Auth export types checksum mismatch\");\n return null;\n }\n\n const generatedPath = join(opts.runtimeDir, \"auth\", \"auth-export.d.ts\");\n mkdirSync(dirname(generatedPath), { recursive: true });\n writeFileIfChanged(generatedPath, content);\n\n return generatedPath;\n}\n\nfunction writeAuthTypesGen(targetPath: string, authExportPath: string) {\n const exportImportPath = toImportPath(targetPath, authExportPath);\n const content = [\n `export type {`,\n ` Auth,`,\n ` AuthOrganizationContext,`,\n ` AuthOrganization,`,\n ` AuthOrganizationSummary,`,\n ` AuthOrganizationMember,`,\n ` AuthApiKey,`,\n ` AuthInvitation,`,\n ` GetActiveMemberInput,`,\n ` GetOrganizationInput,`,\n ` ListMembersInput,`,\n ` ListInvitationsInput,`,\n ` ListApiKeysInput,`,\n ` AuthServices,`,\n ` createAuthInstance,`,\n `} from \"${exportImportPath}\";`,\n `import type { InferOutput, ContractType as AuthContract } from \"${toImportPath(targetPath, join(dirname(authExportPath), \"contract.d.ts\"))}\";`,\n `import type { Auth as BaseAuth } from \"${exportImportPath}\";`,\n \"\",\n 'type RawAuthSession = InferOutput<\"getSession\">;',\n 'type RawAuthRequestContext = InferOutput<\"getContext\">;',\n 'type RawAuthActiveMember = InferOutput<\"getActiveMember\">;',\n \"\",\n 'export type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {',\n \" role?: string | null;\",\n \" isAnonymous?: boolean | null;\",\n \" walletAddress?: string | null;\",\n \" banned?: boolean | null;\",\n \"};\",\n 'export type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {',\n \" activeOrganizationId?: string | null;\",\n \"};\",\n \"export type AuthSession = {\",\n \" user: AuthSessionUser | null;\",\n \" session: AuthSessionData | null;\",\n \"};\",\n \"export type AuthRequestContext = RawAuthRequestContext;\",\n \"export type AuthActiveMember = RawAuthActiveMember;\",\n 'export type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];',\n \"export type AuthContractType = AuthContract;\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nfunction writeFallbackAuthTypesGen(targetPath: string) {\n const content = [\n 'import type { Auth } from \"better-auth\";',\n 'export type { Auth } from \"better-auth\";',\n 'export type AuthSession = Auth[\"$Infer\"][\"Session\"];',\n \"export type AuthSessionData = AuthSession;\",\n 'export type AuthSessionUser = NonNullable<AuthSession[\"user\"]>;',\n \"export interface AuthOrganizationContext {\",\n \" activeOrganizationId: string | null;\",\n \" organization: { id: string; name: string; slug: string; logo?: string | null; metadata?: Record<string, unknown> } | null;\",\n \" member: { id: string; role: string } | null;\",\n \" isPersonal: boolean;\",\n \" hasOrganization: boolean;\",\n \"}\",\n \"export interface AuthRequestContext {\",\n \" user: AuthSessionUser | null;\",\n \" userId: string | null;\",\n \" isAuthenticated: boolean;\",\n ' authMethod: \"session\" | \"apiKey\" | \"anonymous\" | \"none\";',\n \" near: {\",\n \" primaryAccountId: string | null;\",\n \" linkedAccounts: Array<{ accountId: string; network: string; publicKey: string; isPrimary: boolean }>;\",\n \" hasNearAccount: boolean;\",\n \" };\",\n \" organization: AuthOrganizationContext;\",\n \" organizations?: Array<{ id: string; role: string; name?: string; slug?: string }>;\",\n \"}\",\n \"export type AuthActiveMember = { id: string | null; role: string | null; organizationId: string | null };\",\n \"export type AuthOrganization = {\",\n \" id: string;\",\n \" name: string;\",\n \" slug: string;\",\n \" logo?: string | null;\",\n \" metadata?: Record<string, unknown> | null;\",\n \" createdAt: Date;\",\n \"};\",\n 'export type AuthOrganizationSummary = NonNullable<AuthOrganizationContext[\"organization\"]>;',\n 'export type AuthOrganizationMember = NonNullable<AuthOrganizationContext[\"member\"]>;',\n \"export type AuthApiKey = {\",\n \" id: string;\",\n \" name: string | null;\",\n \" prefix: string | null;\",\n \" start: string | null;\",\n \" expiresAt: Date | null;\",\n \" createdAt: Date;\",\n \" updatedAt: Date;\",\n \" metadata: unknown | null;\",\n \" permissions: Record<string, string[]> | null;\",\n \"};\",\n \"export type AuthInvitation = {\",\n \" id: string;\",\n \" organizationId: string;\",\n \" email: string;\",\n \" role: string | null;\",\n \" status: string;\",\n \" expiresAt: Date;\",\n \" inviterId: string;\",\n \"};\",\n \"export type GetActiveMemberInput = { organizationId?: string };\",\n \"export type GetOrganizationInput = { id: string };\",\n \"export type ListMembersInput = { organizationId: string };\",\n \"export type ListInvitationsInput = { organizationId: string };\",\n \"export type ListApiKeysInput = { organizationId?: string };\",\n \"export type createAuthInstance = never;\",\n \"export interface AuthServices {\",\n \" auth: Auth;\",\n \" db: unknown;\",\n \" driver: { close(): Promise<void> };\",\n \" handler: (req: Request) => Promise<Response>;\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileIfChanged(targetPath, content);\n}\n\nasync function resolveContractSource(opts: {\n configDir: string;\n runtimeDir: string;\n key: string;\n source: RuntimePluginConfig | { url: string; localPath?: string; name: string } | null;\n baseUrl: string;\n generatedSubdir: string;\n localSourceFactory?: (configDir: string) => ContractSource;\n}): Promise<ContractSource> {\n if (opts.key === \"api\") {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"BaseApiContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return localApiContractSource(opts.configDir);\n }\n }\n\n if (opts.key === \"auth\" && opts.localSourceFactory) {\n const localPath = opts.source && \"localPath\" in opts.source ? opts.source.localPath : undefined;\n if (localPath != null && localPath !== \"\") {\n return {\n key: opts.key,\n importName: \"authContract\",\n sourceFilePath: join(localPath, \"src\", \"contract.ts\"),\n };\n }\n\n if (!opts.baseUrl) {\n return opts.localSourceFactory(opts.configDir);\n }\n }\n\n if (\n opts.source &&\n \"localPath\" in opts.source &&\n opts.source.localPath != null &&\n opts.source.localPath !== \"\"\n ) {\n return {\n key: opts.key,\n importName: `${sanitizeIdentifier(opts.key)}Contract`,\n sourceFilePath: join(opts.source.localPath, \"src\", \"contract.ts\"),\n };\n }\n\n return remoteContractSource({\n configDir: opts.configDir,\n runtimeDir: opts.runtimeDir,\n name: opts.key,\n baseUrl: opts.baseUrl,\n generatedSubdir: opts.generatedSubdir,\n });\n}\n\nfunction writeGeneratedFiles(opts: {\n configDir: string;\n sources: ContractSource[];\n pluginKeys: string[];\n authSource: ContractSource | null;\n authExportPath?: string | null;\n}) {\n const baseSource = opts.sources.find((source) => source.key === \"api\");\n const pluginSources = opts.pluginKeys\n .map((key) => opts.sources.find((entry) => entry.key === key))\n .filter((source): source is ContractSource => Boolean(source));\n\n if (!baseSource) {\n throw new Error(\"API contract source is required to generate the aggregate contract\");\n }\n\n // --- Generate ui/src/lib/api-types.gen.ts ---\n const uiContractPath = join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n const uiLines: string[] = [];\n\n for (const source of opts.sources) {\n const importPath = toImportPath(uiContractPath, source.sourceFilePath);\n uiLines.push(`import type { ContractType as ${source.importName} } from \"${importPath}\";`);\n }\n\n uiLines.push(\"\");\n\n const compositeParts: string[] = [];\n if (opts.authSource) {\n compositeParts.push(`auth: ${opts.authSource.importName}`);\n }\n for (const source of pluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key) ? source.key : JSON.stringify(source.key);\n compositeParts.push(`${key}: ${source.importName}`);\n }\n\n if (compositeParts.length === 0) {\n uiLines.push(`export type ApiContract = ${baseSource.importName};`);\n } else {\n uiLines.push(`export type ApiContract = ${baseSource.importName} & {`);\n for (const part of compositeParts) {\n uiLines.push(` ${part};`);\n }\n uiLines.push(\"};\");\n }\n mkdirSync(dirname(uiContractPath), { recursive: true });\n writeFileIfChanged(uiContractPath, `${uiLines.join(\"\\n\")}\\n`);\n\n // --- Generate api/src/lib/plugins-types.gen.ts ---\n // Includes both plugin contracts AND auth as a unified PluginsClient type\n const pluginsClientPath = join(opts.configDir, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n const pluginsClientLines: string[] = [];\n\n for (const source of pluginSources) {\n const importPath = toImportPath(pluginsClientPath, source.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${source.importName} } from \"${importPath}\";`,\n );\n }\n\n if (opts.authSource) {\n const authImportPath = toImportPath(pluginsClientPath, opts.authSource.sourceFilePath);\n pluginsClientLines.push(\n `import type { ContractType as ${opts.authSource.importName} } from \"${authImportPath}\";`,\n );\n }\n\n pluginsClientLines.push(\n 'import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";',\n );\n pluginsClientLines.push(\n \"type ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\",\n );\n pluginsClientLines.push(\"\");\n\n const allPluginSources = [...pluginSources];\n if (opts.authSource) {\n allPluginSources.push({ ...opts.authSource, key: \"auth\" });\n }\n\n if (allPluginSources.length === 0) {\n pluginsClientLines.push(\"export type PluginsClient = Record<string, never>;\");\n } else {\n pluginsClientLines.push(\"export type PluginsClient = {\");\n for (const source of allPluginSources) {\n const key = /^[$A-Z_][0-9A-Z_$]*$/i.test(source.key)\n ? source.key\n : JSON.stringify(source.key);\n pluginsClientLines.push(` ${key}: ClientFactory<${source.importName}>;`);\n }\n pluginsClientLines.push(\"};\");\n }\n\n mkdirSync(dirname(pluginsClientPath), { recursive: true });\n writeFileIfChanged(pluginsClientPath, `${pluginsClientLines.join(\"\\n\")}\\n`);\n\n // --- Generate */src/lib/auth-types.gen.ts ---\n const authTypeTargets = [join(opts.configDir, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\")];\n const apiLibDir = join(opts.configDir, \"api\", \"src\", \"lib\");\n if (existsSync(apiLibDir)) {\n authTypeTargets.push(join(apiLibDir, \"auth-types.gen.ts\"));\n }\n const hostLibDir = join(opts.configDir, \"host\", \"src\", \"lib\");\n if (existsSync(join(opts.configDir, \"host\", \"src\"))) {\n authTypeTargets.push(join(hostLibDir, \"auth-types.gen.ts\"));\n }\n\n if (opts.authExportPath) {\n for (const authTypesPath of authTypeTargets) {\n writeAuthTypesGen(authTypesPath, opts.authExportPath);\n }\n } else if (opts.authSource) {\n for (const authTypesPath of authTypeTargets) {\n writeFallbackAuthTypesGen(authTypesPath);\n }\n }\n\n return uiContractPath;\n}\n\nexport async function syncApiContractBridge(opts: {\n configDir: string;\n runtimeConfig: RuntimeConfig;\n apiBaseUrl: string;\n}): Promise<{\n bridgePath: string;\n generatedPath: string | null;\n manifest: ApiPluginManifest | null;\n source: \"local\" | \"remote\";\n}> {\n const runtimeDir = join(opts.configDir, \".bos\", \"generated\");\n const pluginEntries = Object.entries(opts.runtimeConfig.plugins ?? {}).sort(([a], [b]) =>\n a.localeCompare(b),\n );\n const sources: ContractSource[] = [];\n let manifest: ApiPluginManifest | null = null;\n let generatedPath: string | null = null;\n let authSource: ContractSource | null = null;\n let authExportPath: string | null = null;\n\n const baseSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"api\",\n source: opts.runtimeConfig.api,\n baseUrl: opts.apiBaseUrl,\n generatedSubdir: \"api\",\n });\n sources.push(baseSource);\n\n if (opts.runtimeConfig.auth) {\n authSource = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key: \"auth\",\n source: opts.runtimeConfig.auth,\n baseUrl: opts.runtimeConfig.auth.url,\n generatedSubdir: \"auth\",\n localSourceFactory: localAuthContractSource,\n });\n sources.push(authSource);\n if (authSource.generatedPath) {\n generatedPath = authSource.generatedPath;\n }\n\n // Fetch auth additional exports (auth-export.d.ts) for remote auth\n if (opts.runtimeConfig.auth.url && opts.runtimeConfig.auth.source !== \"local\") {\n try {\n const authManifest = await fetchApiPluginManifest(opts.runtimeConfig.auth.url);\n const fetchedAuthExportPath = await fetchAuthExportTypes({\n baseUrl: opts.runtimeConfig.auth.url,\n runtimeDir,\n manifest: authManifest,\n });\n if (fetchedAuthExportPath) {\n authExportPath = fetchedAuthExportPath;\n }\n } catch (error) {\n console.warn(\n `[API Contract] Failed to fetch auth additional exports: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n if (!authExportPath) {\n const localAuthExport = join(opts.configDir, \"plugins\", \"auth\", \"src\", \"auth-export.ts\");\n if (existsSync(localAuthExport)) {\n authExportPath = localAuthExport;\n } else {\n const generatedAuthExport = join(runtimeDir, \"auth\", \"auth-export.d.ts\");\n if (existsSync(generatedAuthExport)) {\n authExportPath = generatedAuthExport;\n }\n }\n }\n }\n\n for (const [key, plugin] of pluginEntries) {\n if (!plugin.url && !plugin.localPath) {\n console.warn(\n `[API Contract] Skipping plugin \"${key}\" — no URL resolved (local path missing and no production URL configured)`,\n );\n continue;\n }\n const source = await resolveContractSource({\n configDir: opts.configDir,\n runtimeDir,\n key,\n source: plugin,\n baseUrl: plugin.url,\n generatedSubdir: `plugins/${key}`,\n });\n sources.push(source);\n if (source.generatedPath) {\n generatedPath = source.generatedPath;\n }\n }\n\n const allPluginKeys = pluginEntries.map(([key]) => key);\n\n writeGeneratedFiles({\n configDir: opts.configDir,\n sources,\n pluginKeys: allPluginKeys,\n authSource,\n authExportPath,\n });\n\n if (opts.runtimeConfig.api.source !== \"local\") {\n manifest = await fetchApiPluginManifest(opts.apiBaseUrl);\n }\n\n return {\n bridgePath: join(opts.configDir, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\"),\n generatedPath,\n manifest,\n source: opts.runtimeConfig.api.source,\n };\n}\n"],"mappings":";;;;;AAKA,MAAM,0BAA0B;AAmChC,SAAS,OAAO,OAAuB;AACrC,QAAO,WAAW,SAAS,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM;;AAGzD,SAAS,kBAAkB,OAAuB;AAChD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,mBAAmB,OAAuB;AACjD,QAAO,MAAM,QAAQ,kBAAkB,IAAI,CAAC,QAAQ,gBAAgB,IAAI;;AAG1E,SAAS,aAAa,UAAkB,YAA4B;CAClE,MAAM,MAAM,SAAS,QAAQ,SAAS,EAAE,WAAW,CAAC,QAAQ,OAAO,IAAI;AACvE,QAAO,IAAI,WAAW,IAAI,GAAG,MAAM,KAAK;;AAG1C,SAAS,mBAAmB,UAAkB,SAAiB;AAC7D,KAAI;AACF,MAAI,aAAa,UAAU,OAAO,KA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ACtD,oBAAmB,eAAe,QAAQ;AAE1C,QAAO;;AAGT,SAAS,kBAAkB,YAAoB,gBAAwB;CACrE,MAAM,mBAAmB,aAAa,YAAY,eAAe;CACjE,MAAM,UAAU;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,iBAAiB;EAC5B,mEAAmE,aAAa,YAAY,KAAK,QAAQ,eAAe,EAAE,gBAAgB,CAAC,CAAC;EAC5I,0CAA0C,iBAAiB;EAC3D;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;AACZ,WAAU,QAAQ,WAAW,EAAE,EAAE,WAAW,MAAM,CAAC;AACnD,oBAAmB,YAAY,QAAQ;;AAGzC,SAAS,0BAA0B,YAAoB;CACrD,MAAM,UAAU;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;AACZ,WAAU,QAAQ,WAAW,EAAE,EAAE,WAAW,MAAM,CAAC;AACnD,oBAAmB,YAAY,QAAQ;;AAGzC,eAAe,sBAAsB,MAQT;AAC1B,KAAI,KAAK,QAAQ,OAAO;EACtB,MAAM,YAAY,KAAK,UAAU,eAAe,KAAK,SAAS,KAAK,OAAO,YAAY;AACtF,MAAI,aAAa,QAAQ,cAAc,GACrC,QAAO;GACL,KAAK,KAAK;GACV,YAAY;GACZ,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AO;AACpB,MAAI,OAAO,cACT,iBAAgB,OAAO;;CAI3B,MAAM,gBAAgB,cAAc,KAAK,CAAC,SAAS,IAAI;AAEvD,qBAAoB;EAClB,WAAW,KAAK;EAChB;EACA,YAAY;EACZ;EACA;EACD,CAAC;AAEF,KAAI,KAAK,cAAc,IAAI,WAAW,QACpC,YAAW,MAAM,uBAAuB,KAAK,WAAW;AAG1D,QAAO;EACL,YAAY,KAAK,KAAK,WAAW,MAAM,OAAO,OAAO,mBAAmB;EACxE;EACA;EACA,QAAQ,KAAK,cAAc,IAAI;EAChC"}
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.cjs","names":["bosContract","cliCommandMeta"],"sources":["../../src/cli/catalog.ts"],"sourcesContent":["import { bosContract } from \"../contract\";\nimport { type CliCommandMeta, cliCommandMeta } from \"../contract.meta\";\n\nexport type CommandDescriptor = {\n key: keyof typeof bosContract;\n commandPath: string[];\n summary: string;\n meta: CliCommandMeta;\n procedure: (typeof bosContract)[keyof typeof bosContract];\n};\n\nfunction splitCamelCase(value: string): string[] {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/\\s+/)\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => part.toLowerCase());\n}\n\nexport const commandCatalog: CommandDescriptor[] = (\n Object.entries(bosContract) as Array<\n [keyof typeof bosContract, (typeof bosContract)[keyof typeof bosContract]]\n >\n).map(([key, procedure]) => {\n const meta = cliCommandMeta[key as keyof typeof cliCommandMeta] ?? {\n summary: splitCamelCase(String(key)).join(\" \"),\n };\n return {\n key,\n commandPath: meta.commandPath ?? splitCamelCase(String(key)),\n summary: meta.summary,\n meta,\n procedure,\n };\n});\n\nexport function findCommandDescriptor(\n args: string[],\n): { descriptor: CommandDescriptor; consumed: number } | null {\n const sorted = [...commandCatalog].sort((a, b) => b.commandPath.length - a.commandPath.length);\n for (const descriptor of sorted) {\n const parts = args.slice(0, descriptor.commandPath.length).map((part) => part.toLowerCase());\n if (parts.join(\" \") === descriptor.commandPath.join(\" \")) {\n return { descriptor, consumed: descriptor.commandPath.length };\n }\n }\n return null;\n}\n"],"mappings":";;;;AAWA,SAAS,eAAe,OAAyB;AAC/C,QAAO,MACJ,QAAQ,sBAAsB,QAAQ,CACtC,MAAM,MAAM,CACZ,KAAK,SAAS,KAAK,MAAM,CAAC,CAC1B,OAAO,QAAQ,CACf,KAAK,SAAS,KAAK,aAAa,CAAC;;AAGtC,MAAa,iBACX,OAAO,QAAQA,6BAAY,CAG3B,KAAK,CAAC,KAAK,eAAe;CAC1B,MAAM,OAAOC,qCAAe,QAAuC,EACjE,SAAS,eAAe,OAAO,IAAI,CAAC,CAAC,KAAK,IAAI,EAC/C;AACD,QAAO;EACL;EACA,aAAa,KAAK,eAAe,eAAe,OAAO,IAAI,CAAC;EAC5D,SAAS,KAAK;EACd;EACA;EACD;EACD;AAEF,SAAgB,sBACd,MAC4D;CAC5D,MAAM,SAAS,CAAC,GAAG,eAAe,CAAC,MAAM,GAAG,MAAM,EAAE,YAAY,SAAS,EAAE,YAAY,OAAO;AAC9F,MAAK,MAAM,cAAc,OAEvB,KADc,KAAK,MAAM,GAAG,WAAW,YAAY,OAAO,CAAC,KAAK,SAAS,KAAK,aAAa,CAAC,CAClF,KAAK,IAAI,KAAK,WAAW,YAAY,KAAK,IAAI,CACtD,QAAO;EAAE;EAAY,UAAU,WAAW,YAAY;EAAQ;AAGlE,QAAO"}
1
+ {"version":3,"file":"catalog.cjs","names":["bosContract","cliCommandMeta"],"sources":["../../src/cli/catalog.ts"],"sourcesContent":["import { bosContract } from \"../contract\";\nimport { type CliCommandMeta, cliCommandMeta } from \"../contract.meta\";\n\nexport type CommandDescriptor = {\n key: keyof typeof bosContract;\n commandPath: string[];\n summary: string;\n meta: CliCommandMeta;\n procedure: (typeof bosContract)[keyof typeof bosContract];\n};\n\nfunction splitCamelCase(value: string): string[] {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/\\s+/)\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => part.toLowerCase());\n}\n\nexport const commandCatalog: CommandDescriptor[] = (\n Object.entries(bosContract) as Array<\n [keyof typeof bosContract, (typeof bosContract)[keyof typeof bosContract]]\n >\n).map(([key, procedure]) => {\n const meta = cliCommandMeta[key as keyof typeof cliCommandMeta] ?? {\n summary: splitCamelCase(String(key)).join(\" \"),\n };\n return {\n key,\n commandPath: meta.commandPath ?? splitCamelCase(String(key)),\n summary: meta.summary,\n meta,\n procedure,\n };\n});\n\nexport function findCommandDescriptor(\n args: string[],\n): { descriptor: CommandDescriptor; consumed: number } | null {\n const sorted = [...commandCatalog].sort((a, b) => b.commandPath.length - a.commandPath.length);\n for (const descriptor of sorted) {\n const parts = args.slice(0, descriptor.commandPath.length).map((part) => part.toLowerCase());\n if (parts.join(\" \") === descriptor.commandPath.join(\" \")) {\n return { descriptor, consumed: descriptor.commandPath.length };\n }\n }\n return null;\n}\n"],"mappings":";;;;AAWA,SAAS,eAAe,OAAyB;AAC/C,QAAO,MACJ,QAAQ,sBAAsB,QAAQ,CACtC,MAAM,MAAM,CACZ,KAAK,SAAS,KAAK,MAAM,CAAC,CAC1B,OAAO,QAAQ,CACf,KAAK,SAAS,KAAK,aAAa,CAAC;;AAGtC,MAAa,iBACX,OAAO,QAAQA,6BAAY,CAG3B,KAAK,CAAC,KAAK,eAAe;CAC1B,MAAM,OAAOC,qCAAe,QAAuC,EACjE,SAAS,eAAe,OAAO,IAAI,CAAC,CAAC,KAAK,IAAI,EAC/C;AACD,QAAO;EACL;EACA,aAAa,KAAK,eAAe,eAAe,OAAO,IAAI,CAAC;EAC5D,SAAS,KAAK;EACd;EACA;EACD;EACD;AAEF,SAAgB,sBACd,MAC4D;CAC5D,MAAM,SAAS,CAAC,GAAG,eAAe,CAAC,MAAM,GAAG,MAAM,EAAE,YAAY,SAAS,EAAE,YAAY,OAAO;AAC9F,MAAK,MAAM,cAAc,OAEvB,KADc,KAAK,MAAM,GAAG,WAAW,YAAY,OAAO,CAAC,KAAK,SAAS,KAAK,aAAa,CAClF,CAAC,KAAK,IAAI,KAAK,WAAW,YAAY,KAAK,IAAI,CACtD,QAAO;EAAE;EAAY,UAAU,WAAW,YAAY;EAAQ;AAGlE,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.mjs","names":[],"sources":["../../src/cli/catalog.ts"],"sourcesContent":["import { bosContract } from \"../contract\";\nimport { type CliCommandMeta, cliCommandMeta } from \"../contract.meta\";\n\nexport type CommandDescriptor = {\n key: keyof typeof bosContract;\n commandPath: string[];\n summary: string;\n meta: CliCommandMeta;\n procedure: (typeof bosContract)[keyof typeof bosContract];\n};\n\nfunction splitCamelCase(value: string): string[] {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/\\s+/)\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => part.toLowerCase());\n}\n\nexport const commandCatalog: CommandDescriptor[] = (\n Object.entries(bosContract) as Array<\n [keyof typeof bosContract, (typeof bosContract)[keyof typeof bosContract]]\n >\n).map(([key, procedure]) => {\n const meta = cliCommandMeta[key as keyof typeof cliCommandMeta] ?? {\n summary: splitCamelCase(String(key)).join(\" \"),\n };\n return {\n key,\n commandPath: meta.commandPath ?? splitCamelCase(String(key)),\n summary: meta.summary,\n meta,\n procedure,\n };\n});\n\nexport function findCommandDescriptor(\n args: string[],\n): { descriptor: CommandDescriptor; consumed: number } | null {\n const sorted = [...commandCatalog].sort((a, b) => b.commandPath.length - a.commandPath.length);\n for (const descriptor of sorted) {\n const parts = args.slice(0, descriptor.commandPath.length).map((part) => part.toLowerCase());\n if (parts.join(\" \") === descriptor.commandPath.join(\" \")) {\n return { descriptor, consumed: descriptor.commandPath.length };\n }\n }\n return null;\n}\n"],"mappings":";;;;AAWA,SAAS,eAAe,OAAyB;AAC/C,QAAO,MACJ,QAAQ,sBAAsB,QAAQ,CACtC,MAAM,MAAM,CACZ,KAAK,SAAS,KAAK,MAAM,CAAC,CAC1B,OAAO,QAAQ,CACf,KAAK,SAAS,KAAK,aAAa,CAAC;;AAGtC,MAAa,iBACX,OAAO,QAAQ,YAAY,CAG3B,KAAK,CAAC,KAAK,eAAe;CAC1B,MAAM,OAAO,eAAe,QAAuC,EACjE,SAAS,eAAe,OAAO,IAAI,CAAC,CAAC,KAAK,IAAI,EAC/C;AACD,QAAO;EACL;EACA,aAAa,KAAK,eAAe,eAAe,OAAO,IAAI,CAAC;EAC5D,SAAS,KAAK;EACd;EACA;EACD;EACD;AAEF,SAAgB,sBACd,MAC4D;CAC5D,MAAM,SAAS,CAAC,GAAG,eAAe,CAAC,MAAM,GAAG,MAAM,EAAE,YAAY,SAAS,EAAE,YAAY,OAAO;AAC9F,MAAK,MAAM,cAAc,OAEvB,KADc,KAAK,MAAM,GAAG,WAAW,YAAY,OAAO,CAAC,KAAK,SAAS,KAAK,aAAa,CAAC,CAClF,KAAK,IAAI,KAAK,WAAW,YAAY,KAAK,IAAI,CACtD,QAAO;EAAE;EAAY,UAAU,WAAW,YAAY;EAAQ;AAGlE,QAAO"}
1
+ {"version":3,"file":"catalog.mjs","names":[],"sources":["../../src/cli/catalog.ts"],"sourcesContent":["import { bosContract } from \"../contract\";\nimport { type CliCommandMeta, cliCommandMeta } from \"../contract.meta\";\n\nexport type CommandDescriptor = {\n key: keyof typeof bosContract;\n commandPath: string[];\n summary: string;\n meta: CliCommandMeta;\n procedure: (typeof bosContract)[keyof typeof bosContract];\n};\n\nfunction splitCamelCase(value: string): string[] {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/\\s+/)\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => part.toLowerCase());\n}\n\nexport const commandCatalog: CommandDescriptor[] = (\n Object.entries(bosContract) as Array<\n [keyof typeof bosContract, (typeof bosContract)[keyof typeof bosContract]]\n >\n).map(([key, procedure]) => {\n const meta = cliCommandMeta[key as keyof typeof cliCommandMeta] ?? {\n summary: splitCamelCase(String(key)).join(\" \"),\n };\n return {\n key,\n commandPath: meta.commandPath ?? splitCamelCase(String(key)),\n summary: meta.summary,\n meta,\n procedure,\n };\n});\n\nexport function findCommandDescriptor(\n args: string[],\n): { descriptor: CommandDescriptor; consumed: number } | null {\n const sorted = [...commandCatalog].sort((a, b) => b.commandPath.length - a.commandPath.length);\n for (const descriptor of sorted) {\n const parts = args.slice(0, descriptor.commandPath.length).map((part) => part.toLowerCase());\n if (parts.join(\" \") === descriptor.commandPath.join(\" \")) {\n return { descriptor, consumed: descriptor.commandPath.length };\n }\n }\n return null;\n}\n"],"mappings":";;;;AAWA,SAAS,eAAe,OAAyB;AAC/C,QAAO,MACJ,QAAQ,sBAAsB,QAAQ,CACtC,MAAM,MAAM,CACZ,KAAK,SAAS,KAAK,MAAM,CAAC,CAC1B,OAAO,QAAQ,CACf,KAAK,SAAS,KAAK,aAAa,CAAC;;AAGtC,MAAa,iBACX,OAAO,QAAQ,YAAY,CAG3B,KAAK,CAAC,KAAK,eAAe;CAC1B,MAAM,OAAO,eAAe,QAAuC,EACjE,SAAS,eAAe,OAAO,IAAI,CAAC,CAAC,KAAK,IAAI,EAC/C;AACD,QAAO;EACL;EACA,aAAa,KAAK,eAAe,eAAe,OAAO,IAAI,CAAC;EAC5D,SAAS,KAAK;EACd;EACA;EACD;EACD;AAEF,SAAgB,sBACd,MAC4D;CAC5D,MAAM,SAAS,CAAC,GAAG,eAAe,CAAC,MAAM,GAAG,MAAM,EAAE,YAAY,SAAS,EAAE,YAAY,OAAO;AAC9F,MAAK,MAAM,cAAc,OAEvB,KADc,KAAK,MAAM,GAAG,WAAW,YAAY,OAAO,CAAC,KAAK,SAAS,KAAK,aAAa,CAClF,CAAC,KAAK,IAAI,KAAK,WAAW,YAAY,KAAK,IAAI,CACtD,QAAO;EAAE;EAAY,UAAU,WAAW,YAAY;EAAQ;AAGlE,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"framework-version.cjs","names":[],"sources":["../../src/cli/framework-version.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nfunction stripVersionPrefix(version: string): string {\n return version.replace(/^[\\^~>=]+/, \"\");\n}\n\nexport function readRootCatalogVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n workspaces?: { catalog?: Record<string, string> };\n };\n const version = pkg.workspaces?.catalog?.[packageName];\n return version ? stripVersionPrefix(version) : undefined;\n}\n\nexport function readNodeModulesVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"node_modules\", packageName, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { version?: string };\n return pkg.version;\n}\n\nexport function readInstalledFrameworkVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const deps = (pkg.dependencies ?? {}) as Record<string, string>;\n const devDeps = (pkg.devDependencies ?? {}) as Record<string, string>;\n const version = deps[packageName] || devDeps[packageName];\n\n if (!version) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"catalog:\")) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"workspace:\") || version.startsWith(\"file:\")) {\n return readNodeModulesVersion(projectDir, packageName);\n }\n\n return stripVersionPrefix(version);\n}\n"],"mappings":";;;;;AAGA,SAAS,mBAAmB,SAAyB;AACnD,QAAO,QAAQ,QAAQ,aAAa,GAAG;;AAGzC,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,8BAAe,YAAY,eAAe;AAChD,KAAI,yBAAY,QAAQ,CAAE,QAAO;CAIjC,MAAM,UAHM,KAAK,gCAAmB,SAAS,QAAQ,CAAC,CAGlC,YAAY,UAAU;AAC1C,QAAO,UAAU,mBAAmB,QAAQ,GAAG;;AAGjD,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,8BAAe,YAAY,gBAAgB,aAAa,eAAe;AAC7E,KAAI,yBAAY,QAAQ,CAAE,QAAO;AAEjC,QADY,KAAK,gCAAmB,SAAS,QAAQ,CAAC,CAC3C;;AAGb,SAAgB,8BACd,YACA,aACoB;CACpB,MAAM,8BAAe,YAAY,eAAe;AAChD,KAAI,yBAAY,QAAQ,CAAE,QAAO;CACjC,MAAM,MAAM,KAAK,gCAAmB,SAAS,QAAQ,CAAC;CACtD,MAAM,OAAQ,IAAI,gBAAgB,EAAE;CACpC,MAAM,UAAW,IAAI,mBAAmB,EAAE;CAC1C,MAAM,UAAU,KAAK,gBAAgB,QAAQ;AAE7C,KAAI,CAAC,QACH,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,WAAW,CAChC,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,aAAa,IAAI,QAAQ,WAAW,QAAQ,CACjE,QAAO,uBAAuB,YAAY,YAAY;AAGxD,QAAO,mBAAmB,QAAQ"}
1
+ {"version":3,"file":"framework-version.cjs","names":[],"sources":["../../src/cli/framework-version.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nfunction stripVersionPrefix(version: string): string {\n return version.replace(/^[\\^~>=]+/, \"\");\n}\n\nexport function readRootCatalogVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n workspaces?: { catalog?: Record<string, string> };\n };\n const version = pkg.workspaces?.catalog?.[packageName];\n return version ? stripVersionPrefix(version) : undefined;\n}\n\nexport function readNodeModulesVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"node_modules\", packageName, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { version?: string };\n return pkg.version;\n}\n\nexport function readInstalledFrameworkVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const deps = (pkg.dependencies ?? {}) as Record<string, string>;\n const devDeps = (pkg.devDependencies ?? {}) as Record<string, string>;\n const version = deps[packageName] || devDeps[packageName];\n\n if (!version) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"catalog:\")) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"workspace:\") || version.startsWith(\"file:\")) {\n return readNodeModulesVersion(projectDir, packageName);\n }\n\n return stripVersionPrefix(version);\n}\n"],"mappings":";;;;;AAGA,SAAS,mBAAmB,SAAyB;AACnD,QAAO,QAAQ,QAAQ,aAAa,GAAG;;AAGzC,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,8BAAe,YAAY,eAAe;AAChD,KAAI,yBAAY,QAAQ,CAAE,QAAO;CAIjC,MAAM,UAHM,KAAK,gCAAmB,SAAS,QAAQ,CAGlC,CAAC,YAAY,UAAU;AAC1C,QAAO,UAAU,mBAAmB,QAAQ,GAAG;;AAGjD,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,8BAAe,YAAY,gBAAgB,aAAa,eAAe;AAC7E,KAAI,yBAAY,QAAQ,CAAE,QAAO;AAEjC,QADY,KAAK,gCAAmB,SAAS,QAAQ,CAC3C,CAAC;;AAGb,SAAgB,8BACd,YACA,aACoB;CACpB,MAAM,8BAAe,YAAY,eAAe;AAChD,KAAI,yBAAY,QAAQ,CAAE,QAAO;CACjC,MAAM,MAAM,KAAK,gCAAmB,SAAS,QAAQ,CAAC;CACtD,MAAM,OAAQ,IAAI,gBAAgB,EAAE;CACpC,MAAM,UAAW,IAAI,mBAAmB,EAAE;CAC1C,MAAM,UAAU,KAAK,gBAAgB,QAAQ;AAE7C,KAAI,CAAC,QACH,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,WAAW,CAChC,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,aAAa,IAAI,QAAQ,WAAW,QAAQ,CACjE,QAAO,uBAAuB,YAAY,YAAY;AAGxD,QAAO,mBAAmB,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"framework-version.mjs","names":[],"sources":["../../src/cli/framework-version.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nfunction stripVersionPrefix(version: string): string {\n return version.replace(/^[\\^~>=]+/, \"\");\n}\n\nexport function readRootCatalogVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n workspaces?: { catalog?: Record<string, string> };\n };\n const version = pkg.workspaces?.catalog?.[packageName];\n return version ? stripVersionPrefix(version) : undefined;\n}\n\nexport function readNodeModulesVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"node_modules\", packageName, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { version?: string };\n return pkg.version;\n}\n\nexport function readInstalledFrameworkVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const deps = (pkg.dependencies ?? {}) as Record<string, string>;\n const devDeps = (pkg.devDependencies ?? {}) as Record<string, string>;\n const version = deps[packageName] || devDeps[packageName];\n\n if (!version) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"catalog:\")) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"workspace:\") || version.startsWith(\"file:\")) {\n return readNodeModulesVersion(projectDir, packageName);\n }\n\n return stripVersionPrefix(version);\n}\n"],"mappings":";;;;AAGA,SAAS,mBAAmB,SAAyB;AACnD,QAAO,QAAQ,QAAQ,aAAa,GAAG;;AAGzC,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,UAAU,KAAK,YAAY,eAAe;AAChD,KAAI,CAAC,WAAW,QAAQ,CAAE,QAAO;CAIjC,MAAM,UAHM,KAAK,MAAM,aAAa,SAAS,QAAQ,CAAC,CAGlC,YAAY,UAAU;AAC1C,QAAO,UAAU,mBAAmB,QAAQ,GAAG;;AAGjD,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,UAAU,KAAK,YAAY,gBAAgB,aAAa,eAAe;AAC7E,KAAI,CAAC,WAAW,QAAQ,CAAE,QAAO;AAEjC,QADY,KAAK,MAAM,aAAa,SAAS,QAAQ,CAAC,CAC3C;;AAGb,SAAgB,8BACd,YACA,aACoB;CACpB,MAAM,UAAU,KAAK,YAAY,eAAe;AAChD,KAAI,CAAC,WAAW,QAAQ,CAAE,QAAO;CACjC,MAAM,MAAM,KAAK,MAAM,aAAa,SAAS,QAAQ,CAAC;CACtD,MAAM,OAAQ,IAAI,gBAAgB,EAAE;CACpC,MAAM,UAAW,IAAI,mBAAmB,EAAE;CAC1C,MAAM,UAAU,KAAK,gBAAgB,QAAQ;AAE7C,KAAI,CAAC,QACH,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,WAAW,CAChC,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,aAAa,IAAI,QAAQ,WAAW,QAAQ,CACjE,QAAO,uBAAuB,YAAY,YAAY;AAGxD,QAAO,mBAAmB,QAAQ"}
1
+ {"version":3,"file":"framework-version.mjs","names":[],"sources":["../../src/cli/framework-version.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nfunction stripVersionPrefix(version: string): string {\n return version.replace(/^[\\^~>=]+/, \"\");\n}\n\nexport function readRootCatalogVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n workspaces?: { catalog?: Record<string, string> };\n };\n const version = pkg.workspaces?.catalog?.[packageName];\n return version ? stripVersionPrefix(version) : undefined;\n}\n\nexport function readNodeModulesVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"node_modules\", packageName, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { version?: string };\n return pkg.version;\n}\n\nexport function readInstalledFrameworkVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const pkgPath = join(projectDir, \"package.json\");\n if (!existsSync(pkgPath)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const deps = (pkg.dependencies ?? {}) as Record<string, string>;\n const devDeps = (pkg.devDependencies ?? {}) as Record<string, string>;\n const version = deps[packageName] || devDeps[packageName];\n\n if (!version) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"catalog:\")) {\n return (\n readRootCatalogVersion(projectDir, packageName) ??\n readNodeModulesVersion(projectDir, packageName)\n );\n }\n\n if (version.startsWith(\"workspace:\") || version.startsWith(\"file:\")) {\n return readNodeModulesVersion(projectDir, packageName);\n }\n\n return stripVersionPrefix(version);\n}\n"],"mappings":";;;;AAGA,SAAS,mBAAmB,SAAyB;AACnD,QAAO,QAAQ,QAAQ,aAAa,GAAG;;AAGzC,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,UAAU,KAAK,YAAY,eAAe;AAChD,KAAI,CAAC,WAAW,QAAQ,CAAE,QAAO;CAIjC,MAAM,UAHM,KAAK,MAAM,aAAa,SAAS,QAAQ,CAGlC,CAAC,YAAY,UAAU;AAC1C,QAAO,UAAU,mBAAmB,QAAQ,GAAG;;AAGjD,SAAgB,uBACd,YACA,aACoB;CACpB,MAAM,UAAU,KAAK,YAAY,gBAAgB,aAAa,eAAe;AAC7E,KAAI,CAAC,WAAW,QAAQ,CAAE,QAAO;AAEjC,QADY,KAAK,MAAM,aAAa,SAAS,QAAQ,CAC3C,CAAC;;AAGb,SAAgB,8BACd,YACA,aACoB;CACpB,MAAM,UAAU,KAAK,YAAY,eAAe;AAChD,KAAI,CAAC,WAAW,QAAQ,CAAE,QAAO;CACjC,MAAM,MAAM,KAAK,MAAM,aAAa,SAAS,QAAQ,CAAC;CACtD,MAAM,OAAQ,IAAI,gBAAgB,EAAE;CACpC,MAAM,UAAW,IAAI,mBAAmB,EAAE;CAC1C,MAAM,UAAU,KAAK,gBAAgB,QAAQ;AAE7C,KAAI,CAAC,QACH,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,WAAW,CAChC,QACE,uBAAuB,YAAY,YAAY,IAC/C,uBAAuB,YAAY,YAAY;AAInD,KAAI,QAAQ,WAAW,aAAa,IAAI,QAAQ,WAAW,QAAQ,CACjE,QAAO,uBAAuB,YAAY,YAAY;AAGxD,QAAO,mBAAmB,QAAQ"}
@@ -1,9 +1,9 @@
1
1
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
2
  let node_fs = require("node:fs");
3
3
  let node_path = require("node:path");
4
+ let node_crypto = require("node:crypto");
4
5
  let _clack_prompts = require("@clack/prompts");
5
6
  _clack_prompts = require_runtime.__toESM(_clack_prompts, 1);
6
- let node_crypto = require("node:crypto");
7
7
 
8
8
  //#region src/cli/infra.ts
9
9
  const POSTGRES_USER = "everythingdev";
@@ -1 +1 @@
1
- {"version":3,"file":"infra.cjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n port: number;\n serviceName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getRuntimeSecrets(runtimeConfig: RuntimeConfig): string[] {\n const pluginSecrets = Object.values(runtimeConfig.plugins ?? {}).flatMap(\n (plugin) => plugin.secrets ?? [],\n );\n\n return uniqueSecrets([\n API_DATABASE_SECRET,\n AUTH_DATABASE_SECRET,\n ...(runtimeConfig.api.secrets ?? []),\n ...(runtimeConfig.auth?.secrets ?? []),\n ...pluginSecrets,\n ]);\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildDatabaseConfigs(secrets: string[]): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n return {\n secret,\n slug,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n databaseName: `${slug}_db`,\n volumeName: `postgres_${slug}_data`,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n secrets: string[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const secret of secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[]): string {\n const lines = [\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n const secrets = getRuntimeSecrets(runtimeConfig);\n const databases = buildDatabaseConfigs(secrets);\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n writeFileSync(envExamplePath, renderEnvFile(secrets, databases, { forExample: true }));\n writeFileSync(dockerComposePath, renderDockerCompose(databases));\n\n return secrets;\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n write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,UAAU,kBAAkB,cAAc;CAChD,MAAM,YAAY,qBAAqB,QAAQ;CAC/C,MAAM,qCAAsB,WAAW,eAAe;CACtD,MAAM,wCAAyB,WAAW,qBAAqB;AAE/D,4BAAc,gBAAgB,cAAc,SAAS,WAAW,EAAE,YAAY,MAAM,CAAC,CAAC;AACtF,4BAAc,mBAAmB,oBAAoB,UAAU,CAAC;AAEhE,QAAO;;AAGT,SAAgB,cAAc,WAAyB;CACrD,MAAM,8BAAe,WAAW,OAAO;CACvC,MAAM,kCAAmB,WAAW,eAAe;AAEnD,6BAAe,QAAQ,IAAI,yBAAY,YAAY,CAAE;CAGrD,MAAM,kCADuB,aAAa,QAAQ,CAC5B,MAAM,KAAK;CACjC,MAAM,sCAAqB,GAAG,CAAC,SAAS,YAAY;AAUpD,4BAAc,SATE,MACb,KAAK,SAAS;AACb,MAAI,uBAAuB,KAAK,KAAK,CACnC,QAAO,sBAAsB;AAE/B,SAAO;GACP,CACD,KAAK,KAAK,CAEkB;AAC/B,gBAAE,IAAI,KAAK,6EAA6E"}
1
+ {"version":3,"file":"infra.cjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n port: number;\n serviceName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getRuntimeSecrets(runtimeConfig: RuntimeConfig): string[] {\n const pluginSecrets = Object.values(runtimeConfig.plugins ?? {}).flatMap(\n (plugin) => plugin.secrets ?? [],\n );\n\n return uniqueSecrets([\n API_DATABASE_SECRET,\n AUTH_DATABASE_SECRET,\n ...(runtimeConfig.api.secrets ?? []),\n ...(runtimeConfig.auth?.secrets ?? []),\n ...pluginSecrets,\n ]);\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildDatabaseConfigs(secrets: string[]): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n return {\n secret,\n slug,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n databaseName: `${slug}_db`,\n volumeName: `postgres_${slug}_data`,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n secrets: string[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const secret of secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[]): string {\n const lines = [\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n const secrets = getRuntimeSecrets(runtimeConfig);\n const databases = buildDatabaseConfigs(secrets);\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n writeFileSync(envExamplePath, renderEnvFile(secrets, databases, { forExample: true }));\n writeFileSync(dockerComposePath, renderDockerCompose(databases));\n\n return secrets;\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n writeFileSync(envPath, updated);\n p.log.info(\"Created .env from generated .env.example with generated BETTER_AUTH_SECRET\");\n}\n"],"mappings":";;;;;;;;AAMA,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAY3B,SAAS,cAAc,QAA6C;CAClE,MAAM,UAAoB,EAAE;CAC5B,MAAM,uBAAO,IAAI,KAAa;AAE9B,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,CAAC,SAAS,KAAK,IAAI,MAAM,CAAE;AAC/B,OAAK,IAAI,MAAM;AACf,UAAQ,KAAK,MAAM;;AAGrB,QAAO;;AAGT,SAAS,kBAAkB,eAAwC;CACjE,MAAM,gBAAgB,OAAO,OAAO,cAAc,WAAW,EAAE,CAAC,CAAC,SAC9D,WAAW,OAAO,WAAW,EAAE,CACjC;AAED,QAAO,cAAc;EACnB;EACA;EACA,GAAI,cAAc,IAAI,WAAW,EAAE;EACnC,GAAI,cAAc,MAAM,WAAW,EAAE;EACrC,GAAG;EACJ,CAAC;;AAGJ,SAAS,sBAAsB,QAAwB;AACrD,QAAO,OAAO,QAAQ,kBAAkB,GAAG,CAAC,aAAa;;AAG3D,SAAS,qBAAqB,SAA2C;AAWvE,QAAO;EAFiB;EAAqB;EAAsB,GAR3C,cACtB,QAAQ,QAAQ,WAAW,OAAO,SAAS,gBAAgB,CAAC,CAGrB,CACtC,QAAQ,WAAW,WAAW,uBAAuB,WAAW,qBAAqB,CACrF,MAAM,GAAG,MAAM,EAAE,c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K,eAAe;AAC1B,QAAM,KAAK,WAAW,SAAS,WAAW,2BAA2B;AACrE,QAAM,KAAK,GAAG;;AAGhB,OAAM,KAAK,WAAW;AACtB,MAAK,MAAM,YAAY,UACrB,OAAM,KAAK,KAAK,SAAS,WAAW,GAAG;AAGzC,QAAO,GAAG,MAAM,KAAK,KAAK,CAAC;;AAG7B,SAAgB,oBAAoB,WAAmB,eAAwC;CAC7F,MAAM,UAAU,kBAAkB,cAAc;CAChD,MAAM,YAAY,qBAAqB,QAAQ;CAC/C,MAAM,qCAAsB,WAAW,eAAe;CACtD,MAAM,wCAAyB,WAAW,qBAAqB;AAE/D,4BAAc,gBAAgB,cAAc,SAAS,WAAW,EAAE,YAAY,MAAM,CAAC,CAAC;AACtF,4BAAc,mBAAmB,oBAAoB,UAAU,CAAC;AAEhE,QAAO;;AAGT,SAAgB,cAAc,WAAyB;CACrD,MAAM,8BAAe,WAAW,OAAO;CACvC,MAAM,kCAAmB,WAAW,eAAe;AAEnD,6BAAe,QAAQ,IAAI,yBAAY,YAAY,CAAE;CAGrD,MAAM,kCADuB,aAAa,QACrB,CAAC,MAAM,KAAK;CACjC,MAAM,sCAAqB,GAAG,CAAC,SAAS,YAAY;AAUpD,4BAAc,SATE,MACb,KAAK,SAAS;AACb,MAAI,uBAAuB,KAAK,KAAK,CACnC,QAAO,sBAAsB;AAE/B,SAAO;GACP,CACD,KAAK,KAEsB,CAAC;AAC/B,gBAAE,IAAI,KAAK,6EAA6E"}
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import * as p from "@clack/prompts";
4
3
  import { randomBytes } from "node:crypto";
4
+ import * as p from "@clack/prompts";
5
5
 
6
6
  //#region src/cli/infra.ts
7
7
  const POSTGRES_USER = "everythingdev";
@@ -1 +1 @@
1
- {"version":3,"file":"infra.mjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n port: number;\n serviceName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getRuntimeSecrets(runtimeConfig: RuntimeConfig): string[] {\n const pluginSecrets = Object.values(runtimeConfig.plugins ?? {}).flatMap(\n (plugin) => plugin.secrets ?? [],\n );\n\n return uniqueSecrets([\n API_DATABASE_SECRET,\n AUTH_DATABASE_SECRET,\n ...(runtimeConfig.api.secrets ?? []),\n ...(runtimeConfig.auth?.secrets ?? []),\n ...pluginSecrets,\n ]);\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildDatabaseConfigs(secrets: string[]): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n return {\n secret,\n slug,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n databaseName: `${slug}_db`,\n volumeName: `postgres_${slug}_data`,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n secrets: string[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const secret of secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[]): string {\n const lines = [\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n const secrets = getRuntimeSecrets(runtimeConfig);\n const databases = buildDatabaseConfigs(secrets);\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n writeFileSync(envExamplePath, renderEnvFile(secrets, databases, { forExample: true }));\n writeFileSync(dockerComposePath, renderDockerCompose(databases));\n\n return secrets;\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n writeFileSync(envPath, updated);\n p.log.info(\"Created .env from generated .env.example with generated BETTER_AUTH_SECRET\");\n}\n"],"mappings":";;;;;;AAMA,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAY3B,SAAS,cAAc,QAA6C;CAClE,MAAM,UAAoB,EAAE;CAC5B,MAAM,uBAAO,IAAI,KAAa;AAE9B,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,CAAC,SAAS,KAAK,IAAI,MAAM,CAAE;AAC/B,OAAK,IAAI,MAAM;AACf,UAAQ,KAAK,MAAM;;AAGrB,QAAO;;AAGT,SAAS,kBAAkB,eAAwC;CACjE,MAAM,gBAAgB,OAAO,OAAO,cA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M,SAAS,YAAY,GAAG,CAAC,SAAS,YAAY;AAUpD,eAAc,SATE,MACb,KAAK,SAAS;AACb,MAAI,uBAAuB,KAAK,KAAK,CACnC,QAAO,sBAAsB;AAE/B,SAAO;GACP,CACD,KAAK,KAAK,CAEkB;AAC/B,GAAE,IAAI,KAAK,6EAA6E"}
1
+ {"version":3,"file":"infra.mjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n port: number;\n serviceName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getRuntimeSecrets(runtimeConfig: RuntimeConfig): string[] {\n const pluginSecrets = Object.values(runtimeConfig.plugins ?? {}).flatMap(\n (plugin) => plugin.secrets ?? [],\n );\n\n return uniqueSecrets([\n API_DATABASE_SECRET,\n AUTH_DATABASE_SECRET,\n ...(runtimeConfig.api.secrets ?? []),\n ...(runtimeConfig.auth?.secrets ?? []),\n ...pluginSecrets,\n ]);\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildDatabaseConfigs(secrets: string[]): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n return {\n secret,\n slug,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n databaseName: `${slug}_db`,\n volumeName: `postgres_${slug}_data`,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n secrets: string[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const secret of secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[]): string {\n const lines = [\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n const secrets = getRuntimeSecrets(runtimeConfig);\n const databases = buildDatabaseConfigs(secrets);\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n writeFileSync(envExamplePath, renderEnvFile(secrets, databases, { forExample: true }));\n writeFileSync(dockerComposePath, renderDockerCompose(databases));\n\n return secrets;\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n writeFileSync(envPath, updated);\n p.log.info(\"Created .env from generated .env.example with generated BETTER_AUTH_SECRET\");\n}\n"],"mappings":";;;;;;AAMA,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,qBA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