everything-dev 1.33.7 → 1.35.1
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.
- package/dist/api-contract.cjs +48 -68
- package/dist/api-contract.cjs.map +1 -1
- package/dist/api-contract.mjs +48 -68
- package/dist/api-contract.mjs.map +1 -1
- package/dist/cli/init.cjs +64 -41
- package/dist/cli/init.cjs.map +1 -1
- package/dist/cli/init.d.cts.map +1 -1
- package/dist/cli/init.d.mts.map +1 -1
- package/dist/cli/init.mjs +65 -42
- package/dist/cli/init.mjs.map +1 -1
- package/dist/cli/sync.cjs +5 -0
- package/dist/cli/sync.cjs.map +1 -1
- package/dist/cli/sync.mjs +5 -0
- package/dist/cli/sync.mjs.map +1 -1
- package/dist/cli/upgrade.cjs +6 -3
- package/dist/cli/upgrade.cjs.map +1 -1
- package/dist/cli/upgrade.mjs +6 -3
- package/dist/cli/upgrade.mjs.map +1 -1
- package/dist/config.cjs +12 -4
- package/dist/config.cjs.map +1 -1
- package/dist/config.d.cts.map +1 -1
- package/dist/config.d.mts.map +1 -1
- package/dist/config.mjs +12 -4
- package/dist/config.mjs.map +1 -1
- package/dist/contract.d.cts +60 -44
- package/dist/contract.d.cts.map +1 -1
- package/dist/contract.d.mts +60 -44
- package/dist/contract.d.mts.map +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/merge.cjs +1 -2
- package/dist/merge.cjs.map +1 -1
- package/dist/merge.d.cts +1 -1
- package/dist/merge.d.cts.map +1 -1
- package/dist/merge.d.mts +1 -1
- package/dist/merge.d.mts.map +1 -1
- package/dist/merge.mjs +1 -2
- package/dist/merge.mjs.map +1 -1
- package/dist/plugin.cjs +7 -3
- package/dist/plugin.cjs.map +1 -1
- package/dist/plugin.d.cts +71 -49
- package/dist/plugin.d.mts +71 -49
- package/dist/plugin.mjs +7 -3
- package/dist/plugin.mjs.map +1 -1
- package/dist/shared-deps.cjs +201 -0
- package/dist/shared-deps.cjs.map +1 -0
- package/dist/shared-deps.mjs +200 -0
- package/dist/shared-deps.mjs.map +1 -0
- package/dist/types.cjs +14 -12
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +88 -40
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +88 -40
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +14 -13
- package/dist/types.mjs.map +1 -1
- package/package.json +4 -4
- package/skills/extends-config/SKILL.md +7 -8
- package/skills/init-upgrade/SKILL.md +5 -2
- package/skills/publish-sync/SKILL.md +1 -1
- package/dist/shared.cjs +0 -155
- package/dist/shared.cjs.map +0 -1
- package/dist/shared.mjs +0 -154
- package/dist/shared.mjs.map +0 -1
|
@@ -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 hasLocalApiWorkspace = existsSync(join(opts.configDir, \"api\", \"src\"));\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 if (hasLocalApiWorkspace) {\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\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 interface ContractBridgeStatus {\n key: string;\n source: \"local\" | \"remote\" | \"skipped\" | \"failed\";\n url?: string;\n error?: string;\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 status: ContractBridgeStatus[];\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 const status: ContractBridgeStatus[] = [];\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 const excludedPluginKeys = new Set<string>();\n\n try {\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 status.push({\n key: \"api\",\n source: opts.runtimeConfig.api.source,\n url: opts.runtimeConfig.api.source !== \"local\" ? opts.apiBaseUrl : undefined,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[API Contract] Failed to resolve api contract: ${message}`);\n status.push({\n key: \"api\",\n source: \"failed\",\n url: opts.apiBaseUrl || undefined,\n error: message,\n });\n }\n\n if (opts.runtimeConfig.auth) {\n try {\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 status.push({\n key: \"auth\",\n source: opts.runtimeConfig.auth.source,\n url: opts.runtimeConfig.auth.source !== \"local\" ? opts.runtimeConfig.auth.url : undefined,\n });\n if (authSource.generatedPath) {\n generatedPath = authSource.generatedPath;\n }\n\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 } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[API Contract] Failed to resolve auth contract: ${message}`);\n status.push({\n key: \"auth\",\n source: \"failed\",\n url: opts.runtimeConfig.auth.url || undefined,\n error: message,\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 status.push({ key, source: \"skipped\" });\n excludedPluginKeys.add(key);\n continue;\n }\n try {\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 status.push({\n key,\n source: plugin.source,\n url: plugin.source !== \"local\" ? plugin.url : undefined,\n });\n if (source.generatedPath) {\n generatedPath = source.generatedPath;\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[API Contract] Failed to resolve plugin \"${key}\": ${message}`);\n status.push({ key, source: \"failed\", url: plugin.url || undefined, error: message });\n excludedPluginKeys.add(key);\n }\n }\n\n const apiStatus = status.find((s) => s.key === \"api\");\n if (apiStatus?.source === \"failed\") {\n throw new Error(\n `Cannot generate contract types without api contract: ${apiStatus.error ?? \"unknown error\"}`,\n );\n }\n\n const allPluginKeys = pluginEntries\n .filter(([key]) => !excludedPluginKeys.has(key))\n .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 status,\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,KAAK,QAAS,QAAO;SACjD;AAIR,eAAc,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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,gBAAgB,KAAK,WAAW,OAAO,cAAc;G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CAI/B,MAAM,YAAY,OAAO,MAAM,MAAM,EAAE,QAAQ,MAAM;AACrD,KAAI,WAAW,WAAW,SACxB,OAAM,IAAI,MACR,wDAAwD,UAAU,SAAS,kBAC5E;CAGH,MAAM,gBAAgB,cACnB,QAAQ,CAAC,SAAS,CAAC,mBAAmB,IAAI,IAAI,CAAC,CAC/C,KAAK,CAAC,SAAS,IAAI;AAEtB,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;EAC/B;EACD"}
|
|
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 \" organization?: { activeOrganizationId?: string | null } | null;\",\n \" apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\",\n \"};\",\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 writeContractBasedAuthTypesGen(targetPath: string, configDir: string) {\n const authExportRel = toImportPath(\n targetPath,\n join(configDir, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n );\n const contractRel = toImportPath(\n targetPath,\n join(configDir, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n );\n\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 \"${authExportRel}\";`,\n `import type { InferOutput, ContractType as AuthContract } from \"${contractRel}\";`,\n `import type { Auth as BaseAuth } from \"${authExportRel}\";`,\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 \" organization?: { activeOrganizationId?: string | null } | null;\",\n \" apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\",\n \"};\",\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\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 hasLocalApiWorkspace = existsSync(join(opts.configDir, \"api\", \"src\"));\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 if (hasLocalApiWorkspace) {\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\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 writeContractBasedAuthTypesGen(authTypesPath, opts.configDir);\n }\n }\n\n return uiContractPath;\n}\n\nexport interface ContractBridgeStatus {\n key: string;\n source: \"local\" | \"remote\" | \"skipped\" | \"failed\";\n url?: string;\n error?: string;\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 status: ContractBridgeStatus[];\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 const status: ContractBridgeStatus[] = [];\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 const excludedPluginKeys = new Set<string>();\n\n try {\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 status.push({\n key: \"api\",\n source: opts.runtimeConfig.api.source,\n url: opts.runtimeConfig.api.source !== \"local\" ? opts.apiBaseUrl : undefined,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[API Contract] Failed to resolve api contract: ${message}`);\n status.push({\n key: \"api\",\n source: \"failed\",\n url: opts.apiBaseUrl || undefined,\n error: message,\n });\n }\n\n if (opts.runtimeConfig.auth) {\n try {\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 status.push({\n key: \"auth\",\n source: opts.runtimeConfig.auth.source,\n url: opts.runtimeConfig.auth.source !== \"local\" ? opts.runtimeConfig.auth.url : undefined,\n });\n if (authSource.generatedPath) {\n generatedPath = authSource.generatedPath;\n }\n\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 } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[API Contract] Failed to resolve auth contract: ${message}`);\n status.push({\n key: \"auth\",\n source: \"failed\",\n url: opts.runtimeConfig.auth.url || undefined,\n error: message,\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 status.push({ key, source: \"skipped\" });\n excludedPluginKeys.add(key);\n continue;\n }\n try {\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 status.push({\n key,\n source: plugin.source,\n url: plugin.source !== \"local\" ? plugin.url : undefined,\n });\n if (source.generatedPath) {\n generatedPath = source.generatedPath;\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[API Contract] Failed to resolve plugin \"${key}\": ${message}`);\n status.push({ key, source: \"failed\", url: plugin.url || undefined, error: message });\n excludedPluginKeys.add(key);\n }\n }\n\n const apiStatus = status.find((s) => s.key === \"api\");\n if (apiStatus?.source === \"failed\") {\n throw new Error(\n `Cannot generate contract types without api contract: ${apiStatus.error ?? \"unknown error\"}`,\n );\n }\n\n const allPluginKeys = pluginEntries\n .filter(([key]) => !excludedPluginKeys.has(key))\n .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 status,\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,KAAK,QAAS,QAAO;SACjD;AAIR,eAAc,UAAU,QAAQ;AAChC,QAAO;;AAGT,SAAS,wBAAwB,YAA4B;AAC3D,QAAO,GAAG,kBAAkB,WAAW,CAAC;;AAG1C,eAAe,iBAAiB,KAAgC;CAC9D,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,UAAU,iBAAiB,WAAW,OAAO,EAAE,wBAAwB;AAE7E,KAAI;AACF,SAAO,MAAM,MAAM,KAAK,EAAE,QAAQ,WA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nB,QAAQ,CAAC,SAAS,CAAC,mBAAmB,IAAI,IAAI,CAAC,CAC/C,KAAK,CAAC,SAAS,IAAI;AAEtB,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;EAC/B;EACD"}
|
package/dist/cli/init.cjs
CHANGED
|
@@ -432,8 +432,7 @@ async function personalizeConfig(destination, opts) {
|
|
|
432
432
|
"account",
|
|
433
433
|
"domain",
|
|
434
434
|
"app",
|
|
435
|
-
"plugins"
|
|
436
|
-
"shared"
|
|
435
|
+
"plugins"
|
|
437
436
|
]);
|
|
438
437
|
const preservedRootKeys = new Set([
|
|
439
438
|
...managedRootKeys,
|
|
@@ -550,14 +549,37 @@ async function personalizeConfig(destination, opts) {
|
|
|
550
549
|
(0, node_fs.writeFileSync)(pluginsClientGenPath, `import type { ContractRouterClient, AnyContractRouter } from "@orpc/contract";\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\nexport type PluginsClient = Record<string, never>;\n`);
|
|
551
550
|
}
|
|
552
551
|
}
|
|
553
|
-
const authTypesContent = generateAuthTypesTemplate();
|
|
554
552
|
const authTypesPaths = [];
|
|
555
553
|
if (has("ui")) authTypesPaths.push((0, node_path.join)(destination, "ui", "src", "lib", "auth-types.gen.ts"));
|
|
556
554
|
if (has("api")) authTypesPaths.push((0, node_path.join)(destination, "api", "src", "lib", "auth-types.gen.ts"));
|
|
557
555
|
if (has("host") && (0, node_fs.existsSync)((0, node_path.join)(destination, "host", "src"))) authTypesPaths.push((0, node_path.join)(destination, "host", "src", "lib", "auth-types.gen.ts"));
|
|
558
556
|
for (const authTypesGenPath of authTypesPaths) if (!(0, node_fs.existsSync)(authTypesGenPath)) {
|
|
559
557
|
(0, node_fs.mkdirSync)((0, node_path.dirname)(authTypesGenPath), { recursive: true });
|
|
560
|
-
(0, node_fs.writeFileSync)(authTypesGenPath,
|
|
558
|
+
(0, node_fs.writeFileSync)(authTypesGenPath, generateAuthTypesContent(authTypesGenPath, destination));
|
|
559
|
+
}
|
|
560
|
+
if (authTypesPaths.length > 0) {
|
|
561
|
+
const authDir = (0, node_path.join)(destination, ".bos", "generated", "auth");
|
|
562
|
+
if (!(0, node_fs.existsSync)(authDir)) (0, node_fs.mkdirSync)(authDir, { recursive: true });
|
|
563
|
+
const authExportStubPath = (0, node_path.join)(authDir, "auth-export.d.ts");
|
|
564
|
+
if (!(0, node_fs.existsSync)(authExportStubPath)) (0, node_fs.writeFileSync)(authExportStubPath, `export type Auth = any;
|
|
565
|
+
export type AuthOrganizationContext = any;
|
|
566
|
+
export type AuthOrganization = any;
|
|
567
|
+
export type AuthOrganizationSummary = any;
|
|
568
|
+
export type AuthOrganizationMember = any;
|
|
569
|
+
export type AuthApiKey = any;
|
|
570
|
+
export type AuthInvitation = any;
|
|
571
|
+
export type GetActiveMemberInput = any;
|
|
572
|
+
export type GetOrganizationInput = any;
|
|
573
|
+
export type ListMembersInput = any;
|
|
574
|
+
export type ListInvitationsInput = any;
|
|
575
|
+
export type ListApiKeysInput = any;
|
|
576
|
+
export type AuthServices = any;
|
|
577
|
+
export type createAuthInstance = any;
|
|
578
|
+
`);
|
|
579
|
+
const contractStubPath = (0, node_path.join)(authDir, "contract.d.ts");
|
|
580
|
+
if (!(0, node_fs.existsSync)(contractStubPath)) (0, node_fs.writeFileSync)(contractStubPath, `export type ContractType = any;
|
|
581
|
+
export type InferOutput<_TRoute extends string> = any;
|
|
582
|
+
`);
|
|
561
583
|
}
|
|
562
584
|
if (has("plugins")) for (const plugin of opts.plugins ?? []) {
|
|
563
585
|
const pluginSrcDir = (0, node_path.join)(destination, "plugins", plugin, "src");
|
|
@@ -568,56 +590,57 @@ async function personalizeConfig(destination, opts) {
|
|
|
568
590
|
(0, node_fs.writeFileSync)(pluginClientGenPath, "export type PluginsClient = Record<string, never>;\n");
|
|
569
591
|
}
|
|
570
592
|
}
|
|
571
|
-
function
|
|
572
|
-
|
|
573
|
-
export type {
|
|
574
|
-
|
|
593
|
+
function generateAuthTypesContent(targetPath, configDir) {
|
|
594
|
+
const authExportRel = toRelativeImportPath((0, node_path.join)(configDir, ".bos", "generated", "auth", "auth-export.d.ts"), targetPath);
|
|
595
|
+
return `export type {
|
|
596
|
+
Auth,
|
|
597
|
+
AuthOrganizationContext,
|
|
598
|
+
AuthOrganization,
|
|
599
|
+
AuthOrganizationSummary,
|
|
600
|
+
AuthOrganizationMember,
|
|
601
|
+
AuthApiKey,
|
|
602
|
+
AuthInvitation,
|
|
603
|
+
GetActiveMemberInput,
|
|
604
|
+
GetOrganizationInput,
|
|
605
|
+
ListMembersInput,
|
|
606
|
+
ListInvitationsInput,
|
|
607
|
+
ListApiKeysInput,
|
|
608
|
+
AuthServices,
|
|
609
|
+
createAuthInstance,
|
|
610
|
+
} from "${authExportRel}";
|
|
611
|
+
import type { InferOutput, ContractType as AuthContract } from "${toRelativeImportPath((0, node_path.join)(configDir, ".bos", "generated", "auth", "contract.d.ts"), targetPath)}";
|
|
612
|
+
import type { Auth as BaseAuth } from "${authExportRel}";
|
|
613
|
+
|
|
614
|
+
type RawAuthSession = InferOutput<"getSession">;
|
|
615
|
+
type RawAuthRequestContext = InferOutput<"getContext">;
|
|
616
|
+
type RawAuthActiveMember = InferOutput<"getActiveMember">;
|
|
617
|
+
|
|
618
|
+
export type AuthSessionUser = NonNullable<RawAuthSession["user"]> & {
|
|
575
619
|
role?: string | null;
|
|
576
620
|
isAnonymous?: boolean | null;
|
|
577
621
|
walletAddress?: string | null;
|
|
578
622
|
banned?: boolean | null;
|
|
579
623
|
};
|
|
580
|
-
export type AuthSessionData = NonNullable<
|
|
624
|
+
export type AuthSessionData = NonNullable<RawAuthSession["session"]> & {
|
|
581
625
|
activeOrganizationId?: string | null;
|
|
582
626
|
};
|
|
583
627
|
export type AuthSession = {
|
|
584
628
|
user: AuthSessionUser | null;
|
|
585
629
|
session: AuthSessionData | null;
|
|
586
630
|
};
|
|
587
|
-
export
|
|
588
|
-
activeOrganizationId
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
export interface AuthRequestContext {
|
|
595
|
-
user: AuthSessionUser | null;
|
|
596
|
-
userId: string | null;
|
|
597
|
-
isAuthenticated: boolean;
|
|
598
|
-
authMethod: "session" | "apiKey" | "anonymous" | "none";
|
|
599
|
-
near: {
|
|
600
|
-
primaryAccountId: string | null;
|
|
601
|
-
linkedAccounts: Array<{ accountId: string; network: string; publicKey: string; isPrimary: boolean }>;
|
|
602
|
-
hasNearAccount: boolean;
|
|
603
|
-
};
|
|
604
|
-
organization: AuthOrganizationContext;
|
|
605
|
-
organizations?: Array<{ id: string; role: string; name?: string; slug?: string }>;
|
|
606
|
-
}
|
|
607
|
-
export type AuthActiveMember = { id: string | null; role: string | null; organizationId: string | null };
|
|
608
|
-
export type AuthOrganization = NonNullable<AuthOrganizationContext["organization"]>;
|
|
609
|
-
export type AuthOrganizationMember = NonNullable<AuthOrganizationContext["member"]>;
|
|
610
|
-
export type AuthOrganizationSummary = NonNullable<AuthRequestContext["organizations"]>[number];
|
|
611
|
-
export type AuthBaseSession = Auth["$Infer"]["Session"];
|
|
612
|
-
export type createAuthInstance = never;
|
|
613
|
-
export interface AuthServices {
|
|
614
|
-
auth: Auth;
|
|
615
|
-
db: unknown;
|
|
616
|
-
driver: { close(): Promise<void> };
|
|
617
|
-
handler: (req: Request) => Promise<Response>;
|
|
618
|
-
}
|
|
631
|
+
export type AuthRequestContext = RawAuthRequestContext & {
|
|
632
|
+
organization?: { activeOrganizationId?: string | null } | null;
|
|
633
|
+
apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;
|
|
634
|
+
};
|
|
635
|
+
export type AuthActiveMember = RawAuthActiveMember;
|
|
636
|
+
export type AuthBaseSession = BaseAuth["$Infer"]["Session"];
|
|
637
|
+
export type AuthContractType = AuthContract;
|
|
619
638
|
`;
|
|
620
639
|
}
|
|
640
|
+
function toRelativeImportPath(fromPath, toPath) {
|
|
641
|
+
const rel = (0, node_path.relative)((0, node_path.dirname)(toPath), fromPath);
|
|
642
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
643
|
+
}
|
|
621
644
|
async function runBunInstall(destination, spinner) {
|
|
622
645
|
await runWithProgress("bun", ["install", "--ignore-scripts"], destination, spinner, "Installing dependencies");
|
|
623
646
|
}
|
package/dist/cli/init.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.cjs","names":["require","resolveExtendsRef","fetchBosConfigFromFastKv","saveBosConfig","loadManifestNormalizationSpec","normalizePackageManifestsInTree","writeSnapshot"],"sources":["../../src/cli/init.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport type { OverrideSection } from \"../contract\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport {\n loadManifestNormalizationSpec,\n normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { BosConfig, BosConfigInput } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { writeSnapshot } from \"./snapshot\";\n\nconst require = createRequire(import.meta.url);\n\nexport const INIT_ROOT_PATTERNS = [\n \"bos.config.json\",\n \"package.json\",\n \".env.example\",\n \".gitignore\",\n \"biome.json\",\n \"bunfig.toml\",\n \"Dockerfile\",\n \"railway.json\",\n \"railway.toml\",\n \"AGENTS.md\",\n \".changeset/config.json\",\n \".changeset/README.md\",\n \"README.md\",\n \"CONTRIBUTING.md\",\n \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n ui: [\"ui\"],\n api: [\"api\"],\n host: [\"host\"],\n plugins: [],\n};\n\ninterface SourceResult {\n sourceDir: string;\n parentConfig: BosConfig;\n cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n catalog: Record<string, string>;\n repository?: string;\n extendsChain: string[];\n}\n\nfunction getExtendsRef(config: Record<string, unknown>): string | undefined {\n if (typeof config.extends === \"string\") {\n return config.extends;\n }\n\n if (config.extends && typeof config.extends === \"object\") {\n return resolveExtendsRef(config.extends as Record<string, string>, \"production\");\n }\n\n return undefined;\n}\n\nfunction parseBosRef(ref: string): { account: string; gateway: string } | null {\n const match = ref.match(/^bos:\\/\\/([^/]+)\\/(.+)$/);\n if (!match?.[1] || !match[2]) return null;\n return { account: match[1], gateway: match[2] };\n}\n\nfunction readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n const pkgPath = join(sourceDir, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n\n const pkg = readJsonFile<{ workspaces?: { catalog?: Record<string, string> } }>(pkgPath);\n return { ...(pkg.workspaces?.catalog ?? {}) };\n}\n\nexport async function resolveCatalogChainSource(opts: {\n extendsAccount: string;\n extendsGateway: string;\n sourceDir?: string;\n}): Promise<CatalogChainSource> {\n const catalogs: Record<string, string>[] = [];\n const cleanups: Array<() => Promise<void>> = [];\n const extendsChain: string[] = [];\n const visited = new Set<string>();\n let repository: string | undefined;\n let currentRef = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n let sourceDir = opts.sourceDir ? resolve(opts.sourceDir) : undefined;\n let configPath = sourceDir ? join(sourceDir, \"bos.config.json\") : undefined;\n\n try {\n while (true) {\n if (visited.has(currentRef)) {\n throw new Error(`Circular extends detected while resolving catalog source: ${currentRef}`);\n }\n\n visited.add(currentRef);\n extendsChain.push(currentRef);\n\n let config: Record<string, unknown>;\n let currentSourceDir = sourceDir;\n let cleanup: () => Promise<void> = async () => {};\n\n if (configPath) {\n config = readJsonFile<Record<string, unknown>>(configPath);\n currentSourceDir = dirname(configPath);\n } else {\n const parsed = parseBosRef(currentRef);\n if (!parsed) {\n break;\n }\n const sourceResult = await resolveSourceDir({\n extendsAccount: parsed.account,\n extendsGateway: parsed.gateway,\n });\n config = sourceResult.parentConfig as Record<string, unknown>;\n currentSourceDir = sourceResult.sourceDir || undefined;\n cleanup = sourceResult.cleanup;\n }\n\n cleanups.push(cleanup);\n catalogs.push(currentSourceDir ? readWorkspaceCatalog(currentSourceDir) : {});\n\n if (typeof config.repository === \"string\") {\n repository = config.repository;\n }\n\n const nextExtendsRef = getExtendsRef(config);\n if (!nextExtendsRef) {\n break;\n }\n\n if (nextExtendsRef.startsWith(\"bos://\")) {\n currentRef = nextExtendsRef;\n sourceDir = undefined;\n configPath = undefined;\n continue;\n }\n\n if (!currentSourceDir) {\n break;\n }\n\n const nextConfigPath = resolve(currentSourceDir, nextExtendsRef);\n if (!existsSync(nextConfigPath)) {\n break;\n }\n\n currentRef = nextConfigPath;\n sourceDir = dirname(nextConfigPath);\n configPath = nextConfigPath;\n }\n } finally {\n for (const cleanup of cleanups.reverse()) {\n await cleanup();\n }\n }\n\n return {\n catalog: Object.assign({}, ...catalogs.reverse()),\n repository,\n extendsChain,\n };\n}\n\nexport async function resolveSourceDir(opts: {\n extendsAccount: string;\n extendsGateway: string;\n source?: string;\n}): Promise<SourceResult> {\n if (opts.source) {\n const sourceDir = resolve(opts.source);\n if (!existsSync(join(sourceDir, \"bos.config.json\"))) {\n throw new Error(`No bos.config.json found in source directory: ${sourceDir}`);\n }\n const parentConfig = JSON.parse(\n readFileSync(join(sourceDir, \"bos.config.json\"), \"utf-8\"),\n ) as BosConfig;\n return { sourceDir, parentConfig, cleanup: async () => {} };\n }\n\n const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n if (parentConfig.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n return { sourceDir, parentConfig, cleanup };\n }\n\n const chainResult = await resolveRepositoryViaExtendsChain(\n opts.extendsAccount,\n opts.extendsGateway,\n );\n if (chainResult?.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n return { sourceDir, parentConfig: chainResult.config, cleanup };\n }\n\n return {\n sourceDir: \"\",\n parentConfig,\n cleanup: async () => {},\n };\n}\n\nexport function buildInitPatterns(overrides: OverrideSection[], plugins?: string[]): string[] {\n const has = (section: OverrideSection) => overrides.includes(section);\n const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n if (has(\"ui\")) patterns.push(\"ui/**\");\n if (has(\"api\")) patterns.push(\"api/**\");\n if (has(\"host\")) patterns.push(\"host/**\");\n if (has(\"plugins\")) {\n for (const plugin of plugins ?? []) {\n patterns.push(`plugins/${plugin}/**`);\n }\n }\n\n return patterns;\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n return filePath.startsWith(\".github/templates/\")\n ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n : filePath;\n}\n\nexport async function fetchParentConfig(\n extendsAccount: string,\n extendsGateway: string,\n): Promise<BosConfig> {\n const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n extendsAccount: string,\n extendsGateway: string,\n visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n const key = `bos://${extendsAccount}/${extendsGateway}`;\n if (visited.has(key)) return null;\n visited.add(key);\n\n try {\n const config = await fetchParentConfig(extendsAccount, extendsGateway);\n if (config.repository) {\n return { repository: config.repository, config };\n }\n\n const extendsRef = getExtendsRef(config as Record<string, unknown>);\n if (extendsRef) {\n const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n const parsed = parseBosRef(normalized);\n if (parsed) {\n const result = await resolveRepositoryViaExtendsChain(\n parsed.account,\n parsed.gateway,\n visited,\n );\n if (result) return result;\n }\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: directory,\n stdio: \"pipe\",\n });\n const url = stdout.trim();\n if (!url) return undefined;\n return normalizeGitUrl(url);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n }\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n }\n return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n const parsed = parseGitHubUrl(repoUrl);\n if (!parsed) {\n throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n }\n\n const { owner, repo } = parsed;\n let response: Response | null = null;\n\n for (const branch of [\"main\", \"master\"]) {\n const candidate = await fetch(\n `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n {\n headers: { \"User-Agent\": \"everything-dev\" },\n redirect: \"follow\",\n },\n );\n if (candidate.ok) {\n response = candidate;\n break;\n }\n if (candidate.status !== 404) {\n throw new Error(\n `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n );\n }\n }\n\n if (!response) {\n throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n }\n\n if (!response.body) {\n throw new Error(\"GitHub tarball download returned empty body\");\n }\n\n const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n const fileStream = createWriteStream(tarballPath);\n const reader = response.body as unknown as NodeJS.ReadableStream;\n await pipeline(reader, fileStream);\n\n const extractDir = mkTmpDir(\"bos-init-extract-\");\n try {\n const tar = require(\"tar\") as {\n extract: (opts: { cwd: string; file: string; strip: number }) => Promise<void>;\n };\n await tar.extract({ cwd: extractDir, file: tarballPath, strip: 1 });\n } catch {\n await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n }\n\n rmSync(tmpDir, { recursive: true, force: true });\n\n return {\n dir: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return { owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return { owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n return null;\n}\n\nexport async function copyFilteredFiles(\n sourceDir: string,\n destination: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<number> {\n if (patterns.length === 0) {\n return 0;\n }\n\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n mkdirSync(destination, { recursive: true });\n\n let count = 0;\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n\n const destPath = sourcePathToDestinationPath(filePath);\n const dest = join(destination, destPath);\n mkdirSync(dirname(dest), { recursive: true });\n const content = readFileSync(src);\n writeFileSync(dest, content);\n count++;\n }\n\n return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n delete entry.production;\n delete entry.integrity;\n delete entry.ssr;\n delete entry.ssrIntegrity;\n}\n\nfunction buildRootTypecheckScript(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): string {\n const commands = [\"bun run types:gen\"];\n\n if (sections.ui) {\n commands.push(\"if [ -d ui ]; then bun run --cwd ui typecheck; fi\");\n }\n if (sections.api) {\n commands.push(\"if [ -d api ]; then bun run --cwd api typecheck; fi\");\n }\n if (sections.host) {\n commands.push(\"if [ -d host ]; then bun run --cwd host typecheck; fi\");\n }\n if (sections.plugins) {\n commands.push(\n 'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then bun run --cwd \"$dir\" typecheck; fi; done; fi',\n );\n }\n\n return commands.join(\" && \");\n}\n\nexport function buildChildRootScripts(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): Record<string, string> {\n const scripts: Record<string, string> = {\n dev: \"node_modules/.bin/bos dev --host remote\",\n \"dev:proxy\": \"node_modules/.bin/bos dev --proxy\",\n build: \"node_modules/.bin/bos build\",\n deploy: \"node_modules/.bin/bos build --deploy\",\n publish: \"node_modules/.bin/bos publish\",\n start: \"node_modules/.bin/bos start\",\n typecheck: buildRootTypecheckScript(sections),\n lint: \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n format: \"biome format --write .\",\n \"format:check\": \"biome format .\",\n changeset: \"changeset\",\n version: \"changeset version\",\n release: \"echo 'Packages versioned - app release handled by workflow'\",\n postinstall: \"node_modules/.bin/bos types gen || true\",\n \"types:gen\": \"node_modules/.bin/bos types gen\",\n bos: \"node_modules/.bin/bos\",\n };\n\n if (sections.api) {\n scripts[\"db:push\"] = \"bun run --cwd api drizzle-kit push\";\n scripts[\"db:studio\"] = \"bun run --cwd api drizzle-kit studio\";\n scripts[\"db:generate\"] = \"bun run --cwd api drizzle-kit generate\";\n scripts[\"db:migrate\"] = \"bun run --cwd api drizzle-kit migrate\";\n scripts[\"test:api\"] = \"cd api && bun run test tests/integration/ tests/unit/\";\n scripts[\"test:integration\"] = \"cd api && bun run test tests/integration/\";\n }\n\n if (sections.host) {\n scripts[\"test:e2e\"] = \"bun run --cwd host test:e2e\";\n }\n\n if (sections.api && sections.host) {\n scripts.test = \"bun run test:api && bun run test:e2e\";\n } else if (sections.api) {\n scripts.test = \"bun run test:api\";\n } else if (sections.host) {\n scripts.test = \"bun run test:e2e\";\n }\n\n if (sections.api || sections.host) {\n scripts[\"dev:postgres\"] = \"docker compose up -d --wait && bun run dev\";\n scripts[\"dev:postgres:down\"] = \"docker compose down\";\n scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n }\n\n if (sections.ui) {\n scripts[\"dev:ui\"] = \"node_modules/.bin/bos dev --ui local --api remote\";\n }\n if (sections.api) {\n scripts[\"dev:api\"] = \"node_modules/.bin/bos dev --ui remote --api local\";\n }\n\n return scripts;\n}\n\nexport async function personalizeConfig(\n destination: string,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n pluginRoutes?: Record<string, string[]>;\n workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n mode?: \"init\" | \"sync\";\n existingConfig?: Record<string, unknown>;\n repository?: string;\n title?: string;\n description?: string;\n testnet?: string;\n staging?: unknown;\n },\n): Promise<void> {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const existingApp =\n opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n ? (opts.existingConfig.app as Record<string, unknown>)\n : undefined;\n const preservedAuth = existingApp?.auth;\n\n const explicitRootKeys = new Set(\n Object.entries(opts)\n .filter(\n ([key, value]) =>\n value !== undefined &&\n ![\n \"extendsAccount\",\n \"extendsGateway\",\n \"plugins\",\n \"overrides\",\n \"pluginRoutes\",\n \"workspaceOpts\",\n \"mode\",\n \"existingConfig\",\n ].includes(key),\n )\n .map(([key]) => key),\n );\n\n const configPath = join(destination, \"bos.config.json\");\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n if (opts.account) {\n config.account = opts.account;\n }\n if (opts.domain) {\n config.domain = opts.domain;\n }\n if (opts.repository) {\n config.repository = opts.repository;\n } else {\n delete config.repository;\n }\n\n const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n for (const field of inheritableFields) {\n if (!(field in opts)) {\n delete config[field];\n }\n }\n\n if (config.app && typeof config.app === \"object\") {\n const app = config.app as Record<string, unknown>;\n\n for (const entryKey of Object.keys(app)) {\n if (\n !has(entryKey as OverrideSection) &&\n (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n ) {\n delete app[entryKey];\n continue;\n }\n if (entryKey === \"auth\") {\n delete app[entryKey];\n continue;\n }\n const entry = app[entryKey];\n if (entry && typeof entry === \"object\") {\n stripProductionFields(entry as Record<string, unknown>);\n }\n }\n\n if (preservedAuth !== undefined) {\n app.auth = preservedAuth;\n }\n\n if (Object.keys(app).length === 0) {\n delete config.app;\n }\n }\n\n if (has(\"plugins\")) {\n if (config.plugins && typeof config.plugins === \"object\") {\n const plugins = config.plugins as Record<string, unknown>;\n\n if (opts.plugins !== undefined) {\n for (const pluginKey of Object.keys(plugins)) {\n if (!opts.plugins.includes(pluginKey)) {\n delete plugins[pluginKey];\n }\n }\n }\n\n for (const pluginKey of Object.keys(plugins)) {\n const plugin = plugins[pluginKey];\n let pluginObj: Record<string, unknown>;\n\n if (typeof plugin === \"string\") {\n pluginObj = { extends: plugin };\n plugins[pluginKey] = pluginObj;\n } else if (plugin && typeof plugin === \"object\") {\n pluginObj = { ...(plugin as Record<string, unknown>) };\n plugins[pluginKey] = pluginObj;\n } else {\n continue;\n }\n\n stripProductionFields(pluginObj);\n }\n\n if (Object.keys(plugins).length === 0) {\n delete config.plugins;\n }\n }\n } else {\n delete config.plugins;\n }\n\n if (opts.mode === \"sync\" && opts.existingConfig) {\n const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\", \"shared\"]);\n const preservedRootKeys = new Set([\n ...managedRootKeys,\n ...Object.keys(opts.existingConfig),\n ...explicitRootKeys,\n ]);\n\n for (const key of Object.keys(config)) {\n if (!preservedRootKeys.has(key)) {\n delete config[key];\n }\n }\n\n for (const [key, value] of Object.entries(opts.existingConfig)) {\n if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n config[key] = value;\n }\n }\n }\n\n await saveBosConfig(destination, config);\n }\n\n const pkgPath = join(destination, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const childScripts = buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n });\n\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n pkg.name = \"monorepo\";\n }\n pkg.private = true;\n pkg.type = \"module\";\n delete pkg.module;\n delete pkg.peerDependencies;\n\n if (pkg.workspaces && typeof pkg.workspaces === \"object\") {\n const ws = pkg.workspaces as { packages?: string[] };\n if (Array.isArray(ws.packages)) {\n ws.packages = ws.packages.filter((p: string) => {\n if (p.startsWith(\"packages/\")) return false;\n if (p === \"ui\") return has(\"ui\");\n if (p === \"api\") return has(\"api\");\n if (p === \"host\") return has(\"host\");\n if (p.startsWith(\"plugins/\")) return false;\n return true;\n });\n\n if (has(\"plugins\")) {\n if (!ws.packages.includes(\"plugins/*\")) {\n ws.packages.push(\"plugins/*\");\n }\n }\n }\n }\n\n if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n pkg.scripts = {};\n }\n const scripts = pkg.scripts as Record<string, string>;\n for (const [key, value] of Object.entries(childScripts)) {\n scripts[key] = value;\n }\n for (const obsoleteScript of [\n \"init\",\n \"sync-catalog\",\n \"db:push\",\n \"db:studio\",\n \"db:generate\",\n \"db:migrate\",\n \"test\",\n \"test:api\",\n \"test:integration\",\n \"test:e2e\",\n \"dev:postgres\",\n \"dev:postgres:down\",\n \"dev:postgres:reset\",\n \"dev:ui\",\n \"dev:api\",\n ]) {\n if (!(obsoleteScript in childScripts)) {\n delete scripts[obsoleteScript];\n }\n }\n\n if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n const deps = pkg.devDependencies as Record<string, string>;\n delete deps[\"every-plugin\"];\n delete deps[\"everything-dev\"];\n }\n\n if (!pkg.workspaces || typeof pkg.workspaces !== \"object\") {\n pkg.workspaces = { packages: [], catalog: {} };\n }\n const workspaces = pkg.workspaces as { packages?: string[]; catalog?: Record<string, string> };\n if (!workspaces.catalog || typeof workspaces.catalog !== \"object\") {\n workspaces.catalog = {};\n }\n\n if (!pkg.dependencies) pkg.dependencies = {};\n const deps = pkg.dependencies as Record<string, string>;\n const spec = opts.workspaceOpts?.sourceDir\n ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n : null;\n if (spec) {\n workspaces.catalog[\"everything-dev\"] = spec.rootCatalog[\"everything-dev\"];\n workspaces.catalog[\"every-plugin\"] = spec.rootCatalog[\"every-plugin\"];\n }\n const frameworkCatalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n sourceDir: opts.workspaceOpts?.sourceDir,\n })\n ).catalog;\n for (const [name, version] of Object.entries(frameworkCatalog)) {\n workspaces.catalog[name] = version;\n }\n if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n }\n\n const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n if (existsSync(apiTsConfigPath)) {\n const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n files?: string[];\n [key: string]: unknown;\n };\n if (apiTsConfig.files) {\n const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n if (validFiles.length !== apiTsConfig.files.length) {\n if (validFiles.length === 0) {\n delete apiTsConfig.files;\n } else {\n apiTsConfig.files = validFiles;\n }\n writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n }\n }\n }\n\n await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n if (has(\"ui\")) {\n const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n if (!existsSync(genContractPath)) {\n mkdirSync(dirname(genContractPath), { recursive: true });\n writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n }\n }\n\n if (has(\"api\")) {\n const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n if (!existsSync(pluginsClientGenPath)) {\n mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n writeFileSync(\n pluginsClientGenPath,\n `import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";\\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n );\n }\n }\n\n const authTypesContent = generateAuthTypesTemplate();\n const authTypesPaths: string[] = [];\n if (has(\"ui\")) {\n authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"api\")) {\n authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n for (const authTypesGenPath of authTypesPaths) {\n if (!existsSync(authTypesGenPath)) {\n mkdirSync(dirname(authTypesGenPath), { recursive: true });\n writeFileSync(authTypesGenPath, authTypesContent);\n }\n }\n\n if (has(\"plugins\")) {\n for (const plugin of opts.plugins ?? []) {\n const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n const pluginClientGenPath = join(pluginSrcDir, \"plugins-client.gen.ts\");\n if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n continue;\n }\n const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n if (!pluginIndex.includes(\"./plugins-client.gen\")) {\n continue;\n }\n writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n }\n }\n}\n\nfunction generateAuthTypesTemplate(): string {\n return `import type { Auth } from \"better-auth\";\nexport type { Auth } from \"better-auth\";\nexport type AuthSessionUser = NonNullable<Auth[\"$Infer\"][\"Session\"][\"user\"]> & {\n role?: string | null;\n isAnonymous?: boolean | null;\n walletAddress?: string | null;\n banned?: boolean | null;\n};\nexport type AuthSessionData = NonNullable<Auth[\"$Infer\"][\"Session\"][\"session\"]> & {\n activeOrganizationId?: string | null;\n};\nexport type AuthSession = {\n user: AuthSessionUser | null;\n session: AuthSessionData | null;\n};\nexport 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}\nexport 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}\nexport type AuthActiveMember = { id: string | null; role: string | null; organizationId: string | null };\nexport type AuthOrganization = NonNullable<AuthOrganizationContext[\"organization\"]>;\nexport type AuthOrganizationMember = NonNullable<AuthOrganizationContext[\"member\"]>;\nexport type AuthOrganizationSummary = NonNullable<AuthRequestContext[\"organizations\"]>[number];\nexport type AuthBaseSession = Auth[\"$Infer\"][\"Session\"];\nexport type createAuthInstance = never;\nexport interface AuthServices {\n auth: Auth;\n db: unknown;\n driver: { close(): Promise<void> };\n handler: (req: Request) => Promise<Response>;\n}\n`;\n}\n\nexport async function runBunInstall(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--ignore-scripts\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runBunInstallForUpgrade(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--force\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runTypesGen(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n const localBosBin = join(destination, \"node_modules\", \".bin\", \"bos\");\n if (existsSync(localBosBin)) {\n await runWithProgress(\n \"node_modules/.bin/bos\",\n [\"types\", \"gen\"],\n destination,\n spinner,\n \"Generating types\",\n );\n return;\n }\n\n throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport async function runDockerComposeUp(destination: string): Promise<void> {\n await execCommand(\"docker\", [\"compose\", \"up\", \"-d\", \"--wait\"], destination, { stdio: \"inherit\" });\n}\n\nasync function runWithProgress(\n command: string,\n args: string[],\n cwd: string,\n spinner: { message: (msg: string) => void } | undefined,\n label: string,\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n const child = execa(command, args, { cwd, stdio: \"inherit\", timeout });\n\n if (spinner) {\n const start = Date.now();\n const interval = setInterval(() => {\n const elapsed = Math.round((Date.now() - start) / 1000);\n spinner.message(`${label}... (${elapsed}s)`);\n }, 2000);\n try {\n await child;\n } finally {\n clearInterval(interval);\n }\n } else {\n await child;\n }\n}\n\nexport function stripOrphanedWorkspacesFromLockfile(\n lockfilePath: string,\n allowedWorkspaces: string[],\n): void {\n if (!existsSync(lockfilePath)) return;\n\n const content = readFileSync(lockfilePath, \"utf-8\");\n let lockfile: Record<string, unknown>;\n try {\n lockfile = JSON.parse(content) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const workspaces = lockfile.workspaces;\n if (!workspaces || typeof workspaces !== \"object\") return;\n\n const workspaceMap = workspaces as Record<string, unknown>;\n const allowed = new Set([\"\", ...allowedWorkspaces]);\n\n const keys = Object.keys(workspaceMap);\n let changed = false;\n for (const key of keys) {\n if (allowed.has(key)) continue;\n if (\n allowedWorkspaces.some(\n (pattern) => pattern.endsWith(\"/*\") && key.startsWith(pattern.slice(0, -1)),\n )\n )\n continue;\n delete workspaceMap[key];\n changed = true;\n }\n\n if (changed) {\n writeFileSync(lockfilePath, `${JSON.stringify(lockfile, null, 2)}\\n`);\n }\n}\n\nexport function removeInitLockfile(lockfilePath: string): void {\n if (!existsSync(lockfilePath)) return;\n rmSync(lockfilePath, { force: true });\n}\n\nfunction readJsonFile<T>(filePath: string): T {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n}\n\nexport async function scaffoldMinimalProject(\n destination: string,\n parentConfig: BosConfigInput,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n repository?: string;\n title?: string;\n description?: string;\n },\n): Promise<number> {\n mkdirSync(destination, { recursive: true });\n\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n const config: Record<string, unknown> = {\n extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n account: opts.account || opts.extendsAccount,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.repository ? { repository: opts.repository } : {}),\n ...(opts.title ? { title: opts.title } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n };\n\n if (parentConfig.app && typeof parentConfig.app === \"object\") {\n const app: Record<string, unknown> = {};\n const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n if (has(\"host\") && parentApp.host) {\n app.host = { ...parentApp.host };\n stripProductionFields(app.host as Record<string, unknown>);\n }\n\n if (has(\"ui\") && parentApp.ui) {\n app.ui = { ...parentApp.ui };\n stripProductionFields(app.ui as Record<string, unknown>);\n }\n\n if (has(\"api\") && parentApp.api) {\n app.api = { ...parentApp.api };\n stripProductionFields(app.api as Record<string, unknown>);\n }\n\n if (Object.keys(app).length > 0) {\n config.app = app;\n }\n }\n\n if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n const plugins: Record<string, unknown> = {};\n for (const key of opts.plugins) {\n const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n if (parentPlugin) {\n if (typeof parentPlugin === \"string\") {\n plugins[key] = { extends: parentPlugin };\n } else {\n const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n stripProductionFields(pluginCopy);\n plugins[key] = pluginCopy;\n }\n }\n }\n config.plugins = plugins;\n }\n\n await saveBosConfig(destination, config);\n\n const workspacePackages: string[] = [];\n for (const section of opts.overrides) {\n workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n }\n if (has(\"plugins\")) {\n workspacePackages.push(\"plugins/*\");\n }\n\n const catalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n })\n ).catalog;\n\n const pkg: Record<string, unknown> = {\n name: \"monorepo\",\n private: true,\n type: \"module\",\n scripts: buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n }),\n dependencies: {\n \"everything-dev\": \"catalog:\",\n \"every-plugin\": \"catalog:\",\n },\n devDependencies: {},\n workspaces: {\n packages: workspacePackages,\n catalog,\n },\n };\n writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n return 4;\n}\n\nasync function resolveWorkspaceRefs(\n destination: string,\n options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n await normalizePackageManifestsInTree({\n sourceRootDir: options?.sourceDir ?? destination,\n targetDir: destination,\n resolveCatalogRefs: false,\n preserveCatalogRefs: true,\n removeWorkspaceDeps: [\"host\"],\n });\n}\n\nexport async function writeInitSnapshot(\n destination: string,\n extendsAccount: string,\n extendsGateway: string,\n sourceDir: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n const fileHashes: Record<string, string> = {};\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n const content = readFileSync(src);\n const destPath = sourcePathToDestinationPath(filePath);\n fileHashes[destPath] = computeHash(content);\n }\n\n await writeSnapshot(destination, {\n parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n files: fileHashes,\n });\n}\n\nfunction computeHash(data: Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\").substring(0, 16);\n}\n\nfunction mkTmpDir(prefix: string): string {\n return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n cwd: destination,\n nodir: true,\n dot: false,\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n });\n\n for (const configPath of drizzleConfigs) {\n const workspaceDir = dirname(configPath);\n const pkgPath = join(destination, workspaceDir, \"package.json\");\n if (!existsSync(pkgPath)) continue;\n\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const scripts = pkg.scripts as Record<string, string> | undefined;\n if (!scripts?.[\"db:generate\"]) continue;\n\n const cwd = join(destination, workspaceDir);\n await execCommand(\"bun\", [\"run\", \"db:generate\"], cwd);\n }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n bun: 5 * 60_000,\n docker: 5 * 60_000,\n node_modules: 2 * 60_000,\n tar: 60_000,\n};\n\nexport async function execCommand(\n command: string,\n args: string[],\n cwd?: string,\n options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\nfunction generateGitignore(): string {\n return `node_modules/\ndist/\n.env\n.bos/\n*.gen.ts\n*.gen.tsx\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAMA,yFAAwC;AAE9C,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,yBAA4D;CAChE,IAAI,CAAC,KAAK;CACV,KAAK,CAAC,MAAM;CACZ,MAAM,CAAC,OAAO;CACd,SAAS,EAAE;CACZ;AAcD,SAAS,cAAc,QAAqD;AAC1E,KAAI,OAAO,OAAO,YAAY,SAC5B,QAAO,OAAO;AAGhB,KAAI,OAAO,WAAW,OAAO,OAAO,YAAY,SAC9C,QAAOC,gCAAkB,OAAO,SAAmC,aAAa;;AAMpF,SAAS,YAAY,KAA0D;CAC7E,MAAM,QAAQ,IAAI,MAAM,0BAA0B;AAClD,KAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,GAAI,QAAO;AACrC,QAAO;EAAE,SAAS,MAAM;EAAI,SAAS,MAAM;EAAI;;AAGjD,SAAS,q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ACA,MACA,KACA,SACe;CACf,MAAM,UAAU,iBAAiB,YAAY,IAAI;AACjD,wBAAY,SAAS,MAAM;EAAE;EAAK,OAAO,SAAS,SAAS;EAAQ;EAAS,CAAC;;AAG/E,SAAS,oBAA4B;AACnC,QAAO"}
|
|
1
|
+
{"version":3,"file":"init.cjs","names":["require","resolveExtendsRef","fetchBosConfigFromFastKv","saveBosConfig","loadManifestNormalizationSpec","normalizePackageManifestsInTree","writeSnapshot"],"sources":["../../src/cli/init.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport type { OverrideSection } from \"../contract\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport {\n loadManifestNormalizationSpec,\n normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { BosConfig, BosConfigInput } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { writeSnapshot } from \"./snapshot\";\n\nconst require = createRequire(import.meta.url);\n\nexport const INIT_ROOT_PATTERNS = [\n \"bos.config.json\",\n \"package.json\",\n \".env.example\",\n \".gitignore\",\n \"biome.json\",\n \"bunfig.toml\",\n \"Dockerfile\",\n \"railway.json\",\n \"railway.toml\",\n \"AGENTS.md\",\n \".changeset/config.json\",\n \".changeset/README.md\",\n \"README.md\",\n \"CONTRIBUTING.md\",\n \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n ui: [\"ui\"],\n api: [\"api\"],\n host: [\"host\"],\n plugins: [],\n};\n\ninterface SourceResult {\n sourceDir: string;\n parentConfig: BosConfig;\n cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n catalog: Record<string, string>;\n repository?: string;\n extendsChain: string[];\n}\n\nfunction getExtendsRef(config: Record<string, unknown>): string | undefined {\n if (typeof config.extends === \"string\") {\n return config.extends;\n }\n\n if (config.extends && typeof config.extends === \"object\") {\n return resolveExtendsRef(config.extends as Record<string, string>, \"production\");\n }\n\n return undefined;\n}\n\nfunction parseBosRef(ref: string): { account: string; gateway: string } | null {\n const match = ref.match(/^bos:\\/\\/([^/]+)\\/(.+)$/);\n if (!match?.[1] || !match[2]) return null;\n return { account: match[1], gateway: match[2] };\n}\n\nfunction readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n const pkgPath = join(sourceDir, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n\n const pkg = readJsonFile<{ workspaces?: { catalog?: Record<string, string> } }>(pkgPath);\n return { ...(pkg.workspaces?.catalog ?? {}) };\n}\n\nexport async function resolveCatalogChainSource(opts: {\n extendsAccount: string;\n extendsGateway: string;\n sourceDir?: string;\n}): Promise<CatalogChainSource> {\n const catalogs: Record<string, string>[] = [];\n const cleanups: Array<() => Promise<void>> = [];\n const extendsChain: string[] = [];\n const visited = new Set<string>();\n let repository: string | undefined;\n let currentRef = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n let sourceDir = opts.sourceDir ? resolve(opts.sourceDir) : undefined;\n let configPath = sourceDir ? join(sourceDir, \"bos.config.json\") : undefined;\n\n try {\n while (true) {\n if (visited.has(currentRef)) {\n throw new Error(`Circular extends detected while resolving catalog source: ${currentRef}`);\n }\n\n visited.add(currentRef);\n extendsChain.push(currentRef);\n\n let config: Record<string, unknown>;\n let currentSourceDir = sourceDir;\n let cleanup: () => Promise<void> = async () => {};\n\n if (configPath) {\n config = readJsonFile<Record<string, unknown>>(configPath);\n currentSourceDir = dirname(configPath);\n } else {\n const parsed = parseBosRef(currentRef);\n if (!parsed) {\n break;\n }\n const sourceResult = await resolveSourceDir({\n extendsAccount: parsed.account,\n extendsGateway: parsed.gateway,\n });\n config = sourceResult.parentConfig as Record<string, unknown>;\n currentSourceDir = sourceResult.sourceDir || undefined;\n cleanup = sourceResult.cleanup;\n }\n\n cleanups.push(cleanup);\n catalogs.push(currentSourceDir ? readWorkspaceCatalog(currentSourceDir) : {});\n\n if (typeof config.repository === \"string\") {\n repository = config.repository;\n }\n\n const nextExtendsRef = getExtendsRef(config);\n if (!nextExtendsRef) {\n break;\n }\n\n if (nextExtendsRef.startsWith(\"bos://\")) {\n currentRef = nextExtendsRef;\n sourceDir = undefined;\n configPath = undefined;\n continue;\n }\n\n if (!currentSourceDir) {\n break;\n }\n\n const nextConfigPath = resolve(currentSourceDir, nextExtendsRef);\n if (!existsSync(nextConfigPath)) {\n break;\n }\n\n currentRef = nextConfigPath;\n sourceDir = dirname(nextConfigPath);\n configPath = nextConfigPath;\n }\n } finally {\n for (const cleanup of cleanups.reverse()) {\n await cleanup();\n }\n }\n\n return {\n catalog: Object.assign({}, ...catalogs.reverse()),\n repository,\n extendsChain,\n };\n}\n\nexport async function resolveSourceDir(opts: {\n extendsAccount: string;\n extendsGateway: string;\n source?: string;\n}): Promise<SourceResult> {\n if (opts.source) {\n const sourceDir = resolve(opts.source);\n if (!existsSync(join(sourceDir, \"bos.config.json\"))) {\n throw new Error(`No bos.config.json found in source directory: ${sourceDir}`);\n }\n const parentConfig = JSON.parse(\n readFileSync(join(sourceDir, \"bos.config.json\"), \"utf-8\"),\n ) as BosConfig;\n return { sourceDir, parentConfig, cleanup: async () => {} };\n }\n\n const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n if (parentConfig.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n return { sourceDir, parentConfig, cleanup };\n }\n\n const chainResult = await resolveRepositoryViaExtendsChain(\n opts.extendsAccount,\n opts.extendsGateway,\n );\n if (chainResult?.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n return { sourceDir, parentConfig: chainResult.config, cleanup };\n }\n\n return {\n sourceDir: \"\",\n parentConfig,\n cleanup: async () => {},\n };\n}\n\nexport function buildInitPatterns(overrides: OverrideSection[], plugins?: string[]): string[] {\n const has = (section: OverrideSection) => overrides.includes(section);\n const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n if (has(\"ui\")) patterns.push(\"ui/**\");\n if (has(\"api\")) patterns.push(\"api/**\");\n if (has(\"host\")) patterns.push(\"host/**\");\n if (has(\"plugins\")) {\n for (const plugin of plugins ?? []) {\n patterns.push(`plugins/${plugin}/**`);\n }\n }\n\n return patterns;\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n return filePath.startsWith(\".github/templates/\")\n ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n : filePath;\n}\n\nexport async function fetchParentConfig(\n extendsAccount: string,\n extendsGateway: string,\n): Promise<BosConfig> {\n const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n extendsAccount: string,\n extendsGateway: string,\n visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n const key = `bos://${extendsAccount}/${extendsGateway}`;\n if (visited.has(key)) return null;\n visited.add(key);\n\n try {\n const config = await fetchParentConfig(extendsAccount, extendsGateway);\n if (config.repository) {\n return { repository: config.repository, config };\n }\n\n const extendsRef = getExtendsRef(config as Record<string, unknown>);\n if (extendsRef) {\n const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n const parsed = parseBosRef(normalized);\n if (parsed) {\n const result = await resolveRepositoryViaExtendsChain(\n parsed.account,\n parsed.gateway,\n visited,\n );\n if (result) return result;\n }\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: directory,\n stdio: \"pipe\",\n });\n const url = stdout.trim();\n if (!url) return undefined;\n return normalizeGitUrl(url);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n }\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n }\n return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n const parsed = parseGitHubUrl(repoUrl);\n if (!parsed) {\n throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n }\n\n const { owner, repo } = parsed;\n let response: Response | null = null;\n\n for (const branch of [\"main\", \"master\"]) {\n const candidate = await fetch(\n `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n {\n headers: { \"User-Agent\": \"everything-dev\" },\n redirect: \"follow\",\n },\n );\n if (candidate.ok) {\n response = candidate;\n break;\n }\n if (candidate.status !== 404) {\n throw new Error(\n `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n );\n }\n }\n\n if (!response) {\n throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n }\n\n if (!response.body) {\n throw new Error(\"GitHub tarball download returned empty body\");\n }\n\n const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n const fileStream = createWriteStream(tarballPath);\n const reader = response.body as unknown as NodeJS.ReadableStream;\n await pipeline(reader, fileStream);\n\n const extractDir = mkTmpDir(\"bos-init-extract-\");\n try {\n const tar = require(\"tar\") as {\n extract: (opts: { cwd: string; file: string; strip: number }) => Promise<void>;\n };\n await tar.extract({ cwd: extractDir, file: tarballPath, strip: 1 });\n } catch {\n await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n }\n\n rmSync(tmpDir, { recursive: true, force: true });\n\n return {\n dir: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return { owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return { owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n return null;\n}\n\nexport async function copyFilteredFiles(\n sourceDir: string,\n destination: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<number> {\n if (patterns.length === 0) {\n return 0;\n }\n\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n mkdirSync(destination, { recursive: true });\n\n let count = 0;\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n\n const destPath = sourcePathToDestinationPath(filePath);\n const dest = join(destination, destPath);\n mkdirSync(dirname(dest), { recursive: true });\n const content = readFileSync(src);\n writeFileSync(dest, content);\n count++;\n }\n\n return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n delete entry.production;\n delete entry.integrity;\n delete entry.ssr;\n delete entry.ssrIntegrity;\n}\n\nfunction buildRootTypecheckScript(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): string {\n const commands = [\"bun run types:gen\"];\n\n if (sections.ui) {\n commands.push(\"if [ -d ui ]; then bun run --cwd ui typecheck; fi\");\n }\n if (sections.api) {\n commands.push(\"if [ -d api ]; then bun run --cwd api typecheck; fi\");\n }\n if (sections.host) {\n commands.push(\"if [ -d host ]; then bun run --cwd host typecheck; fi\");\n }\n if (sections.plugins) {\n commands.push(\n 'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then bun run --cwd \"$dir\" typecheck; fi; done; fi',\n );\n }\n\n return commands.join(\" && \");\n}\n\nexport function buildChildRootScripts(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): Record<string, string> {\n const scripts: Record<string, string> = {\n dev: \"node_modules/.bin/bos dev --host remote\",\n \"dev:proxy\": \"node_modules/.bin/bos dev --proxy\",\n build: \"node_modules/.bin/bos build\",\n deploy: \"node_modules/.bin/bos build --deploy\",\n publish: \"node_modules/.bin/bos publish\",\n start: \"node_modules/.bin/bos start\",\n typecheck: buildRootTypecheckScript(sections),\n lint: \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n format: \"biome format --write .\",\n \"format:check\": \"biome format .\",\n changeset: \"changeset\",\n version: \"changeset version\",\n release: \"echo 'Packages versioned - app release handled by workflow'\",\n postinstall: \"node_modules/.bin/bos types gen || true\",\n \"types:gen\": \"node_modules/.bin/bos types gen\",\n bos: \"node_modules/.bin/bos\",\n };\n\n if (sections.api) {\n scripts[\"db:push\"] = \"bun run --cwd api drizzle-kit push\";\n scripts[\"db:studio\"] = \"bun run --cwd api drizzle-kit studio\";\n scripts[\"db:generate\"] = \"bun run --cwd api drizzle-kit generate\";\n scripts[\"db:migrate\"] = \"bun run --cwd api drizzle-kit migrate\";\n scripts[\"test:api\"] = \"cd api && bun run test tests/integration/ tests/unit/\";\n scripts[\"test:integration\"] = \"cd api && bun run test tests/integration/\";\n }\n\n if (sections.host) {\n scripts[\"test:e2e\"] = \"bun run --cwd host test:e2e\";\n }\n\n if (sections.api && sections.host) {\n scripts.test = \"bun run test:api && bun run test:e2e\";\n } else if (sections.api) {\n scripts.test = \"bun run test:api\";\n } else if (sections.host) {\n scripts.test = \"bun run test:e2e\";\n }\n\n if (sections.api || sections.host) {\n scripts[\"dev:postgres\"] = \"docker compose up -d --wait && bun run dev\";\n scripts[\"dev:postgres:down\"] = \"docker compose down\";\n scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n }\n\n if (sections.ui) {\n scripts[\"dev:ui\"] = \"node_modules/.bin/bos dev --ui local --api remote\";\n }\n if (sections.api) {\n scripts[\"dev:api\"] = \"node_modules/.bin/bos dev --ui remote --api local\";\n }\n\n return scripts;\n}\n\nexport async function personalizeConfig(\n destination: string,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n pluginRoutes?: Record<string, string[]>;\n workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n mode?: \"init\" | \"sync\";\n existingConfig?: Record<string, unknown>;\n repository?: string;\n title?: string;\n description?: string;\n testnet?: string;\n staging?: unknown;\n },\n): Promise<void> {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const existingApp =\n opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n ? (opts.existingConfig.app as Record<string, unknown>)\n : undefined;\n const preservedAuth = existingApp?.auth;\n\n const explicitRootKeys = new Set(\n Object.entries(opts)\n .filter(\n ([key, value]) =>\n value !== undefined &&\n ![\n \"extendsAccount\",\n \"extendsGateway\",\n \"plugins\",\n \"overrides\",\n \"pluginRoutes\",\n \"workspaceOpts\",\n \"mode\",\n \"existingConfig\",\n ].includes(key),\n )\n .map(([key]) => key),\n );\n\n const configPath = join(destination, \"bos.config.json\");\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n if (opts.account) {\n config.account = opts.account;\n }\n if (opts.domain) {\n config.domain = opts.domain;\n }\n if (opts.repository) {\n config.repository = opts.repository;\n } else {\n delete config.repository;\n }\n\n const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n for (const field of inheritableFields) {\n if (!(field in opts)) {\n delete config[field];\n }\n }\n\n if (config.app && typeof config.app === \"object\") {\n const app = config.app as Record<string, unknown>;\n\n for (const entryKey of Object.keys(app)) {\n if (\n !has(entryKey as OverrideSection) &&\n (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n ) {\n delete app[entryKey];\n continue;\n }\n if (entryKey === \"auth\") {\n delete app[entryKey];\n continue;\n }\n const entry = app[entryKey];\n if (entry && typeof entry === \"object\") {\n stripProductionFields(entry as Record<string, unknown>);\n }\n }\n\n if (preservedAuth !== undefined) {\n app.auth = preservedAuth;\n }\n\n if (Object.keys(app).length === 0) {\n delete config.app;\n }\n }\n\n if (has(\"plugins\")) {\n if (config.plugins && typeof config.plugins === \"object\") {\n const plugins = config.plugins as Record<string, unknown>;\n\n if (opts.plugins !== undefined) {\n for (const pluginKey of Object.keys(plugins)) {\n if (!opts.plugins.includes(pluginKey)) {\n delete plugins[pluginKey];\n }\n }\n }\n\n for (const pluginKey of Object.keys(plugins)) {\n const plugin = plugins[pluginKey];\n let pluginObj: Record<string, unknown>;\n\n if (typeof plugin === \"string\") {\n pluginObj = { extends: plugin };\n plugins[pluginKey] = pluginObj;\n } else if (plugin && typeof plugin === \"object\") {\n pluginObj = { ...(plugin as Record<string, unknown>) };\n plugins[pluginKey] = pluginObj;\n } else {\n continue;\n }\n\n stripProductionFields(pluginObj);\n }\n\n if (Object.keys(plugins).length === 0) {\n delete config.plugins;\n }\n }\n } else {\n delete config.plugins;\n }\n\n if (opts.mode === \"sync\" && opts.existingConfig) {\n const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\"]);\n const preservedRootKeys = new Set([\n ...managedRootKeys,\n ...Object.keys(opts.existingConfig),\n ...explicitRootKeys,\n ]);\n\n for (const key of Object.keys(config)) {\n if (!preservedRootKeys.has(key)) {\n delete config[key];\n }\n }\n\n for (const [key, value] of Object.entries(opts.existingConfig)) {\n if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n config[key] = value;\n }\n }\n }\n\n await saveBosConfig(destination, config);\n }\n\n const pkgPath = join(destination, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const childScripts = buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n });\n\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n pkg.name = \"monorepo\";\n }\n pkg.private = true;\n pkg.type = \"module\";\n delete pkg.module;\n delete pkg.peerDependencies;\n\n if (pkg.workspaces && typeof pkg.workspaces === \"object\") {\n const ws = pkg.workspaces as { packages?: string[] };\n if (Array.isArray(ws.packages)) {\n ws.packages = ws.packages.filter((p: string) => {\n if (p.startsWith(\"packages/\")) return false;\n if (p === \"ui\") return has(\"ui\");\n if (p === \"api\") return has(\"api\");\n if (p === \"host\") return has(\"host\");\n if (p.startsWith(\"plugins/\")) return false;\n return true;\n });\n\n if (has(\"plugins\")) {\n if (!ws.packages.includes(\"plugins/*\")) {\n ws.packages.push(\"plugins/*\");\n }\n }\n }\n }\n\n if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n pkg.scripts = {};\n }\n const scripts = pkg.scripts as Record<string, string>;\n for (const [key, value] of Object.entries(childScripts)) {\n scripts[key] = value;\n }\n for (const obsoleteScript of [\n \"init\",\n \"sync-catalog\",\n \"db:push\",\n \"db:studio\",\n \"db:generate\",\n \"db:migrate\",\n \"test\",\n \"test:api\",\n \"test:integration\",\n \"test:e2e\",\n \"dev:postgres\",\n \"dev:postgres:down\",\n \"dev:postgres:reset\",\n \"dev:ui\",\n \"dev:api\",\n ]) {\n if (!(obsoleteScript in childScripts)) {\n delete scripts[obsoleteScript];\n }\n }\n\n if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n const deps = pkg.devDependencies as Record<string, string>;\n delete deps[\"every-plugin\"];\n delete deps[\"everything-dev\"];\n }\n\n if (!pkg.workspaces || typeof pkg.workspaces !== \"object\") {\n pkg.workspaces = { packages: [], catalog: {} };\n }\n const workspaces = pkg.workspaces as { packages?: string[]; catalog?: Record<string, string> };\n if (!workspaces.catalog || typeof workspaces.catalog !== \"object\") {\n workspaces.catalog = {};\n }\n\n if (!pkg.dependencies) pkg.dependencies = {};\n const deps = pkg.dependencies as Record<string, string>;\n const spec = opts.workspaceOpts?.sourceDir\n ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n : null;\n if (spec) {\n workspaces.catalog[\"everything-dev\"] = spec.rootCatalog[\"everything-dev\"];\n workspaces.catalog[\"every-plugin\"] = spec.rootCatalog[\"every-plugin\"];\n }\n const frameworkCatalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n sourceDir: opts.workspaceOpts?.sourceDir,\n })\n ).catalog;\n for (const [name, version] of Object.entries(frameworkCatalog)) {\n workspaces.catalog[name] = version;\n }\n if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n }\n\n const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n if (existsSync(apiTsConfigPath)) {\n const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n files?: string[];\n [key: string]: unknown;\n };\n if (apiTsConfig.files) {\n const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n if (validFiles.length !== apiTsConfig.files.length) {\n if (validFiles.length === 0) {\n delete apiTsConfig.files;\n } else {\n apiTsConfig.files = validFiles;\n }\n writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n }\n }\n }\n\n await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n if (has(\"ui\")) {\n const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n if (!existsSync(genContractPath)) {\n mkdirSync(dirname(genContractPath), { recursive: true });\n writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n }\n }\n\n if (has(\"api\")) {\n const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n if (!existsSync(pluginsClientGenPath)) {\n mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n writeFileSync(\n pluginsClientGenPath,\n `import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";\\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n );\n }\n }\n\n const authTypesPaths: string[] = [];\n if (has(\"ui\")) {\n authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"api\")) {\n authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n for (const authTypesGenPath of authTypesPaths) {\n if (!existsSync(authTypesGenPath)) {\n mkdirSync(dirname(authTypesGenPath), { recursive: true });\n writeFileSync(authTypesGenPath, generateAuthTypesContent(authTypesGenPath, destination));\n }\n }\n\n if (authTypesPaths.length > 0) {\n const authDir = join(destination, \".bos\", \"generated\", \"auth\");\n if (!existsSync(authDir)) {\n mkdirSync(authDir, { recursive: true });\n }\n const authExportStubPath = join(authDir, \"auth-export.d.ts\");\n if (!existsSync(authExportStubPath)) {\n writeFileSync(\n authExportStubPath,\n `export type Auth = any;\nexport type AuthOrganizationContext = any;\nexport type AuthOrganization = any;\nexport type AuthOrganizationSummary = any;\nexport type AuthOrganizationMember = any;\nexport type AuthApiKey = any;\nexport type AuthInvitation = any;\nexport type GetActiveMemberInput = any;\nexport type GetOrganizationInput = any;\nexport type ListMembersInput = any;\nexport type ListInvitationsInput = any;\nexport type ListApiKeysInput = any;\nexport type AuthServices = any;\nexport type createAuthInstance = any;\n`,\n );\n }\n const contractStubPath = join(authDir, \"contract.d.ts\");\n if (!existsSync(contractStubPath)) {\n writeFileSync(\n contractStubPath,\n `export type ContractType = any;\nexport type InferOutput<_TRoute extends string> = any;\n`,\n );\n }\n }\n\n if (has(\"plugins\")) {\n for (const plugin of opts.plugins ?? []) {\n const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n const pluginClientGenPath = join(pluginSrcDir, \"plugins-client.gen.ts\");\n if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n continue;\n }\n const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n if (!pluginIndex.includes(\"./plugins-client.gen\")) {\n continue;\n }\n writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n }\n }\n}\n\nfunction generateAuthTypesContent(targetPath: string, configDir: string): string {\n const authExportRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n targetPath,\n );\n const contractRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n targetPath,\n );\n\n return `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 \"${authExportRel}\";\nimport type { InferOutput, ContractType as AuthContract } from \"${contractRel}\";\nimport type { Auth as BaseAuth } from \"${authExportRel}\";\n\ntype RawAuthSession = InferOutput<\"getSession\">;\ntype RawAuthRequestContext = InferOutput<\"getContext\">;\ntype RawAuthActiveMember = InferOutput<\"getActiveMember\">;\n\nexport type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {\n role?: string | null;\n isAnonymous?: boolean | null;\n walletAddress?: string | null;\n banned?: boolean | null;\n};\nexport type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {\n activeOrganizationId?: string | null;\n};\nexport type AuthSession = {\n user: AuthSessionUser | null;\n session: AuthSessionData | null;\n};\nexport type AuthRequestContext = RawAuthRequestContext & {\n organization?: { activeOrganizationId?: string | null } | null;\n apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\n};\nexport type AuthActiveMember = RawAuthActiveMember;\nexport type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];\nexport type AuthContractType = AuthContract;\n`;\n}\n\nfunction toRelativeImportPath(fromPath: string, toPath: string): string {\n const rel = relative(dirname(toPath), fromPath);\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport async function runBunInstall(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--ignore-scripts\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runBunInstallForUpgrade(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--force\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runTypesGen(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n const localBosBin = join(destination, \"node_modules\", \".bin\", \"bos\");\n if (existsSync(localBosBin)) {\n await runWithProgress(\n \"node_modules/.bin/bos\",\n [\"types\", \"gen\"],\n destination,\n spinner,\n \"Generating types\",\n );\n return;\n }\n\n throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport async function runDockerComposeUp(destination: string): Promise<void> {\n await execCommand(\"docker\", [\"compose\", \"up\", \"-d\", \"--wait\"], destination, { stdio: \"inherit\" });\n}\n\nasync function runWithProgress(\n command: string,\n args: string[],\n cwd: string,\n spinner: { message: (msg: string) => void } | undefined,\n label: string,\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n const child = execa(command, args, { cwd, stdio: \"inherit\", timeout });\n\n if (spinner) {\n const start = Date.now();\n const interval = setInterval(() => {\n const elapsed = Math.round((Date.now() - start) / 1000);\n spinner.message(`${label}... (${elapsed}s)`);\n }, 2000);\n try {\n await child;\n } finally {\n clearInterval(interval);\n }\n } else {\n await child;\n }\n}\n\nexport function stripOrphanedWorkspacesFromLockfile(\n lockfilePath: string,\n allowedWorkspaces: string[],\n): void {\n if (!existsSync(lockfilePath)) return;\n\n const content = readFileSync(lockfilePath, \"utf-8\");\n let lockfile: Record<string, unknown>;\n try {\n lockfile = JSON.parse(content) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const workspaces = lockfile.workspaces;\n if (!workspaces || typeof workspaces !== \"object\") return;\n\n const workspaceMap = workspaces as Record<string, unknown>;\n const allowed = new Set([\"\", ...allowedWorkspaces]);\n\n const keys = Object.keys(workspaceMap);\n let changed = false;\n for (const key of keys) {\n if (allowed.has(key)) continue;\n if (\n allowedWorkspaces.some(\n (pattern) => pattern.endsWith(\"/*\") && key.startsWith(pattern.slice(0, -1)),\n )\n )\n continue;\n delete workspaceMap[key];\n changed = true;\n }\n\n if (changed) {\n writeFileSync(lockfilePath, `${JSON.stringify(lockfile, null, 2)}\\n`);\n }\n}\n\nexport function removeInitLockfile(lockfilePath: string): void {\n if (!existsSync(lockfilePath)) return;\n rmSync(lockfilePath, { force: true });\n}\n\nfunction readJsonFile<T>(filePath: string): T {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n}\n\nexport async function scaffoldMinimalProject(\n destination: string,\n parentConfig: BosConfigInput,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n repository?: string;\n title?: string;\n description?: string;\n },\n): Promise<number> {\n mkdirSync(destination, { recursive: true });\n\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n const config: Record<string, unknown> = {\n extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n account: opts.account || opts.extendsAccount,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.repository ? { repository: opts.repository } : {}),\n ...(opts.title ? { title: opts.title } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n };\n\n if (parentConfig.app && typeof parentConfig.app === \"object\") {\n const app: Record<string, unknown> = {};\n const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n if (has(\"host\") && parentApp.host) {\n app.host = { ...parentApp.host };\n stripProductionFields(app.host as Record<string, unknown>);\n }\n\n if (has(\"ui\") && parentApp.ui) {\n app.ui = { ...parentApp.ui };\n stripProductionFields(app.ui as Record<string, unknown>);\n }\n\n if (has(\"api\") && parentApp.api) {\n app.api = { ...parentApp.api };\n stripProductionFields(app.api as Record<string, unknown>);\n }\n\n if (Object.keys(app).length > 0) {\n config.app = app;\n }\n }\n\n if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n const plugins: Record<string, unknown> = {};\n for (const key of opts.plugins) {\n const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n if (parentPlugin) {\n if (typeof parentPlugin === \"string\") {\n plugins[key] = { extends: parentPlugin };\n } else {\n const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n stripProductionFields(pluginCopy);\n plugins[key] = pluginCopy;\n }\n }\n }\n config.plugins = plugins;\n }\n\n await saveBosConfig(destination, config);\n\n const workspacePackages: string[] = [];\n for (const section of opts.overrides) {\n workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n }\n if (has(\"plugins\")) {\n workspacePackages.push(\"plugins/*\");\n }\n\n const catalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n })\n ).catalog;\n\n const pkg: Record<string, unknown> = {\n name: \"monorepo\",\n private: true,\n type: \"module\",\n scripts: buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n }),\n dependencies: {\n \"everything-dev\": \"catalog:\",\n \"every-plugin\": \"catalog:\",\n },\n devDependencies: {},\n workspaces: {\n packages: workspacePackages,\n catalog,\n },\n };\n writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n return 4;\n}\n\nasync function resolveWorkspaceRefs(\n destination: string,\n options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n await normalizePackageManifestsInTree({\n sourceRootDir: options?.sourceDir ?? destination,\n targetDir: destination,\n resolveCatalogRefs: false,\n preserveCatalogRefs: true,\n removeWorkspaceDeps: [\"host\"],\n });\n}\n\nexport async function writeInitSnapshot(\n destination: string,\n extendsAccount: string,\n extendsGateway: string,\n sourceDir: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n const fileHashes: Record<string, string> = {};\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n const content = readFileSync(src);\n const destPath = sourcePathToDestinationPath(filePath);\n fileHashes[destPath] = computeHash(content);\n }\n\n await writeSnapshot(destination, {\n parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n files: fileHashes,\n });\n}\n\nfunction computeHash(data: Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\").substring(0, 16);\n}\n\nfunction mkTmpDir(prefix: string): string {\n return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n cwd: destination,\n nodir: true,\n dot: false,\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n });\n\n for (const configPath of drizzleConfigs) {\n const workspaceDir = dirname(configPath);\n const pkgPath = join(destination, workspaceDir, \"package.json\");\n if (!existsSync(pkgPath)) continue;\n\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const scripts = pkg.scripts as Record<string, string> | undefined;\n if (!scripts?.[\"db:generate\"]) continue;\n\n const cwd = join(destination, workspaceDir);\n await execCommand(\"bun\", [\"run\", \"db:generate\"], cwd);\n }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n bun: 5 * 60_000,\n docker: 5 * 60_000,\n node_modules: 2 * 60_000,\n tar: 60_000,\n};\n\nexport async function execCommand(\n command: string,\n args: string[],\n cwd?: string,\n options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\nfunction generateGitignore(): string {\n return `node_modules/\ndist/\n.env\n.bos/\n*.gen.ts\n*.gen.tsx\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAMA,yFAAwC;AAE9C,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,yBAA4D;CAChE,IAAI,CAAC,KAAK;CACV,KAAK,CAAC,MAAM;CACZ,MAAM,CAAC,OAAO;CACd,SAAS,EAAE;CAC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