@ebay-dt/bonfire-node 0.2.0-alpha.0 → 0.2.0-alpha.11
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/README.md +18 -5
- package/dist/deployment-provider.d.ts +2 -1
- package/dist/deployment-provider.d.ts.map +1 -1
- package/dist/deployment-provider.js +2 -1
- package/dist/deployment-provider.js.map +1 -1
- package/dist/duplicate.d.ts.map +1 -1
- package/dist/duplicate.js +103 -47
- package/dist/duplicate.js.map +1 -1
- package/dist/git-repository.d.ts +16 -1
- package/dist/git-repository.d.ts.map +1 -1
- package/dist/git-repository.js +127 -1
- package/dist/git-repository.js.map +1 -1
- package/dist/github-cli.d.ts.map +1 -1
- package/dist/github-cli.js +3 -1
- package/dist/github-cli.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/internal/prototype-templates.d.ts +0 -1
- package/dist/internal/prototype-templates.d.ts.map +1 -1
- package/dist/internal/prototype-templates.js +0 -5
- package/dist/internal/prototype-templates.js.map +1 -1
- package/dist/lifecycle/deployment-worktree.d.ts +36 -0
- package/dist/lifecycle/deployment-worktree.d.ts.map +1 -0
- package/dist/lifecycle/deployment-worktree.js +503 -0
- package/dist/lifecycle/deployment-worktree.js.map +1 -0
- package/dist/lifecycle/local-prototype-lifecycle.d.ts +15 -1
- package/dist/lifecycle/local-prototype-lifecycle.d.ts.map +1 -1
- package/dist/lifecycle/local-prototype-lifecycle.js +738 -98
- package/dist/lifecycle/local-prototype-lifecycle.js.map +1 -1
- package/dist/lifecycle/preparation-marker.d.ts +12 -0
- package/dist/lifecycle/preparation-marker.d.ts.map +1 -0
- package/dist/lifecycle/preparation-marker.js +76 -0
- package/dist/lifecycle/preparation-marker.js.map +1 -0
- package/dist/lifecycle/prototype-path-policy.d.ts +18 -0
- package/dist/lifecycle/prototype-path-policy.d.ts.map +1 -0
- package/dist/lifecycle/prototype-path-policy.js +429 -0
- package/dist/lifecycle/prototype-path-policy.js.map +1 -0
- package/dist/lifecycle/repository-summary.d.ts +7 -1
- package/dist/lifecycle/repository-summary.d.ts.map +1 -1
- package/dist/lifecycle/repository-summary.js +20 -4
- package/dist/lifecycle/repository-summary.js.map +1 -1
- package/dist/lifecycle/repository-synchronization.d.ts +13 -8
- package/dist/lifecycle/repository-synchronization.d.ts.map +1 -1
- package/dist/lifecycle/repository-synchronization.js +680 -139
- package/dist/lifecycle/repository-synchronization.js.map +1 -1
- package/dist/lifecycle/runtime-context.d.ts +2 -0
- package/dist/lifecycle/runtime-context.d.ts.map +1 -1
- package/dist/lifecycle/runtime-context.js +5 -1
- package/dist/lifecycle/runtime-context.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-prototype-lifecycle.d.ts","sourceRoot":"","sources":["../../src/lifecycle/local-prototype-lifecycle.ts"],"names":[],"mappings":"AAIA,OAAO,EAcL,KAAK,sBAAsB,EAC3B,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EAEpB,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EAEvB,KAAK,OAAO,EAEZ,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,aAAa,EACnB,MAAM,uBAAuB,CAAC;AAS/B,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,yBAAyB,CAAC;AAMjC,OAAO,KAAK,EACV,qBAAqB,EAEtB,MAAM,+BAA+B,CAAC;AAUvC,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,2BAA2B,CAAC;AAOnC,KAAK,eAAe,CAAC,KAAK,EAAE,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Ae,CAAC,iBAAiB,CAAC,CAAC,CAe7C;IAEK,MAAM,CACV,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,qBAAqB,GAC3B,OAAO,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC,CAsF3C;IAEK,IAAI,CACR,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,qBAAqB,GAC3B,OAAO,CAAC,eAAe,CAAC,kBAAkB,CAAC,CAAC,CAyB9C;IAEK,OAAO,CACX,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,qBAAqB,GAC3B,OAAO,CAAC,eAAe,CAAC,qBAAqB,CAAC,CAAC,CAoBjD;IAEK,SAAS,CACb,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,uBAAuB,GAC7B,OAAO,CAAC,eAAe,CAAC,uBAAuB,CAAC,CAAC,CAuEnD;CACF","sourcesContent":["import { constants } from \"node:fs\";\nimport { lstat, open, rename, rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport { join, relative, sep } from \"node:path\";\nimport {\n definePrototypeRef,\n getPrototypeUrl,\n LifecycleInputError,\n lifecycleFailure,\n lifecycleSuccess,\n parseCreatePrototypeInput,\n parseDuplicatePrototypeInput,\n parseEditPrototypeInput,\n parseBonfireIdentity,\n parsePrototypeCommandInput,\n parsePrototypeMetadata,\n slugifyPrototypeTitle,\n PrototypeRefError,\n type BranchPreparationValue,\n type CreatePrototypeInput,\n type CreatePrototypeValue,\n type DeletePrototypeValue,\n type DeploymentValue,\n type DeploymentWarningCode,\n type DirtyObservationValue,\n type DiscardPrototypeValue,\n type DuplicatePrototypeInput,\n type DuplicatePrototypeValue,\n type EditPrototypeInput,\n type EditPrototypeValue,\n parseGitModeSetting,\n type GitMode,\n type LifecycleErrorCode,\n type LifecycleResult,\n type BonfireIdentity,\n type PrototypeCommandInput,\n type SavePrototypeValue,\n type RepositorySummary,\n type ThemeRegistry,\n} from \"@ebay-dt/bonfire-core\";\nimport {\n commitPath,\n discardPath,\n GitRepositoryError,\n pushBranch,\n type GitRepository,\n} from \"../git-repository.js\";\nimport { duplicatePrototype, PrototypeDuplicateError } from \"../duplicate.js\";\nimport {\n PrototypeCatalog,\n type PrototypeCatalogLike,\n} from \"../prototype-catalog.js\";\nimport { PrototypeScaffoldError, scaffoldPrototype } from \"../scaffold.js\";\nimport {\n createPrototypeLifecycleRuntime,\n type PrototypeLifecycleRuntimeContext,\n} from \"./runtime-context.js\";\nimport type {\n PreparePrototypeFiles,\n PreparePrototypeFilesRequest,\n} from \"../prepare-prototype-files.js\";\nimport {\n cleanupOwnedDestination,\n validateOwnedDestination,\n type OwnedDestinationReceipt,\n} from \"../internal/owned-destination.js\";\nimport {\n RepositoryBusyError,\n withRepositoryOperation,\n} from \"./operation-gate.js\";\nimport {\n DeploymentProviderError,\n type DeploymentProvider,\n} from \"../deployment-provider.js\";\nimport {\n assertIdentityBranchReady,\n synchronizeIdentityBranch,\n} from \"./repository-synchronization.js\";\nimport { getRepositorySummary } from \"./repository-summary.js\";\n\ntype LifecycleMethod<Input, Value> = (\n identity: BonfireIdentity,\n input: Input,\n) => Promise<LifecycleResult<Value>>;\n\nexport type PrototypeLifecycle = {\n /** Declares whether this lifecycle enforces the selected Git mode. */\n readonly gitMode?: GitMode;\n prepareBranch(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<BranchPreparationValue>>;\n create: LifecycleMethod<CreatePrototypeInput, CreatePrototypeValue>;\n duplicate: LifecycleMethod<DuplicatePrototypeInput, DuplicatePrototypeValue>;\n edit: LifecycleMethod<EditPrototypeInput, EditPrototypeValue>;\n delete: LifecycleMethod<PrototypeCommandInput, DeletePrototypeValue>;\n getDirtyState: LifecycleMethod<PrototypeCommandInput, DirtyObservationValue>;\n getRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>>;\n checkRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>>;\n save: LifecycleMethod<PrototypeCommandInput, SavePrototypeValue>;\n discard: LifecycleMethod<PrototypeCommandInput, DiscardPrototypeValue>;\n deploy: LifecycleMethod<PrototypeCommandInput, DeploymentValue>;\n};\n\nexport type LocalPrototypeLifecycleOptions = {\n repositoryRoot: string;\n prototypeRoot?: string;\n remote?: string;\n primaryBranch?: string;\n automaticBranchSwitch?: \"enabled\" | \"disabled\";\n gitMode?: GitMode;\n commitIdentity?: {\n name: string;\n email: string;\n };\n catalog?: PrototypeCatalogLike;\n preparePrototypeFiles?: PreparePrototypeFiles;\n deploymentProvider?: DeploymentProvider;\n applicationId?: string;\n themeRegistry?: ThemeRegistry;\n};\n\ntype InternalLocalPrototypeLifecycleOptions = LocalPrototypeLifecycleOptions & {\n runtime?: PrototypeLifecycleRuntimeContext;\n};\n\nfunction repositoryRelativePath(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n) {\n const absolutePath = join(runtime.prototypeRoot, ref.login, ref.slug);\n return relative(runtime.repositoryRoot, absolutePath).split(sep).join(\"/\");\n}\n\nfunction destinationRef(identity: BonfireIdentity, title: string) {\n const slug = slugifyPrototypeTitle(title);\n if (slug === null)\n throw new PrototypeRefError(\"title\", \"must produce a slug\");\n return definePrototypeRef({ login: identity.login, slug });\n}\n\nclass PrototypeNotFoundError extends Error {}\nclass PrototypeOwnershipError extends Error {}\nclass PrototypeMetadataFileError extends Error {}\nclass DeploymentUnavailableError extends Error {}\n\nfunction metadataPath(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n) {\n return join(runtime.prototypeRoot, ref.login, ref.slug, \"metadata.json\");\n}\n\nasync function assertPrototypeDirectory(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n) {\n const paths = [\n runtime.prototypeRoot,\n join(runtime.prototypeRoot, ref.login),\n join(runtime.prototypeRoot, ref.login, ref.slug),\n ];\n\n try {\n for (const path of paths) {\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || !stats.isDirectory()) {\n throw new PrototypeMetadataFileError();\n }\n }\n } catch (error) {\n if (error instanceof PrototypeMetadataFileError) throw error;\n throw new PrototypeMetadataFileError();\n }\n}\n\nasync function readMetadataDocument(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n themeRegistry?: ThemeRegistry,\n) {\n const path = metadataPath(runtime, ref);\n try {\n const file = await open(\n path,\n constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n );\n try {\n const source = await file.readFile(\"utf8\");\n const document: unknown = JSON.parse(source);\n parsePrototypeMetadata(document, { themeRegistry });\n if (\n typeof document !== \"object\" ||\n document === null ||\n Array.isArray(document)\n ) {\n throw new PrototypeMetadataFileError();\n }\n return { ...(document as Record<string, unknown>) };\n } finally {\n await file.close();\n }\n } catch (error) {\n if (error instanceof PrototypeMetadataFileError) throw error;\n throw new PrototypeMetadataFileError();\n }\n}\n\nasync function removePrototypeDirectory(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n) {\n await assertPrototypeDirectory(runtime, ref);\n try {\n await rm(join(runtime.prototypeRoot, ref.login, ref.slug), {\n force: false,\n recursive: true,\n });\n } catch {\n throw new PrototypeMetadataFileError();\n }\n}\n\nasync function writeMetadataDocument(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n document: Record<string, unknown>,\n) {\n const path = metadataPath(runtime, ref);\n const temporaryPath = `${path}.${randomUUID()}.tmp`;\n\n try {\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || !stats.isFile()) {\n throw new PrototypeMetadataFileError();\n }\n await writeFile(temporaryPath, `${JSON.stringify(document, null, 2)}\\n`, {\n encoding: \"utf8\",\n flag: \"wx\",\n });\n await rename(temporaryPath, path);\n } catch (error) {\n if (error instanceof PrototypeMetadataFileError) throw error;\n throw new PrototypeMetadataFileError();\n } finally {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n }\n}\n\nasync function mergeIdentityBranchToPrimary(\n repository: GitRepository,\n options: {\n branch: string;\n primaryBranch: string;\n remote: string;\n },\n) {\n if (options.branch === options.primaryBranch) return;\n\n const hasRemote = (await repository.remotes()).some(\n (remote) => remote.name === options.remote,\n );\n if (!hasRemote) return;\n\n await repository.checkout([options.primaryBranch]);\n try {\n await repository.merge([\n options.branch,\n \"--no-ff\",\n \"-m\",\n `merge: ${options.branch}`,\n ]);\n await repository.push(options.remote, options.primaryBranch);\n } finally {\n await repository.checkout([options.branch]);\n }\n}\n\nfunction mapError(error: unknown): LifecycleErrorCode {\n if (error instanceof PrototypeNotFoundError) return \"not-found\";\n if (error instanceof PrototypeOwnershipError) return \"forbidden\";\n if (error instanceof PrototypeMetadataFileError) return \"filesystem-failure\";\n if (error instanceof RepositoryBusyError) return \"repository-busy\";\n if (\n error instanceof PrototypeRefError ||\n error instanceof LifecycleInputError\n ) {\n return \"invalid-input\";\n }\n if (error instanceof GitRepositoryError) {\n if (error.kind === \"timeout\") return \"timeout\";\n if (error.kind === \"conflict\") return \"working-tree-conflict\";\n if (error.kind === \"invalid-configuration\") return \"unexpected-failure\";\n return \"git-failure\";\n }\n if (error instanceof PrototypeScaffoldError) {\n if (error.kind === \"collision\") return \"already-exists\";\n if (error.kind === \"invalid-input\") return \"invalid-input\";\n return \"filesystem-failure\";\n }\n if (error instanceof PrototypeDuplicateError) {\n if (error.kind === \"source-not-found\") return \"not-found\";\n if (error.kind === \"collision\") return \"already-exists\";\n if (error.kind === \"invalid-source\") return \"invalid-input\";\n return \"filesystem-failure\";\n }\n if (error instanceof DeploymentUnavailableError) {\n return \"deployment-unavailable\";\n }\n if (error instanceof DeploymentProviderError) {\n return error.kind === \"timeout\" ? \"timeout\" : \"deployment-failure\";\n }\n return \"unexpected-failure\";\n}\n\nfunction resultFrom<Value>(\n operation: () => Promise<Value>,\n): Promise<LifecycleResult<Value>> {\n return operation()\n .then(lifecycleSuccess)\n .catch((error: unknown) => lifecycleFailure(mapError(error)));\n}\n\nexport class LocalPrototypeLifecycle implements PrototypeLifecycle {\n readonly #runtime: PrototypeLifecycleRuntimeContext;\n readonly gitMode: GitMode;\n readonly #catalog: PrototypeCatalogLike;\n readonly #repository: GitRepository;\n readonly #preparePrototypeFiles: PreparePrototypeFiles;\n readonly #deploymentProvider?: DeploymentProvider;\n readonly #applicationId?: string;\n readonly #themeRegistry?: ThemeRegistry;\n\n constructor(options: LocalPrototypeLifecycleOptions) {\n const internalOptions = options as InternalLocalPrototypeLifecycleOptions;\n const runtime =\n internalOptions.runtime ?? createPrototypeLifecycleRuntime(internalOptions);\n this.#runtime = {\n ...runtime,\n gitMode: parseGitModeSetting(runtime.gitMode),\n };\n this.gitMode = this.#runtime.gitMode;\n this.#themeRegistry = options.themeRegistry;\n this.#catalog =\n internalOptions.catalog ??\n new PrototypeCatalog({\n ...this.#runtime,\n themeRegistry: this.#themeRegistry,\n });\n this.#repository = this.#runtime.gitRepository;\n this.#preparePrototypeFiles =\n internalOptions.preparePrototypeFiles ?? (() => undefined);\n this.#deploymentProvider = internalOptions.deploymentProvider;\n this.#applicationId = internalOptions.applicationId;\n if (\n this.#deploymentProvider &&\n (typeof this.#applicationId !== \"string\" ||\n this.#applicationId.length === 0)\n ) {\n throw new TypeError(\n \"applicationId must be provided when deploymentProvider is configured\",\n );\n }\n }\n\n async #verifiedIdentity(identity: BonfireIdentity) {\n return parseBonfireIdentity(identity);\n }\n\n async #currentBranch() {\n const branch = await this.#repository.currentBranch();\n if (branch === \"HEAD\" || branch.length === 0) {\n throw new GitRepositoryError(\"conflict\", \"current-branch\");\n }\n return branch;\n }\n\n async #ownedPrototype(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ) {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parsePrototypeCommandInput(input);\n if (normalizedInput.ref.login !== verifiedIdentity.login) {\n throw new PrototypeOwnershipError();\n }\n const summary = await this.#catalog.getSummary(normalizedInput.ref);\n if (!summary) {\n throw new PrototypeNotFoundError();\n }\n\n return {\n ref: normalizedInput.ref,\n path: repositoryRelativePath(this.#runtime, normalizedInput.ref),\n summary,\n };\n }\n\n async #prepareMutationBranch(login: string) {\n await assertIdentityBranchReady(this.#repository, login);\n return login;\n }\n\n async #prepareDestination(\n receipt: OwnedDestinationReceipt,\n expectedFiles: readonly string[],\n request: PreparePrototypeFilesRequest,\n ) {\n try {\n const frozenRequest = Object.freeze({\n ...request,\n ref: Object.freeze({ ...request.ref }),\n identity: Object.freeze({ ...request.identity }),\n ...(request.operation === \"duplicate\"\n ? { source: Object.freeze({ ...request.source }) }\n : {}),\n }) as PreparePrototypeFilesRequest;\n await this.#preparePrototypeFiles(frozenRequest);\n await validateOwnedDestination(\n receipt,\n expectedFiles,\n request.ref,\n this.#themeRegistry,\n );\n } catch {\n try {\n await cleanupOwnedDestination(receipt);\n } catch {\n // The failure remains a finite filesystem failure without retrying cleanup.\n }\n throw new PrototypeScaffoldError(\"filesystem\");\n }\n }\n\n async prepareBranch(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<BranchPreparationValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n if (\n this.#runtime.gitMode === \"manual\" ||\n this.#runtime.automaticBranchSwitch === \"disabled\"\n ) {\n await this.#currentBranch();\n return { status: \"disabled\" } satisfies BranchPreparationValue;\n }\n\n const synchronization = await synchronizeIdentityBranch(\n this.#repository,\n {\n identityBranch: verifiedIdentity.login,\n primaryBranch: this.#runtime.primaryBranch,\n remote: this.#runtime.remote,\n },\n );\n if (synchronization.status !== \"synchronized\") {\n return {\n status: synchronization.status,\n reason: synchronization.reason,\n ...(synchronization.affectedPaths.length > 0\n ? { affectedPaths: synchronization.affectedPaths }\n : {}),\n } satisfies BranchPreparationValue;\n }\n return { status: \"ready\" } satisfies BranchPreparationValue;\n },\n );\n });\n }\n\n async create(\n identity: BonfireIdentity,\n input: CreatePrototypeInput,\n ): Promise<LifecycleResult<CreatePrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parseCreatePrototypeInput(\n input,\n this.#themeRegistry,\n );\n const ref = destinationRef(verifiedIdentity, normalizedInput.title);\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n if (await this.#catalog.getSummary(ref)) {\n throw new PrototypeScaffoldError(\"collision\");\n }\n\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n const prepared = await scaffoldPrototype({\n paths: this.#runtime,\n ref,\n title: normalizedInput.title,\n description: normalizedInput.description,\n authorName: verifiedIdentity.name,\n theme: normalizedInput.theme,\n themeRegistry: this.#themeRegistry,\n });\n await this.#prepareDestination(\n prepared.receipt,\n prepared.expectedFiles,\n {\n operation: \"create\",\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n prototypePath: prepared.destination,\n ref,\n identity: verifiedIdentity,\n title: normalizedInput.title,\n description: normalizedInput.description,\n },\n );\n if (branch === undefined) {\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: \"manual\",\n } satisfies CreatePrototypeValue;\n }\n\n await commitPath(\n this.#repository,\n repositoryRelativePath(this.#runtime, ref),\n `init: ${ref.slug}`,\n );\n const push = await pushBranch(\n this.#repository,\n this.#runtime.remote,\n branch,\n );\n\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: push.remoteStatus,\n } satisfies CreatePrototypeValue;\n },\n );\n });\n }\n\n async edit(\n identity: BonfireIdentity,\n input: EditPrototypeInput,\n ): Promise<LifecycleResult<EditPrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parseEditPrototypeInput(\n input,\n this.#themeRegistry,\n );\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n const { ref, path } = await this.#ownedPrototype(verifiedIdentity, {\n ref: normalizedInput.ref,\n });\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n await assertPrototypeDirectory(this.#runtime, ref);\n const document = await readMetadataDocument(\n this.#runtime,\n ref,\n this.#themeRegistry,\n );\n const metadata = parsePrototypeMetadata(document, {\n themeRegistry: this.#themeRegistry,\n });\n if (metadata.authorLogin !== ref.login) {\n throw new PrototypeNotFoundError();\n }\n\n await writeMetadataDocument(this.#runtime, ref, {\n ...document,\n title: normalizedInput.title,\n description: normalizedInput.description,\n updatedAt: new Date().toISOString(),\n ...(normalizedInput.theme === undefined\n ? {}\n : { theme: normalizedInput.theme }),\n });\n if (branch !== undefined) {\n await commitPath(this.#repository, path, `edit: ${ref.slug}`);\n await pushBranch(this.#repository, this.#runtime.remote, branch);\n }\n\n return { edited: true, ref } satisfies EditPrototypeValue;\n },\n );\n });\n }\n\n async delete(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DeletePrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parsePrototypeCommandInput(input);\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n const { ref, path } = await this.#ownedPrototype(\n verifiedIdentity,\n normalizedInput,\n );\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n await removePrototypeDirectory(this.#runtime, ref);\n if (branch !== undefined) {\n await commitPath(this.#repository, path, `delete: ${ref.slug}`);\n await pushBranch(this.#repository, this.#runtime.remote, branch);\n }\n\n return { deleted: true, ref } satisfies DeletePrototypeValue;\n },\n );\n });\n }\n\n async getDirtyState(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DirtyObservationValue>> {\n return resultFrom(async () => {\n const { path, summary } = await this.#ownedPrototype(identity, input);\n const status = await this.#repository.status([path]);\n return {\n status: status.files.length > 0 ? \"dirty\" : \"clean\",\n ...(summary.previewUrl !== undefined\n ? { previewUrl: summary.previewUrl }\n : {}),\n } satisfies DirtyObservationValue;\n });\n }\n\n async getRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return getRepositorySummary({\n repository: this.#repository,\n catalog: this.#catalog,\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n identity: verifiedIdentity,\n mode: this.#runtime.gitMode,\n remote: this.#runtime.remote,\n primaryBranch: this.#runtime.primaryBranch,\n });\n });\n }\n\n async checkRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return getRepositorySummary({\n repository: this.#repository,\n catalog: this.#catalog,\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n identity: verifiedIdentity,\n mode: this.#runtime.gitMode,\n remote: this.#runtime.remote,\n primaryBranch: this.#runtime.primaryBranch,\n refresh: true,\n });\n });\n }\n\n async deploy(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DeploymentValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parsePrototypeCommandInput(input);\n if (!this.#deploymentProvider) {\n throw new DeploymentUnavailableError();\n }\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n const { ref, path } = await this.#ownedPrototype(\n verifiedIdentity,\n normalizedInput,\n );\n const branch = await this.#prepareMutationBranch(\n verifiedIdentity.login,\n );\n await assertPrototypeDirectory(this.#runtime, ref);\n const document = await readMetadataDocument(\n this.#runtime,\n ref,\n this.#themeRegistry,\n );\n const metadata = parsePrototypeMetadata(document, {\n themeRegistry: this.#themeRegistry,\n });\n if (metadata.authorLogin !== ref.login) {\n throw new PrototypeNotFoundError();\n }\n await commitPath(this.#repository, path, `deploy: ${ref.slug}`);\n await pushBranch(this.#repository, this.#runtime.remote, branch);\n\n const deployment = await this.#deploymentProvider!.deploy({\n applicationId: this.#applicationId!,\n login: verifiedIdentity.login,\n });\n const previewUrl = new URL(\n getPrototypeUrl(ref).slice(1),\n `${deployment.url.replace(/\\/+$/, \"\")}/`,\n ).toString();\n\n let warning: DeploymentWarningCode | undefined;\n try {\n await writeMetadataDocument(this.#runtime, ref, {\n ...document,\n previewUrl,\n updatedAt: new Date().toISOString(),\n });\n await commitPath(\n this.#repository,\n path,\n `deploy: ${ref.slug} (metadata)`,\n );\n await pushBranch(this.#repository, this.#runtime.remote, branch);\n } catch {\n warning = \"metadata-persistence-failed\";\n }\n\n if (warning === undefined) {\n try {\n await mergeIdentityBranchToPrimary(this.#repository, {\n branch,\n primaryBranch: this.#runtime.primaryBranch,\n remote: this.#runtime.remote,\n });\n } catch {\n warning = \"primary-merge-failed\";\n }\n }\n\n return {\n deployed: true,\n ref,\n previewUrl,\n deploymentId: deployment.deploymentId,\n readyState: deployment.readyState,\n warning,\n } satisfies DeploymentValue;\n },\n );\n });\n }\n\n async save(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<SavePrototypeValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const { ref, path } = await this.#ownedPrototype(\n verifiedIdentity,\n input,\n );\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n await this.#prepareMutationBranch(verifiedIdentity.login);\n await commitPath(this.#repository, path, `save: ${ref.slug}`);\n await pushBranch(\n this.#repository,\n this.#runtime.remote,\n verifiedIdentity.login,\n );\n return { saved: true } satisfies SavePrototypeValue;\n },\n );\n });\n }\n\n async discard(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DiscardPrototypeValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const { path } = await this.#ownedPrototype(\n verifiedIdentity,\n input,\n );\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n await this.#prepareMutationBranch(verifiedIdentity.login);\n await discardPath(this.#repository, path);\n return { discarded: true } satisfies DiscardPrototypeValue;\n },\n );\n });\n }\n\n async duplicate(\n identity: BonfireIdentity,\n input: DuplicatePrototypeInput,\n ): Promise<LifecycleResult<DuplicatePrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parseDuplicatePrototypeInput(input);\n if (!(await this.#catalog.getSummary(normalizedInput.source))) {\n throw new PrototypeDuplicateError(\"source-not-found\");\n }\n const ref = destinationRef(verifiedIdentity, normalizedInput.title);\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n if (await this.#catalog.getSummary(ref)) {\n throw new PrototypeDuplicateError(\"collision\");\n }\n\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n const prepared = await duplicatePrototype({\n paths: this.#runtime,\n source: normalizedInput.source,\n destination: ref,\n title: normalizedInput.title,\n description: normalizedInput.description,\n authorName: verifiedIdentity.name,\n themeRegistry: this.#themeRegistry,\n });\n await this.#prepareDestination(\n prepared.receipt,\n prepared.expectedFiles,\n {\n operation: \"duplicate\",\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n prototypePath: prepared.destination,\n ref,\n source: normalizedInput.source,\n identity: verifiedIdentity,\n title: normalizedInput.title,\n description: normalizedInput.description,\n },\n );\n if (branch === undefined) {\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: \"manual\",\n } satisfies DuplicatePrototypeValue;\n }\n\n await commitPath(\n this.#repository,\n repositoryRelativePath(this.#runtime, ref),\n `init: ${ref.slug}`,\n );\n const push = await pushBranch(\n this.#repository,\n this.#runtime.remote,\n branch,\n );\n\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: push.remoteStatus,\n } satisfies DuplicatePrototypeValue;\n },\n );\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"local-prototype-lifecycle.d.ts","sourceRoot":"","sources":["../../src/lifecycle/local-prototype-lifecycle.ts"],"names":[],"mappings":"AAMA,OAAO,EAeL,KAAK,sBAAsB,EAC3B,KAAK,oBAAoB,EACzB,KAAK,0BAA0B,EAC/B,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EAKpB,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EAEvB,KAAK,OAAO,EAEZ,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,aAAa,EACnB,MAAM,uBAAuB,CAAC;AAU/B,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,yBAAyB,CAAC;AAMjC,OAAO,KAAK,EACV,qBAAqB,EAEtB,MAAM,+BAA+B,CAAC;AAUvC,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,2BAA2B,CAAC;AAMnC,OAAO,EAEL,uBAAuB,EAExB,MAAM,0BAA0B,CAAC;AAMlC,OAAO,EAIL,KAAK,mBAAmB,EACzB,MAAM,yBAAyB,CAAC;AAIjC,KAAK,eAAe,CAAC,KAAK,EAAE,KAAK,IAAI,CACnC,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,KAAK,KACT,OAAO,CAAC,eAAe,CAAC,KAAK,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AAC,eAAe,CAAC,kBAAkB,CAAC,CAAC,CAuB9C;IAEK,OAAO,CACX,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,qBAAqB,GAC3B,OAAO,CAAC,eAAe,CAAC,qBAAqB,CAAC,CAAC,CAmBjD;IAEK,SAAS,CACb,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,uBAAuB,GAC7B,OAAO,CAAC,eAAe,CAAC,uBAAuB,CAAC,CAAC,CAuEnD;CACF","sourcesContent":["import { constants } from \"node:fs\";\nimport { execFile as execFileCallback } from \"node:child_process\";\nimport { lstat, open, rename, rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport { promisify } from \"node:util\";\nimport { join, relative, sep } from \"node:path\";\nimport {\n definePrototypeRef,\n getPrototypeUrl,\n LifecycleInputError,\n lifecycleFailure,\n lifecycleSuccess,\n parseCreatePrototypeInput,\n parseDuplicatePrototypeInput,\n parseEditPrototypeInput,\n parseBonfireIdentity,\n parsePrototypeCommandInput,\n parsePrototypeMetadata,\n slugifyPrototypeTitle,\n PrototypeRefError,\n type BranchPreparationAttention,\n type BranchPreparationValue,\n type CreatePrototypeInput,\n type DependencyPreparationValue,\n type CreatePrototypeValue,\n type DeletePrototypeValue,\n type DeploymentValue,\n type DeploymentWarningCode,\n type LifecycleOperationOutcome,\n type LifecycleRecoveryKind,\n type LifecycleRecoveryOperation,\n type LifecycleRecoveryValue,\n type DirtyObservationValue,\n type DiscardPrototypeValue,\n type DuplicatePrototypeInput,\n type DuplicatePrototypeValue,\n type EditPrototypeInput,\n type EditPrototypeValue,\n parseGitModeSetting,\n type GitMode,\n type LifecycleErrorCode,\n type LifecycleResult,\n type BonfireIdentity,\n type PrototypeCommandInput,\n type SavePrototypeValue,\n type RepositorySummary,\n type ThemeRegistry,\n} from \"@ebay-dt/bonfire-core\";\nimport {\n commitPath,\n GitRepositoryError,\n pushBranch,\n pushCommitToBranch,\n remoteBranchCommit,\n type GitRepository,\n} from \"../git-repository.js\";\nimport { duplicatePrototype, PrototypeDuplicateError } from \"../duplicate.js\";\nimport {\n PrototypeCatalog,\n type PrototypeCatalogLike,\n} from \"../prototype-catalog.js\";\nimport { PrototypeScaffoldError, scaffoldPrototype } from \"../scaffold.js\";\nimport {\n createPrototypeLifecycleRuntime,\n type PrototypeLifecycleRuntimeContext,\n} from \"./runtime-context.js\";\nimport type {\n PreparePrototypeFiles,\n PreparePrototypeFilesRequest,\n} from \"../prepare-prototype-files.js\";\nimport {\n cleanupOwnedDestination,\n validateOwnedDestination,\n type OwnedDestinationReceipt,\n} from \"../internal/owned-destination.js\";\nimport {\n RepositoryBusyError,\n withRepositoryOperation,\n} from \"./operation-gate.js\";\nimport {\n DeploymentProviderError,\n type DeploymentProvider,\n} from \"../deployment-provider.js\";\nimport {\n assertIdentityBranchReady,\n synchronizeIdentityBranch,\n} from \"./repository-synchronization.js\";\nimport { getRepositorySummary } from \"./repository-summary.js\";\nimport {\n DeploymentWorktreeError,\n publishDeploymentSource,\n reportDeploymentIssue,\n} from \"./deployment-worktree.js\";\nimport {\n commitPrototypePath,\n deletePrototypePath,\n discardPrototypePath,\n} from \"./prototype-path-policy.js\";\nimport {\n clearPreparationMarker,\n readPreparationMarker,\n writePreparationMarker,\n type DependencyInstaller,\n} from \"./preparation-marker.js\";\n\nconst execFile = promisify(execFileCallback);\n\ntype LifecycleMethod<Input, Value> = (\n identity: BonfireIdentity,\n input: Input,\n) => Promise<LifecycleResult<Value>>;\n\nexport type PrototypeLifecycle = {\n /** Declares whether this lifecycle enforces the selected Git mode. */\n readonly gitMode?: GitMode;\n prepareBranch(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<BranchPreparationValue>>;\n prepareDependencies?(\n dependencyPaths?: readonly string[],\n installer?: DependencyInstaller,\n ): Promise<LifecycleResult<DependencyPreparationValue>>;\n create: LifecycleMethod<CreatePrototypeInput, CreatePrototypeValue>;\n duplicate: LifecycleMethod<DuplicatePrototypeInput, DuplicatePrototypeValue>;\n edit: LifecycleMethod<EditPrototypeInput, EditPrototypeValue>;\n delete: LifecycleMethod<PrototypeCommandInput, DeletePrototypeValue>;\n getDirtyState: LifecycleMethod<PrototypeCommandInput, DirtyObservationValue>;\n getRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>>;\n checkRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>>;\n save: LifecycleMethod<PrototypeCommandInput, SavePrototypeValue>;\n discard: LifecycleMethod<PrototypeCommandInput, DiscardPrototypeValue>;\n deploy: LifecycleMethod<PrototypeCommandInput, DeploymentValue>;\n retryPublish?: LifecycleMethod<PrototypeCommandInput, DeploymentValue>;\n getPendingRecovery?(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<LifecycleRecoveryValue | null>>;\n retryPendingPublication?(\n identity: BonfireIdentity,\n recoveryId: string,\n ): Promise<LifecycleResult<LifecycleRecoveryValue>>;\n};\n\nexport type LocalPrototypeLifecycleOptions = {\n repositoryRoot: string;\n prototypeRoot?: string;\n remote?: string;\n primaryBranch?: string;\n automaticBranchSwitch?: \"enabled\" | \"disabled\";\n gitMode?: GitMode;\n commitIdentity?: {\n name: string;\n email: string;\n };\n catalog?: PrototypeCatalogLike;\n preparePrototypeFiles?: PreparePrototypeFiles;\n deploymentProvider?: DeploymentProvider;\n applicationId?: string;\n themeRegistry?: ThemeRegistry;\n publishDeploymentSource?: typeof publishDeploymentSource | null;\n /** Test/host seam for the existing package-manager installation step. */\n installDependencies?: DependencyInstaller;\n};\n\ntype InternalLocalPrototypeLifecycleOptions = LocalPrototypeLifecycleOptions & {\n runtime?: PrototypeLifecycleRuntimeContext;\n};\n\nfunction repositoryRelativePath(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n) {\n const absolutePath = join(runtime.prototypeRoot, ref.login, ref.slug);\n return relative(runtime.repositoryRoot, absolutePath).split(sep).join(\"/\");\n}\n\nfunction namespaceRelativePath(\n runtime: PrototypeLifecycleRuntimeContext,\n login: string,\n) {\n return relative(runtime.repositoryRoot, join(runtime.prototypeRoot, login))\n .split(sep)\n .join(\"/\");\n}\n\nfunction destinationRef(identity: BonfireIdentity, title: string) {\n const slug = slugifyPrototypeTitle(title);\n if (slug === null)\n throw new PrototypeRefError(\"title\", \"must produce a slug\");\n return definePrototypeRef({ login: identity.login, slug });\n}\n\nclass PrototypeNotFoundError extends Error {}\nclass PrototypeOwnershipError extends Error {}\nclass PrototypeMetadataFileError extends Error {}\nclass DeploymentUnavailableError extends Error {}\nclass DeploymentSourcePushError extends Error {}\nclass DeploymentNotAcceptedError extends Error {}\n\ntype PendingPublication = {\n recoveryId: string;\n operation: LifecycleRecoveryOperation;\n kind: LifecycleRecoveryKind;\n identity: BonfireIdentity;\n ref: { login: string; slug: string };\n path: string;\n sourceSha: string;\n previewUrl?: string;\n deploymentId?: string;\n acceptedAt?: string;\n readyState?: DeploymentValue[\"readyState\"];\n};\n\nconst pendingPublications = new Map<string, PendingPublication>();\n\nfunction pendingPublicationKey(repositoryRoot: string, login: string) {\n return `${repositoryRoot}\\0${login}`;\n}\n\nfunction metadataPath(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n) {\n return join(runtime.prototypeRoot, ref.login, ref.slug, \"metadata.json\");\n}\n\ntype PrototypeDirectorySnapshotEntry = {\n path: string;\n kind: \"missing\" | \"directory\" | \"symlink\" | \"other\";\n dev?: number;\n ino?: number;\n};\ntype PrototypeDirectorySnapshot = readonly PrototypeDirectorySnapshotEntry[];\n\nfunction prototypeDirectoryPaths(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n) {\n return [\n runtime.prototypeRoot,\n join(runtime.prototypeRoot, ref.login),\n join(runtime.prototypeRoot, ref.login, ref.slug),\n ];\n}\n\nasync function capturePrototypeDirectory(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n): Promise<PrototypeDirectorySnapshot> {\n const entries: PrototypeDirectorySnapshotEntry[] = [];\n for (const path of prototypeDirectoryPaths(runtime, ref)) {\n try {\n const stats = await lstat(path);\n entries.push({\n path,\n kind: stats.isSymbolicLink()\n ? \"symlink\"\n : stats.isDirectory()\n ? \"directory\"\n : \"other\",\n dev: stats.dev,\n ino: stats.ino,\n });\n } catch (error) {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n entries.push({ path, kind: \"missing\" });\n continue;\n }\n throw new PrototypeMetadataFileError();\n }\n }\n return entries;\n}\n\nfunction samePrototypeDirectorySnapshot(\n expected: PrototypeDirectorySnapshot,\n actual: PrototypeDirectorySnapshot,\n) {\n return expected.every((entry, index) => {\n const current = actual[index];\n return (\n current !== undefined &&\n current.path === entry.path &&\n current.kind === entry.kind &&\n current.dev === entry.dev &&\n current.ino === entry.ino\n );\n });\n}\n\nasync function assertPrototypeDirectory(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n expected?: PrototypeDirectorySnapshot,\n) {\n try {\n const actual = await capturePrototypeDirectory(runtime, ref);\n if (\n expected !== undefined &&\n !samePrototypeDirectorySnapshot(expected, actual)\n ) {\n throw new PrototypeMetadataFileError();\n }\n if (actual.some((entry) => entry.kind !== \"directory\")) {\n throw new PrototypeMetadataFileError();\n }\n } catch (error) {\n if (error instanceof PrototypeMetadataFileError) throw error;\n throw new PrototypeMetadataFileError();\n }\n}\n\nasync function readMetadataDocument(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n themeRegistry?: ThemeRegistry,\n) {\n const path = metadataPath(runtime, ref);\n try {\n const file = await open(\n path,\n constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),\n );\n try {\n const source = await file.readFile(\"utf8\");\n const document: unknown = JSON.parse(source);\n parsePrototypeMetadata(document, { themeRegistry });\n if (\n typeof document !== \"object\" ||\n document === null ||\n Array.isArray(document)\n ) {\n throw new PrototypeMetadataFileError();\n }\n return { ...(document as Record<string, unknown>) };\n } finally {\n await file.close();\n }\n } catch (error) {\n if (error instanceof PrototypeMetadataFileError) throw error;\n throw new PrototypeMetadataFileError();\n }\n}\n\nasync function writeMetadataDocument(\n runtime: PrototypeLifecycleRuntimeContext,\n ref: { login: string; slug: string },\n document: Record<string, unknown>,\n) {\n const path = metadataPath(runtime, ref);\n const temporaryPath = `${path}.${randomUUID()}.tmp`;\n\n try {\n const stats = await lstat(path);\n if (stats.isSymbolicLink() || !stats.isFile()) {\n throw new PrototypeMetadataFileError();\n }\n await writeFile(temporaryPath, `${JSON.stringify(document, null, 2)}\\n`, {\n encoding: \"utf8\",\n flag: \"wx\",\n });\n await rename(temporaryPath, path);\n } catch (error) {\n if (error instanceof PrototypeMetadataFileError) throw error;\n throw new PrototypeMetadataFileError();\n } finally {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n }\n}\n\nfunction mapError(error: unknown): LifecycleErrorCode {\n if (error instanceof PrototypeNotFoundError) return \"not-found\";\n if (error instanceof PrototypeOwnershipError) return \"forbidden\";\n if (error instanceof PrototypeMetadataFileError) return \"filesystem-failure\";\n if (error instanceof RepositoryBusyError) return \"repository-busy\";\n if (\n error instanceof PrototypeRefError ||\n error instanceof LifecycleInputError\n ) {\n return \"invalid-input\";\n }\n if (error instanceof GitRepositoryError) {\n if (error.kind === \"timeout\") return \"timeout\";\n if (error.kind === \"conflict\") return \"working-tree-conflict\";\n if (error.kind === \"invalid-configuration\") return \"unexpected-failure\";\n return \"git-failure\";\n }\n if (error instanceof PrototypeScaffoldError) {\n if (error.kind === \"collision\") return \"already-exists\";\n if (error.kind === \"invalid-input\") return \"invalid-input\";\n return \"filesystem-failure\";\n }\n if (error instanceof PrototypeDuplicateError) {\n if (error.kind === \"source-not-found\") return \"not-found\";\n if (error.kind === \"collision\") return \"already-exists\";\n if (error.kind === \"invalid-source\") return \"invalid-input\";\n return \"filesystem-failure\";\n }\n if (error instanceof DeploymentUnavailableError) {\n return \"deployment-unavailable\";\n }\n if (\n error instanceof DeploymentSourcePushError ||\n error instanceof DeploymentNotAcceptedError ||\n error instanceof DeploymentWorktreeError\n ) {\n return \"deployment-failure\";\n }\n if (error instanceof DeploymentProviderError) {\n return error.kind === \"timeout\" ? \"timeout\" : \"deployment-failure\";\n }\n return \"unexpected-failure\";\n}\n\nfunction resultFrom<Value>(\n operation: () => Promise<Value>,\n): Promise<LifecycleResult<Value>> {\n return operation()\n .then(lifecycleSuccess)\n .catch((error: unknown) => lifecycleFailure(mapError(error)));\n}\n\nasync function diagnoseMetadataStep<Value>(\n step: \"metadata-read\" | \"metadata-write\" | \"metadata-commit\",\n operation: () => Promise<Value>,\n): Promise<Value> {\n try {\n return await operation();\n } catch (error) {\n reportDeploymentIssue(\"publication\", step, error);\n throw error;\n }\n}\n\nexport class LocalPrototypeLifecycle implements PrototypeLifecycle {\n readonly #runtime: PrototypeLifecycleRuntimeContext;\n readonly gitMode: GitMode;\n readonly #catalog: PrototypeCatalogLike;\n readonly #repository: GitRepository;\n readonly #preparePrototypeFiles: PreparePrototypeFiles;\n readonly #deploymentProvider?: DeploymentProvider;\n readonly #applicationId?: string;\n readonly #themeRegistry?: ThemeRegistry;\n readonly #publishDeploymentSource: typeof publishDeploymentSource | null;\n readonly #installDependencies?: DependencyInstaller;\n #restartRequired = false;\n readonly #preparationAttention = new Map<\n string,\n BranchPreparationAttention\n >();\n\n constructor(options: LocalPrototypeLifecycleOptions) {\n const internalOptions = options as InternalLocalPrototypeLifecycleOptions;\n const runtime =\n internalOptions.runtime ??\n createPrototypeLifecycleRuntime(internalOptions);\n this.#runtime = {\n ...runtime,\n gitMode: parseGitModeSetting(runtime.gitMode),\n };\n this.gitMode = this.#runtime.gitMode;\n this.#themeRegistry = options.themeRegistry;\n this.#catalog =\n internalOptions.catalog ??\n new PrototypeCatalog({\n ...this.#runtime,\n themeRegistry: this.#themeRegistry,\n });\n this.#repository = this.#runtime.gitRepository;\n this.#preparePrototypeFiles =\n internalOptions.preparePrototypeFiles ?? (() => undefined);\n this.#deploymentProvider = internalOptions.deploymentProvider;\n this.#applicationId = internalOptions.applicationId;\n this.#publishDeploymentSource =\n internalOptions.publishDeploymentSource === null\n ? null\n : (internalOptions.publishDeploymentSource ?? publishDeploymentSource);\n this.#installDependencies = options.installDependencies;\n if (\n this.#deploymentProvider &&\n (typeof this.#applicationId !== \"string\" ||\n this.#applicationId.length === 0)\n ) {\n throw new TypeError(\n \"applicationId must be provided when deploymentProvider is configured\",\n );\n }\n }\n\n async #verifiedIdentity(identity: BonfireIdentity) {\n return parseBonfireIdentity(identity);\n }\n\n async #currentBranch() {\n const branch = await this.#repository.currentBranch();\n if (branch === \"HEAD\" || branch.length === 0) {\n throw new GitRepositoryError(\"conflict\", \"current-branch\");\n }\n return branch;\n }\n\n async #authorizedPrototype(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ) {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parsePrototypeCommandInput(input);\n if (normalizedInput.ref.login !== verifiedIdentity.login) {\n throw new PrototypeOwnershipError();\n }\n const directorySnapshot = await capturePrototypeDirectory(\n this.#runtime,\n normalizedInput.ref,\n );\n return {\n ref: normalizedInput.ref,\n path: repositoryRelativePath(this.#runtime, normalizedInput.ref),\n directorySnapshot,\n };\n }\n\n async #ownedPrototype(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ) {\n const authorized = await this.#authorizedPrototype(identity, input);\n const summary = await this.#catalog.getSummary(authorized.ref);\n if (!summary) {\n throw new PrototypeNotFoundError();\n }\n\n return { ...authorized, summary };\n }\n\n async #prepareMutationBranch(login: string) {\n await assertIdentityBranchReady(this.#repository, login);\n return login;\n }\n\n async #prepareDestination(\n receipt: OwnedDestinationReceipt,\n expectedFiles: readonly string[],\n request: PreparePrototypeFilesRequest,\n ) {\n try {\n const frozenRequest = Object.freeze({\n ...request,\n ref: Object.freeze({ ...request.ref }),\n identity: Object.freeze({ ...request.identity }),\n ...(request.operation === \"duplicate\"\n ? { source: Object.freeze({ ...request.source }) }\n : {}),\n }) as PreparePrototypeFilesRequest;\n await this.#preparePrototypeFiles(frozenRequest);\n await validateOwnedDestination(\n receipt,\n expectedFiles,\n request.ref,\n this.#themeRegistry,\n );\n } catch {\n try {\n await cleanupOwnedDestination(receipt);\n } catch {\n // The failure remains a finite filesystem failure without retrying cleanup.\n }\n throw new PrototypeScaffoldError(\"filesystem\");\n }\n }\n\n async prepareBranch(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<BranchPreparationValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n if (\n this.#runtime.gitMode === \"manual\" ||\n this.#runtime.automaticBranchSwitch === \"disabled\"\n ) {\n await this.#currentBranch();\n const disabled = {\n status: \"disabled\",\n effects: {\n changed: false,\n pushed: false,\n reconciledPaths: [],\n restartRequired: false,\n },\n } satisfies BranchPreparationValue;\n this.#preparationAttention.set(verifiedIdentity.login, disabled);\n return disabled;\n }\n\n const synchronization = await synchronizeIdentityBranch(\n this.#repository,\n {\n identityBranch: verifiedIdentity.login,\n primaryBranch: this.#runtime.primaryBranch,\n remote: this.#runtime.remote,\n prototypeRoot: relative(\n this.#runtime.repositoryRoot,\n this.#runtime.prototypeRoot,\n )\n .split(sep)\n .join(\"/\"),\n },\n );\n const reconciledPaths =\n synchronization.status === \"synchronized\" &&\n synchronization.platformPaths.length === 0\n ? synchronization.affectedPaths.filter((path) =>\n this.#runtime.managedRepositoryPaths.includes(path),\n )\n : synchronization.platformPaths;\n const effects = {\n changed: synchronization.changed,\n pushed: synchronization.pushed,\n reconciledPaths,\n restartRequired:\n synchronization.status === \"synchronized\" &&\n synchronization.platformPaths.length === 0\n ? reconciledPaths.length > 0\n : synchronization.restartRequired,\n ...(synchronization.platformPaths.length > 0\n ? { platformPaths: synchronization.platformPaths }\n : {}),\n ...(synchronization.dependencyPaths.length > 0\n ? { dependencyPaths: synchronization.dependencyPaths }\n : {}),\n ...(synchronization.preparationRequired\n ? { preparationRequired: true }\n : {}),\n };\n if (effects.restartRequired) this.#restartRequired = true;\n if (effects.preparationRequired) {\n await writePreparationMarker(\n this.#repository,\n this.#runtime.repositoryRoot,\n effects.dependencyPaths ?? [],\n );\n }\n if (synchronization.status === \"deferred\") {\n const attention = {\n status: \"deferred\",\n reason: synchronization.reason,\n effects,\n ...(synchronization.affectedPaths.length > 0\n ? { affectedPaths: synchronization.affectedPaths }\n : {}),\n } satisfies BranchPreparationAttention;\n this.#preparationAttention.set(verifiedIdentity.login, attention);\n return attention;\n }\n if (synchronization.status === \"unsafe\") {\n const attention = {\n status: \"unsafe\",\n reason: synchronization.reason,\n effects,\n ...(synchronization.affectedPaths.length > 0\n ? { affectedPaths: synchronization.affectedPaths }\n : {}),\n } satisfies BranchPreparationAttention;\n this.#preparationAttention.set(verifiedIdentity.login, attention);\n return attention;\n }\n const ready = {\n status: \"ready\",\n effects,\n ...(synchronization.affectedPaths.length > 0\n ? { affectedPaths: synchronization.affectedPaths }\n : {}),\n } satisfies BranchPreparationValue;\n this.#preparationAttention.delete(verifiedIdentity.login);\n return ready;\n },\n );\n });\n }\n\n async prepareDependencies(\n dependencyPaths: readonly string[] = [],\n installer?: DependencyInstaller,\n ): Promise<LifecycleResult<DependencyPreparationValue>> {\n return resultFrom(async () =>\n withRepositoryOperation(this.#runtime.repositoryRealPath, async () => {\n let pending: readonly string[] | null = null;\n try {\n pending = await readPreparationMarker(\n this.#repository,\n this.#runtime.repositoryRoot,\n );\n } catch {\n // A retained/corrupt marker is recovery truth. Restricted modes must\n // preserve it without attempting installation; managed mode must\n // report not-ready rather than guessing what to install.\n if (\n this.#runtime.gitMode === \"manual\" ||\n this.#runtime.automaticBranchSwitch === \"disabled\"\n ) {\n return {\n status: \"skipped\",\n dependencyPaths: [...dependencyPaths],\n pending: true,\n restartRequired: false,\n } satisfies DependencyPreparationValue;\n }\n return {\n status: \"failed\",\n dependencyPaths: [...dependencyPaths],\n pending: true,\n restartRequired: true,\n } satisfies DependencyPreparationValue;\n }\n const paths = [...new Set([...(pending ?? []), ...dependencyPaths])];\n if (\n this.#runtime.gitMode === \"manual\" ||\n this.#runtime.automaticBranchSwitch === \"disabled\"\n ) {\n return {\n status: \"skipped\",\n dependencyPaths: paths,\n pending: pending !== null,\n restartRequired: false,\n } satisfies DependencyPreparationValue;\n }\n // An empty path list is still an obligation when the marker exists.\n // Do not reinterpret a retained marker as \"not required\".\n if (paths.length === 0 && pending === null) {\n return {\n status: \"not-required\",\n dependencyPaths: [],\n pending: false,\n restartRequired: false,\n } satisfies DependencyPreparationValue;\n }\n await writePreparationMarker(\n this.#repository,\n this.#runtime.repositoryRoot,\n paths,\n );\n try {\n await (\n installer ??\n this.#installDependencies ??\n (async (root) => {\n await execFile(\"pnpm\", [\"install\"], { cwd: root });\n })\n )(this.#runtime.repositoryRoot);\n } catch {\n return {\n status: \"failed\",\n dependencyPaths: paths,\n pending: true,\n restartRequired: true,\n } satisfies DependencyPreparationValue;\n }\n await clearPreparationMarker(\n this.#repository,\n this.#runtime.repositoryRoot,\n );\n return {\n status: \"prepared\",\n dependencyPaths: paths,\n pending: false,\n restartRequired: true,\n } satisfies DependencyPreparationValue;\n }),\n );\n }\n\n async create(\n identity: BonfireIdentity,\n input: CreatePrototypeInput,\n ): Promise<LifecycleResult<CreatePrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parseCreatePrototypeInput(\n input,\n this.#themeRegistry,\n );\n const ref = destinationRef(verifiedIdentity, normalizedInput.title);\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n if (await this.#catalog.getSummary(ref)) {\n throw new PrototypeScaffoldError(\"collision\");\n }\n\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n const prepared = await scaffoldPrototype({\n paths: this.#runtime,\n ref,\n title: normalizedInput.title,\n description: normalizedInput.description,\n authorName: verifiedIdentity.name,\n theme: normalizedInput.theme,\n themeRegistry: this.#themeRegistry,\n });\n await this.#prepareDestination(\n prepared.receipt,\n prepared.expectedFiles,\n {\n operation: \"create\",\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n prototypePath: prepared.destination,\n ref,\n identity: verifiedIdentity,\n title: normalizedInput.title,\n description: normalizedInput.description,\n },\n );\n if (branch === undefined) {\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: \"manual\",\n } satisfies CreatePrototypeValue;\n }\n\n await commitPath(\n this.#repository,\n repositoryRelativePath(this.#runtime, ref),\n `init: ${ref.slug}`,\n );\n const sourceSha = await this.#headCommit();\n const outcome = await this.#publishOrdinaryNamespace(\n verifiedIdentity,\n \"create\",\n ref,\n repositoryRelativePath(this.#runtime, ref),\n sourceSha,\n );\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: \"local-only\",\n outcome,\n } satisfies CreatePrototypeValue;\n },\n );\n });\n }\n\n async edit(\n identity: BonfireIdentity,\n input: EditPrototypeInput,\n ): Promise<LifecycleResult<EditPrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parseEditPrototypeInput(\n input,\n this.#themeRegistry,\n );\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n const { ref, path } = await this.#ownedPrototype(verifiedIdentity, {\n ref: normalizedInput.ref,\n });\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n await assertPrototypeDirectory(this.#runtime, ref);\n const document = await readMetadataDocument(\n this.#runtime,\n ref,\n this.#themeRegistry,\n );\n const metadata = parsePrototypeMetadata(document, {\n themeRegistry: this.#themeRegistry,\n });\n if (metadata.authorLogin !== ref.login) {\n throw new PrototypeNotFoundError();\n }\n\n await writeMetadataDocument(this.#runtime, ref, {\n ...document,\n title: normalizedInput.title,\n description: normalizedInput.description,\n updatedAt: new Date().toISOString(),\n ...(normalizedInput.theme === undefined\n ? {}\n : { theme: normalizedInput.theme }),\n });\n if (branch !== undefined) {\n await commitPath(this.#repository, path, `edit: ${ref.slug}`);\n await pushBranch(this.#repository, this.#runtime.remote, branch);\n }\n\n return { edited: true, ref } satisfies EditPrototypeValue;\n },\n );\n });\n }\n\n async delete(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DeletePrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parsePrototypeCommandInput(input);\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n const { ref, path, directorySnapshot } =\n await this.#authorizedPrototype(verifiedIdentity, normalizedInput);\n if (directorySnapshot.at(-1)?.kind === \"missing\") {\n throw new PrototypeNotFoundError();\n }\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n await assertPrototypeDirectory(this.#runtime, ref, directorySnapshot);\n await deletePrototypePath(\n this.#repository,\n path,\n branch === undefined ? undefined : `delete: ${ref.slug}`,\n );\n if (branch !== undefined) {\n const sourceSha = await this.#headCommit();\n const outcome = await this.#publishOrdinaryNamespace(\n verifiedIdentity,\n \"delete\",\n ref,\n path,\n sourceSha,\n );\n return {\n deleted: true,\n ref,\n outcome,\n } satisfies DeletePrototypeValue;\n }\n\n return {\n deleted: true,\n ref,\n outcome: {\n local: { status: \"completed\" },\n upload: { status: \"not-attempted\" },\n preview: { status: \"not-attempted\" },\n publication: { status: \"not-attempted\" },\n },\n } satisfies DeletePrototypeValue;\n },\n );\n });\n }\n\n async getDirtyState(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DirtyObservationValue>> {\n return resultFrom(async () => {\n const { path, summary } = await this.#ownedPrototype(identity, input);\n const status = await this.#repository.status([path]);\n return {\n status: status.files.length > 0 ? \"dirty\" : \"clean\",\n ...(summary.previewUrl !== undefined\n ? { previewUrl: summary.previewUrl }\n : {}),\n } satisfies DirtyObservationValue;\n });\n }\n\n async getRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () =>\n getRepositorySummary({\n repository: this.#repository,\n catalog: this.#catalog,\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n identity: verifiedIdentity,\n mode: this.#runtime.gitMode,\n remote: this.#runtime.remote,\n primaryBranch: this.#runtime.primaryBranch,\n restartRequired: this.#restartRequired,\n preparationAttention: this.#preparationAttention.get(\n verifiedIdentity.login,\n ),\n preparationPending:\n (await readPreparationMarker(\n this.#repository,\n this.#runtime.repositoryRoot,\n )) !== null,\n }),\n );\n });\n }\n\n async checkRepositorySummary(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<RepositorySummary>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () =>\n getRepositorySummary({\n repository: this.#repository,\n catalog: this.#catalog,\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n identity: verifiedIdentity,\n mode: this.#runtime.gitMode,\n remote: this.#runtime.remote,\n primaryBranch: this.#runtime.primaryBranch,\n restartRequired: this.#restartRequired,\n preparationAttention: this.#preparationAttention.get(\n verifiedIdentity.login,\n ),\n preparationPending:\n (await readPreparationMarker(\n this.#repository,\n this.#runtime.repositoryRoot,\n )) !== null,\n refresh: true,\n }),\n );\n });\n }\n\n async #headCommit() {\n const commit = (await this.#repository.raw([\"rev-parse\", \"HEAD\"])).trim();\n if (!/^[0-9a-f]{40,64}$/iu.test(commit)) {\n throw new GitRepositoryError(\"malformed-output\", \"head-commit\");\n }\n return commit.toLowerCase();\n }\n\n #workspaceRuntime(\n workspacePath: string,\n workspaceRepository: GitRepository,\n ): PrototypeLifecycleRuntimeContext {\n return {\n ...this.#runtime,\n repositoryRoot: workspacePath,\n repositoryRealPath: workspacePath,\n prototypeRoot: join(\n workspacePath,\n relative(this.#runtime.repositoryRoot, this.#runtime.prototypeRoot),\n ),\n gitRepository: workspaceRepository,\n };\n }\n\n #pendingKey(login: string) {\n return pendingPublicationKey(this.#runtime.repositoryRoot, login);\n }\n\n #rememberPending(pending: PendingPublication) {\n pendingPublications.set(this.#pendingKey(pending.identity.login), pending);\n }\n\n #clearPending(login: string) {\n pendingPublications.delete(this.#pendingKey(login));\n }\n\n #recoveryValue(\n pending: PendingPublication,\n outcome: LifecycleOperationOutcome,\n ): LifecycleRecoveryValue {\n return {\n recoveryId: pending.recoveryId,\n operation: pending.operation,\n kind: pending.kind,\n ref: pending.ref,\n sourceSha: pending.sourceSha,\n ...(pending.previewUrl === undefined\n ? {}\n : { previewUrl: pending.previewUrl }),\n ...(pending.deploymentId === undefined\n ? {}\n : { deploymentId: pending.deploymentId }),\n ...(pending.readyState === undefined\n ? {}\n : { readyState: pending.readyState }),\n ...(pending.acceptedAt === undefined\n ? {}\n : { acceptedAt: pending.acceptedAt }),\n outcome,\n };\n }\n\n async #publishCommittedNamespace(\n identity: BonfireIdentity,\n sourceSha: string,\n ) {\n if (this.#publishDeploymentSource === null) {\n throw new DeploymentUnavailableError();\n }\n return this.#publishDeploymentSource(\n this.#repository,\n {\n remote: this.#runtime.remote,\n primaryBranch: this.#runtime.primaryBranch,\n sourceSha,\n namespacePath: namespaceRelativePath(this.#runtime, identity.login),\n commitIdentity: this.#runtime.commitIdentity,\n },\n async () => undefined,\n );\n }\n\n async #publishOrdinaryNamespace(\n identity: BonfireIdentity,\n operation: \"create\" | \"delete\",\n ref: { login: string; slug: string },\n path: string,\n sourceSha: string,\n ): Promise<LifecycleOperationOutcome> {\n const baseOutcome: LifecycleOperationOutcome = {\n local: { status: \"completed\", checkpointSha: sourceSha },\n upload: { status: \"not-attempted\", sourceSha },\n preview: { status: \"not-attempted\" },\n publication: {\n status:\n this.#publishDeploymentSource === null ? \"not-attempted\" : \"pending\",\n },\n };\n if (this.#publishDeploymentSource === null) return baseOutcome;\n\n try {\n const publication = await this.#publishCommittedNamespace(\n identity,\n sourceSha,\n );\n this.#clearPending(identity.login);\n return {\n ...baseOutcome,\n publication: {\n status: \"confirmed\",\n revision: publication.publicationSha,\n },\n };\n } catch {\n const pending: PendingPublication = {\n recoveryId: randomUUID(),\n operation,\n kind: \"ordinary-publication\",\n identity,\n ref,\n path,\n sourceSha,\n };\n this.#rememberPending(pending);\n return {\n ...baseOutcome,\n publication: {\n status: \"failed\",\n recoveryId: pending.recoveryId,\n },\n };\n }\n }\n\n async #publishDeploymentMetadata(pending: PendingPublication) {\n if (this.#publishDeploymentSource === null) {\n throw new DeploymentUnavailableError();\n }\n return this.#publishDeploymentSource(\n this.#repository,\n {\n remote: this.#runtime.remote,\n primaryBranch: this.#runtime.primaryBranch,\n sourceSha: pending.sourceSha,\n namespacePath: namespaceRelativePath(\n this.#runtime,\n pending.identity.login,\n ),\n commitIdentity: this.#runtime.commitIdentity,\n },\n async ({ path, repository }) => {\n const workspaceRuntime = this.#workspaceRuntime(path, repository);\n const mergedDocument = await diagnoseMetadataStep(\"metadata-read\", () =>\n readMetadataDocument(\n workspaceRuntime,\n pending.ref,\n this.#themeRegistry,\n ),\n );\n await diagnoseMetadataStep(\"metadata-write\", () =>\n writeMetadataDocument(workspaceRuntime, pending.ref, {\n ...mergedDocument,\n previewUrl: pending.previewUrl,\n updatedAt: pending.acceptedAt,\n }),\n );\n await diagnoseMetadataStep(\"metadata-commit\", () =>\n commitPath(\n repository,\n pending.path,\n `deploy: ${pending.ref.slug} (metadata)`,\n ),\n );\n },\n );\n }\n\n async #deploymentValue(\n pending: PendingPublication,\n publicationWarnings: readonly DeploymentWarningCode[] = [],\n outcome?: LifecycleOperationOutcome,\n ): Promise<DeploymentValue> {\n const warnings = [...publicationWarnings];\n return {\n deployed: true,\n ref: pending.ref,\n previewUrl: pending.previewUrl!,\n deploymentId: pending.deploymentId!,\n sourceSha: pending.sourceSha,\n readyState: pending.readyState!,\n ...(outcome === undefined ? {} : { outcome }),\n warning: publicationWarnings[0],\n ...(warnings.length === 0 ? {} : { warnings }),\n };\n }\n\n async deploy(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DeploymentValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parsePrototypeCommandInput(input);\n if (!this.#deploymentProvider) {\n throw new DeploymentUnavailableError();\n }\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n const { ref, path } = await this.#ownedPrototype(\n verifiedIdentity,\n normalizedInput,\n );\n await assertIdentityBranchReady(\n this.#repository,\n verifiedIdentity.login,\n );\n await assertPrototypeDirectory(this.#runtime, ref);\n const document = await readMetadataDocument(\n this.#runtime,\n ref,\n this.#themeRegistry,\n );\n const metadata = parsePrototypeMetadata(document, {\n themeRegistry: this.#themeRegistry,\n });\n if (metadata.authorLogin !== ref.login) {\n throw new PrototypeNotFoundError();\n }\n\n await commitPrototypePath(\n this.#repository,\n path,\n `deploy: ${ref.slug}`,\n );\n const sourceSha = await this.#headCommit();\n let sourcePush;\n try {\n sourcePush = await pushCommitToBranch(\n this.#repository,\n this.#runtime.remote,\n sourceSha,\n verifiedIdentity.login,\n true,\n );\n } catch (error) {\n if (error instanceof GitRepositoryError) {\n const pending: PendingPublication = {\n recoveryId: randomUUID(),\n operation: \"deploy\",\n kind: \"deployment-upload\",\n identity: verifiedIdentity,\n ref,\n path,\n sourceSha,\n };\n this.#rememberPending(pending);\n return {\n deployed: false,\n ref,\n sourceSha,\n warning: \"upload-unconfirmed\",\n outcome: {\n local: { status: \"completed\", checkpointSha: sourceSha },\n upload: {\n status: \"unconfirmed\",\n sourceSha,\n },\n preview: { status: \"not-attempted\" },\n publication: {\n status: \"pending\",\n recoveryId: pending.recoveryId,\n },\n },\n } satisfies DeploymentValue;\n }\n throw error;\n }\n if (sourcePush.remoteStatus !== \"pushed\") {\n throw new DeploymentSourcePushError();\n }\n\n let deployment;\n try {\n deployment = await this.#deploymentProvider!.deploy({\n applicationId: this.#applicationId!,\n login: verifiedIdentity.login,\n });\n } catch (error) {\n if (\n error instanceof DeploymentProviderError &&\n [\n \"timeout\",\n \"transport-failure\",\n \"invalid-response\",\n \"invalid-url\",\n ].includes(error.kind)\n ) {\n const pending: PendingPublication = {\n recoveryId: randomUUID(),\n operation: \"deploy\",\n kind: \"deployment-preview-unconfirmed\",\n identity: verifiedIdentity,\n ref,\n path,\n sourceSha,\n };\n this.#rememberPending(pending);\n return {\n deployed: false,\n ref,\n sourceSha,\n warning: \"preview-unconfirmed\",\n outcome: {\n local: { status: \"completed\", checkpointSha: sourceSha },\n upload: { status: \"confirmed\", sourceSha },\n preview: { status: \"unconfirmed\" },\n publication: { status: \"not-attempted\" },\n },\n } satisfies DeploymentValue;\n }\n throw error;\n }\n if (\n deployment.commitSha.toLowerCase() !== sourceSha ||\n ![\"READY\", \"QUEUED\", \"INITIALIZING\", \"BUILDING\"].includes(\n deployment.readyState,\n )\n ) {\n throw new DeploymentNotAcceptedError();\n }\n const previewUrl = new URL(\n getPrototypeUrl(ref).slice(1),\n `${deployment.url.replace(/\\/+$/, \"\")}/`,\n ).toString();\n const pending: PendingPublication = {\n recoveryId: randomUUID(),\n operation: \"deploy\",\n kind: \"deployment-publication\",\n identity: verifiedIdentity,\n ref,\n path,\n previewUrl,\n deploymentId: deployment.deploymentId,\n sourceSha,\n acceptedAt: new Date().toISOString(),\n readyState: deployment.readyState,\n };\n const acceptedOutcome: LifecycleOperationOutcome = {\n local: { status: \"completed\", checkpointSha: sourceSha },\n upload: { status: \"confirmed\", sourceSha },\n preview: {\n status: \"accepted\",\n previewUrl,\n deploymentId: deployment.deploymentId,\n },\n publication: { status: \"pending\" },\n };\n\n try {\n const publication = await this.#publishDeploymentMetadata(pending);\n this.#clearPending(verifiedIdentity.login);\n return this.#deploymentValue(\n pending,\n publication.cleanupFailed ? [\"publication-cleanup-failed\"] : [],\n {\n ...acceptedOutcome,\n publication: {\n status: \"confirmed\",\n revision: publication.publicationSha,\n },\n },\n );\n } catch (error) {\n // Keep the accepted deployment retryable for every publication\n // failure, including metadata preparation failures.\n this.#rememberPending(pending);\n return this.#deploymentValue(\n pending,\n [\n error instanceof DeploymentWorktreeError &&\n error.kind !== \"cleanup-failure\" &&\n error.kind !== \"metadata-failure\"\n ? \"primary-merge-failed\"\n : \"metadata-persistence-failed\",\n ...(error instanceof DeploymentWorktreeError &&\n error.cleanupFailed\n ? [\"publication-cleanup-failed\" as const]\n : []),\n ],\n {\n ...acceptedOutcome,\n publication: {\n status: \"failed\",\n recoveryId: pending.recoveryId,\n },\n },\n );\n }\n },\n );\n });\n }\n\n async getPendingRecovery(\n identity: BonfireIdentity,\n ): Promise<LifecycleResult<LifecycleRecoveryValue | null>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const pending = pendingPublications.get(\n this.#pendingKey(verifiedIdentity.login),\n );\n if (pending === undefined) return null;\n return this.#recoveryValue(pending, {\n local: { status: \"completed\", checkpointSha: pending.sourceSha },\n upload: {\n status:\n pending.kind === \"deployment-upload\" ? \"unconfirmed\" : \"confirmed\",\n sourceSha: pending.sourceSha,\n },\n preview:\n pending.kind === \"deployment-publication\"\n ? {\n status: \"accepted\",\n previewUrl: pending.previewUrl!,\n deploymentId: pending.deploymentId!,\n }\n : pending.kind === \"deployment-preview-unconfirmed\"\n ? { status: \"unconfirmed\" }\n : { status: \"not-attempted\" },\n publication: {\n status:\n pending.kind === \"deployment-upload\"\n ? \"pending\"\n : pending.kind === \"deployment-preview-unconfirmed\"\n ? \"not-attempted\"\n : \"failed\",\n ...(pending.kind === \"deployment-preview-unconfirmed\"\n ? {}\n : { recoveryId: pending.recoveryId }),\n },\n });\n });\n }\n\n async retryPendingPublication(\n identity: BonfireIdentity,\n recoveryId: string,\n ): Promise<LifecycleResult<LifecycleRecoveryValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const pending = pendingPublications.get(\n this.#pendingKey(verifiedIdentity.login),\n );\n if (pending === undefined || pending.recoveryId !== recoveryId) {\n throw new DeploymentUnavailableError();\n }\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n await assertIdentityBranchReady(\n this.#repository,\n verifiedIdentity.login,\n );\n if (pending.kind === \"deployment-preview-unconfirmed\") {\n throw new DeploymentUnavailableError();\n }\n let deploymentPending = pending;\n if (pending.kind === \"ordinary-publication\") {\n deploymentPending = {\n ...pending,\n sourceSha: await this.#headCommit(),\n };\n this.#rememberPending(deploymentPending);\n }\n if (pending.kind === \"deployment-upload\") {\n const remoteSource = await remoteBranchCommit(\n this.#repository,\n this.#runtime.remote,\n verifiedIdentity.login,\n );\n if (remoteSource !== pending.sourceSha) {\n const upload = await pushCommitToBranch(\n this.#repository,\n this.#runtime.remote,\n pending.sourceSha,\n verifiedIdentity.login,\n true,\n );\n if (upload.remoteStatus !== \"pushed\") {\n throw new DeploymentSourcePushError();\n }\n }\n if (!this.#deploymentProvider) {\n throw new DeploymentUnavailableError();\n }\n let deployment;\n try {\n deployment = await this.#deploymentProvider.deploy({\n applicationId: this.#applicationId!,\n login: verifiedIdentity.login,\n });\n } catch (error) {\n if (\n error instanceof DeploymentProviderError &&\n [\n \"timeout\",\n \"transport-failure\",\n \"invalid-response\",\n \"invalid-url\",\n ].includes(error.kind)\n ) {\n const uncertain = {\n ...pending,\n kind: \"deployment-preview-unconfirmed\" as const,\n };\n this.#rememberPending(uncertain);\n return this.#recoveryValue(uncertain, {\n local: {\n status: \"completed\",\n checkpointSha: pending.sourceSha,\n },\n upload: {\n status: \"confirmed\",\n sourceSha: pending.sourceSha,\n },\n preview: { status: \"unconfirmed\" },\n publication: { status: \"not-attempted\" },\n });\n }\n throw error;\n }\n if (\n deployment.commitSha.toLowerCase() !== pending.sourceSha ||\n ![\"READY\", \"QUEUED\", \"INITIALIZING\", \"BUILDING\"].includes(\n deployment.readyState,\n )\n ) {\n throw new DeploymentNotAcceptedError();\n }\n deploymentPending = {\n ...pending,\n kind: \"deployment-publication\",\n previewUrl: new URL(\n getPrototypeUrl(pending.ref).slice(1),\n `${deployment.url.replace(/\\/+$/, \"\")}/`,\n ).toString(),\n deploymentId: deployment.deploymentId,\n acceptedAt: new Date().toISOString(),\n readyState: deployment.readyState,\n };\n this.#rememberPending(deploymentPending);\n }\n const publication =\n deploymentPending.kind === \"deployment-publication\"\n ? await this.#publishDeploymentMetadata(deploymentPending)\n : await this.#publishCommittedNamespace(\n verifiedIdentity,\n deploymentPending.sourceSha,\n );\n this.#clearPending(verifiedIdentity.login);\n return this.#recoveryValue(deploymentPending, {\n local: {\n status: \"completed\",\n checkpointSha: deploymentPending.sourceSha,\n },\n upload: {\n status: \"confirmed\",\n sourceSha: deploymentPending.sourceSha,\n },\n preview:\n deploymentPending.kind === \"deployment-publication\"\n ? {\n status: \"accepted\",\n previewUrl: deploymentPending.previewUrl!,\n deploymentId: deploymentPending.deploymentId!,\n }\n : { status: \"not-attempted\" },\n publication: {\n status: \"confirmed\",\n revision: publication.publicationSha,\n },\n });\n },\n );\n });\n }\n\n /** Compatibility wrapper; recovery-ID retry is the implementation. */\n async retryPublish(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DeploymentValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n let normalizedInput: PrototypeCommandInput;\n try {\n normalizedInput = parsePrototypeCommandInput(input);\n } catch {\n return lifecycleFailure(\"invalid-input\");\n }\n const pending = pendingPublications.get(this.#pendingKey(identity.login));\n if (\n pending === undefined ||\n pending.kind !== \"deployment-publication\" ||\n pending.ref.login !== normalizedInput.ref.login ||\n pending.ref.slug !== normalizedInput.ref.slug\n ) {\n return lifecycleFailure(\"deployment-unavailable\");\n }\n const result = await this.retryPendingPublication(\n identity,\n pending.recoveryId,\n );\n if (!result.ok) return result;\n const current = pendingPublications.get(this.#pendingKey(identity.login));\n const completed = {\n ...pending,\n ...(current ?? {}),\n sourceSha: result.value.sourceSha,\n ...(result.value.previewUrl === undefined\n ? {}\n : { previewUrl: result.value.previewUrl }),\n ...(result.value.deploymentId === undefined\n ? {}\n : { deploymentId: result.value.deploymentId }),\n };\n return lifecycleSuccess(\n await this.#deploymentValue(completed, [], result.value.outcome),\n );\n }\n\n async save(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<SavePrototypeValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n await this.#prepareMutationBranch(verifiedIdentity.login);\n const { ref, path, directorySnapshot } =\n await this.#authorizedPrototype(verifiedIdentity, input);\n await assertPrototypeDirectory(this.#runtime, ref, directorySnapshot);\n await commitPrototypePath(\n this.#repository,\n path,\n `save: ${ref.slug}`,\n );\n return { saved: true } satisfies SavePrototypeValue;\n },\n );\n });\n }\n\n async discard(\n identity: BonfireIdentity,\n input: PrototypeCommandInput,\n ): Promise<LifecycleResult<DiscardPrototypeValue>> {\n if (this.#runtime.gitMode === \"manual\") {\n return lifecycleFailure(\"forbidden\");\n }\n\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n await this.#prepareMutationBranch(verifiedIdentity.login);\n const { ref, path, directorySnapshot } =\n await this.#authorizedPrototype(verifiedIdentity, input);\n await assertPrototypeDirectory(this.#runtime, ref, directorySnapshot);\n await discardPrototypePath(this.#repository, path);\n return { discarded: true } satisfies DiscardPrototypeValue;\n },\n );\n });\n }\n\n async duplicate(\n identity: BonfireIdentity,\n input: DuplicatePrototypeInput,\n ): Promise<LifecycleResult<DuplicatePrototypeValue>> {\n return resultFrom(async () => {\n const verifiedIdentity = await this.#verifiedIdentity(identity);\n const normalizedInput = parseDuplicatePrototypeInput(input);\n if (!(await this.#catalog.getSummary(normalizedInput.source))) {\n throw new PrototypeDuplicateError(\"source-not-found\");\n }\n const ref = destinationRef(verifiedIdentity, normalizedInput.title);\n\n return withRepositoryOperation(\n this.#runtime.repositoryRealPath,\n async () => {\n if (await this.#catalog.getSummary(ref)) {\n throw new PrototypeDuplicateError(\"collision\");\n }\n\n const branch =\n this.#runtime.gitMode === \"managed\"\n ? await this.#prepareMutationBranch(verifiedIdentity.login)\n : undefined;\n const prepared = await duplicatePrototype({\n paths: this.#runtime,\n source: normalizedInput.source,\n destination: ref,\n title: normalizedInput.title,\n description: normalizedInput.description,\n authorName: verifiedIdentity.name,\n themeRegistry: this.#themeRegistry,\n });\n await this.#prepareDestination(\n prepared.receipt,\n prepared.expectedFiles,\n {\n operation: \"duplicate\",\n repositoryRoot: this.#runtime.repositoryRoot,\n prototypeRoot: this.#runtime.prototypeRoot,\n prototypePath: prepared.destination,\n ref,\n source: normalizedInput.source,\n identity: verifiedIdentity,\n title: normalizedInput.title,\n description: normalizedInput.description,\n },\n );\n if (branch === undefined) {\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: \"manual\",\n } satisfies DuplicatePrototypeValue;\n }\n\n await commitPath(\n this.#repository,\n repositoryRelativePath(this.#runtime, ref),\n `init: ${ref.slug}`,\n );\n const push = await pushBranch(\n this.#repository,\n this.#runtime.remote,\n branch,\n );\n\n return {\n ref,\n url: getPrototypeUrl(ref),\n remoteStatus: push.remoteStatus,\n } satisfies DuplicatePrototypeValue;\n },\n );\n });\n }\n}\n"]}
|