@aviaratech/ai-delivery 0.3.44 → 0.3.46
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/CONTRIBUTING.md +8 -8
- package/README.md +1 -1
- package/dist/agentReadiness.test.js +7 -0
- package/dist/agentReadiness.test.js.map +2 -2
- package/dist/config/deliveryConfig.d.ts +0 -30
- package/dist/config/deliveryConfig.js +0 -2
- package/dist/config/deliveryConfig.js.map +2 -2
- package/dist/delivery/common.d.ts +0 -2
- package/dist/delivery/common.js +0 -14
- package/dist/delivery/common.js.map +2 -2
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +5 -8
- package/dist/errors.js.map +2 -2
- package/dist/fixtures/builderReady.d.ts +2 -0
- package/dist/fixtures/inertTarget.d.ts +4 -0
- package/dist/fixtures/issue63.d.ts +4 -0
- package/dist/github/client.js +1 -5
- package/dist/github/client.js.map +2 -2
- package/dist/github/nativeIssueMetadata.d.ts +0 -1
- package/dist/github/nativeIssueMetadata.js.map +2 -2
- package/dist/issue.js +8 -5
- package/dist/issue.js.map +2 -2
- package/dist/issueContract.d.ts +18 -1
- package/dist/issueContract.js +37 -8
- package/dist/issueContract.js.map +2 -2
- package/dist/issueContract.test.d.ts +2 -0
- package/dist/issueContract.test.js +29 -1
- package/dist/issueContract.test.js.map +2 -2
- package/dist/issueIntake.test.js +20 -0
- package/dist/issueIntake.test.js.map +2 -2
- package/dist/mcp/tools.d.ts +10 -0
- package/dist/pluginDoctor.test.js +1 -1
- package/dist/pluginDoctor.test.js.map +2 -2
- package/dist/pluginInstaller.js +7 -4
- package/dist/pluginInstaller.js.map +2 -2
- package/dist/pluginInstaller.test.js +38 -13
- package/dist/pluginInstaller.test.js.map +2 -2
- package/dist/pluginPackaging.test.js +1 -1
- package/dist/pluginPackaging.test.js.map +2 -2
- package/dist/pr.js +5 -1
- package/dist/pr.js.map +2 -2
- package/dist/pr.test.js +55 -0
- package/dist/pr.test.js.map +2 -2
- package/package.json +1 -1
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/cli.js +108 -108
- package/plugins/ai-delivery/runtime/package.json +1 -1
- package/plugins/ai-delivery/skills/ticket-design/SKILL.md +10 -10
package/dist/github/client.js
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
import { runStageCommand } from "../verification.js";
|
|
14
14
|
import {
|
|
15
15
|
DeliveryError,
|
|
16
|
+
ownData,
|
|
16
17
|
setMachineRequestDiagnostics,
|
|
17
18
|
getRateLimitDiagnostics
|
|
18
19
|
} from "../errors.js";
|
|
@@ -409,11 +410,6 @@ function buildClients(token, authSource, role, credentialSource, appActorLogin,
|
|
|
409
410
|
if (role === "author") authorGitTokens.set(clients, token);
|
|
410
411
|
return clients;
|
|
411
412
|
}
|
|
412
|
-
function ownData(value, name) {
|
|
413
|
-
if (typeof value !== "object" || value === null || types.isProxy(value) || Array.isArray(value)) return void 0;
|
|
414
|
-
const descriptor = Object.getOwnPropertyDescriptor(value, name);
|
|
415
|
-
return descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
416
|
-
}
|
|
417
413
|
function exactBranchProtectionAbsence(error) {
|
|
418
414
|
const response = ownData(error, "response");
|
|
419
415
|
return ownData(error, "status") === 404 && ownData(response, "status") === 404 && ownData(ownData(response, "data"), "message") === "Branch not protected";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/github/client.ts"],
|
|
4
|
-
"sourcesContent": ["import { createAppAuth } from '@octokit/auth-app';\nimport { graphql } from '@octokit/graphql';\nimport type { graphql as GraphQLType } from '@octokit/graphql';\nimport { Octokit } from '@octokit/rest';\nimport { closeSync, constants, fstatSync, openSync, readFileSync, readSync } from 'node:fs';\nimport { createPrivateKey } from 'node:crypto';\nimport { homedir } from 'node:os';\nimport { types } from 'node:util';\n\nimport type { DeliveryConfig, DeliveryRole, LoadedDeliverySettings } from '../config/deliveryConfig.js';\n\nimport {\n appCredentialSource,\n privateKeyVariable,\n resolveDeliveryRoleCredentials,\n type ConfiguredApp,\n} from '../config/deliveryConfig.js';\nimport { runStageCommand } from '../verification.js';\nimport {\n DeliveryError,\n setMachineRequestDiagnostics,\n getRateLimitDiagnostics,\n type RateLimitDiagnostics,\n type SafeMachineRequestDiagnostics,\n} from '../errors.js';\nimport {\n assertSupportedAuthorHost,\n machineAuthorEligible,\n withMachineAuthorCredential,\n MACHINE_AUTH_ENV_NAMES,\n} from './machineAuth.js';\n\nexport interface GitHubClients {\n authSource: 'app' | 'personal';\n credentialSource?: string;\n effectiveContentsPermission?: DeliveryPermission | 'admin';\n role: DeliveryRole;\n appActorLogin?: (signal?: AbortSignal) => Promise<string>;\n authenticatedAuthor?: (signal?: AbortSignal) => Promise<{ actorLogin: string; credentialIdentity: string }>;\n graphql: typeof GraphQLType;\n rest: Octokit;\n /** Last positively identified request limit; retained across legacy helper error wrapping. */\n rateLimitObservation?: () => RateLimitDiagnostics | undefined;\n}\n\nconst authorGitTokens = new WeakMap<GitHubClients, string>();\nconst machineClients = new WeakSet<GitHubClients>();\nconst machineProtectionAbsence = new WeakMap<\n DeliveryError,\n { clients: GitHubClients; owner: string; repo: string; branch: string }\n>();\ninterface MachineSelection {\n env: NodeJS.ProcessEnv;\n signal: AbortSignal | undefined;\n selectors: string;\n}\nconst machineAuthorSelections = new WeakMap<GitHubClients, MachineSelection>();\nconst resolvedMachineAuthors = new WeakMap<DeliveryConfig['roles'], MachineSelection & { clients: GitHubClients }>();\n\n/** Keep repository discovery and command execution on one resolved account. */\nexport function retainMachineAuthorForConfiguration(\n config: Pick<DeliveryConfig, 'roles'>,\n clients: GitHubClients,\n signal?: AbortSignal,\n): void {\n const selection = machineAuthorSelections.get(clients);\n if (selection !== undefined) {\n if (selection.signal !== signal)\n throw new DeliveryError('Machine GitHub session command context changed; resolve the command again.');\n resolvedMachineAuthors.set(config.roles, { clients, ...selection });\n }\n}\n\nfunction sessionSelectors(env: NodeJS.ProcessEnv): string {\n return JSON.stringify(MACHINE_AUTH_ENV_NAMES.map((name) => [name, env[name]]));\n}\n\n/** Pass the selected author token only to the operation that needs Git HTTP auth. */\nexport async function withAuthorGitToken<T>(\n clients: GitHubClients,\n callback: (token: string) => Promise<T> | T,\n): Promise<T> {\n const token = clients.role === 'author' ? authorGitTokens.get(clients) : undefined;\n if (!token) throw new DeliveryError('Git push requires the selected author credential token.');\n return callback(token);\n}\n\nexport type DeliveryPermission = 'read' | 'write';\n\nexport function assertDeliveryRolePermissions(input: {\n additional?: Readonly<Record<string, DeliveryPermission>>;\n permissions: unknown;\n role: DeliveryRole;\n}): void {\n if (typeof input.permissions !== 'object' || input.permissions === null || Array.isArray(input.permissions)) {\n throw new DeliveryError(`GitHub App ${input.role} role did not return installation permissions.`);\n }\n const permissions = input.permissions as Record<string, unknown>;\n const required =\n input.role === 'author'\n ? { contents: 'write', issues: 'write', organization_projects: 'write', pull_requests: 'write' }\n : { contents: 'read', pull_requests: 'write' };\n for (const [name, level] of [...Object.entries(required), ...Object.entries(input.additional ?? {})]) {\n const actual = permissions[name];\n if (actual !== 'admin' && actual !== 'write' && (level === 'write' || actual !== 'read')) {\n throw new DeliveryError(`GitHub App ${input.role} role lacks required ${name}:${level} permission.`);\n }\n }\n}\n\n/** The author role may use a personal token only after an explicit operator opt-in. */\nexport async function createDeliveryGitHubClients(input: {\n config: Pick<DeliveryConfig, 'roles'> & Pick<LoadedDeliverySettings, 'credentialKeyReferences'>;\n env?: NodeJS.ProcessEnv;\n identity: string;\n personalAuth?: { enabled: true; token?: string };\n selectedAuthor?: GitHubClients;\n additionalPermissions?: Readonly<Record<string, DeliveryPermission>>;\n role: DeliveryRole;\n signal?: AbortSignal;\n}): Promise<GitHubClients> {\n input.signal?.throwIfAborted();\n const env = input.env ?? process.env;\n const selected = input.config.roles[input.role];\n const retained = input.role === 'author' ? resolvedMachineAuthors.get(input.config.roles) : undefined;\n if (retained !== undefined) {\n // A command that discovered its repository as account A must not acquire\n // a newly supplied token/profile and then operate as account B.\n if (\n selected.authSource !== 'personal' ||\n input.identity.trim().toLowerCase() !== selected.identity.toLowerCase() ||\n !machineAuthorEligible(selected.credentialEnv.token, env) ||\n retained.env !== env ||\n retained.signal !== input.signal ||\n retained.selectors !== sessionSelectors(env)\n )\n throw new DeliveryError(\n 'Machine GitHub session environment changed after repository selection; resolve the command again.',\n );\n assertSupportedAuthorHost(env);\n return retained.clients;\n }\n if (selected.authSource === 'personal') {\n if (input.role !== 'author' || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {\n throw new DeliveryError('Personal author operation requires the configured author identity.');\n }\n assertSupportedAuthorHost(env);\n if (machineAuthorEligible(selected.credentialEnv.token, env)) {\n const selection: MachineSelection = { env, signal: input.signal, selectors: sessionSelectors(env) };\n return withMachineAuthorCredential(env, input.signal, async (token, session) => {\n const clients = personalClients(token, `gh:github.com:${session.executable}`, input.signal, session.login);\n await clients.authenticatedAuthor!(input.signal);\n machineAuthorSelections.set(clients, selection);\n return clients;\n });\n }\n const token = env[selected.credentialEnv.token]?.trim();\n if (!token) {\n throw new DeliveryError(`Missing personal author token in ${selected.credentialEnv.token}.`);\n }\n return personalClients(token, `env:${selected.credentialEnv.token}`, input.signal);\n }\n if (input.personalAuth !== undefined) {\n if (\n input.personalAuth.enabled !== true ||\n input.role !== 'author' ||\n input.identity.trim().toLowerCase() !== 'personal'\n ) {\n throw new DeliveryError('Personal-token auth requires the explicit personal author identity.');\n }\n assertSupportedAuthorHost(env);\n const token = (input.personalAuth.token ?? env.GH_TOKEN ?? env.GITHUB_TOKEN)?.trim();\n if (!token) throw new DeliveryError('Explicit personal-token auth requested but no token was supplied.');\n const source =\n input.personalAuth.token !== undefined\n ? 'explicit-personal-token'\n : env.GH_TOKEN !== undefined\n ? 'env:GH_TOKEN'\n : 'env:GITHUB_TOKEN';\n return personalClients(token, source, input.signal);\n }\n\n if (input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {\n throw new DeliveryError(`GitHub ${input.role} operation requires the configured ${input.role} identity.`);\n }\n const credentials = resolveDeliveryRoleCredentials({ config: input.config, env, role: input.role });\n const otherRole: DeliveryRole = input.role === 'author' ? 'reviewer' : 'author';\n const personalAuthorSelected =\n input.role === 'reviewer' &&\n input.selectedAuthor?.role === 'author' &&\n input.selectedAuthor.authSource === 'personal';\n if (!personalAuthorSelected && input.config.roles[otherRole].authSource !== 'personal') {\n const otherRoleConfig = input.config.roles[otherRole];\n // Explicit profiles compare only other-role metadata. Doctor must not need\n // another identity's key reference or resolve its credential source.\n const other =\n credentials.profile === undefined\n ? resolveDeliveryRoleCredentials({ config: input.config, env, role: otherRole })\n : 'appId' in otherRoleConfig\n ? {\n appId: String(otherRoleConfig.appId),\n installationId: otherRoleConfig.installationId,\n privateKeyPath: undefined,\n }\n : {\n appId: env[otherRoleConfig.credentialEnv.appId]?.trim(),\n installationId: Number(env[otherRoleConfig.credentialEnv.installationId]),\n privateKeyPath: undefined,\n };\n if (\n credentials.appId === other.appId ||\n credentials.installationId === other.installationId ||\n (credentials.privateKeyPath !== undefined && credentials.privateKeyPath === other.privateKeyPath)\n ) {\n throw new DeliveryError('Author and reviewer must use distinct GitHub App credentials.');\n }\n }\n let privateKey: string;\n if (credentials.profile !== undefined) {\n privateKey = await selectedPrivateKey(credentials.profile, env, input.config, input.signal);\n } else {\n try {\n privateKey = readFileSync(credentials.privateKeyPath!, 'utf8');\n } catch {\n throw new DeliveryError(`GitHub App private key for ${input.role} role is unavailable.`);\n }\n }\n try {\n const auth = createAppAuth({\n appId: credentials.appId,\n privateKey,\n ...(input.signal === undefined ? {} : { request: new Octokit({ request: { signal: input.signal } }).request }),\n });\n const result = await auth({ installationId: credentials.installationId, type: 'installation' });\n if (typeof result.token !== 'string' || !result.token.startsWith('ghs_')) {\n throw new DeliveryError(`GitHub ${input.role} role did not receive an App installation token.`);\n }\n assertDeliveryRolePermissions({\n ...(input.additionalPermissions === undefined ? {} : { additional: input.additionalPermissions }),\n permissions: result.permissions,\n role: input.role,\n });\n const appActorLogin =\n input.role === 'reviewer'\n ? async (signal?: AbortSignal) => {\n const requestSignal = signal ?? input.signal;\n try {\n const app = await new Octokit({\n auth: (await auth({ type: 'app' })).token,\n ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),\n }).rest.apps.getAuthenticated();\n if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {\n throw new DeliveryError('Reviewer GitHub App identity did not match its configured App ID.');\n }\n const actor = `${app.data.slug}[bot]`;\n if (credentials.profile !== undefined && actor !== credentials.profile.actorLogin)\n throw new DeliveryError('Reviewer GitHub App actor did not match its configured actorLogin.');\n return actor;\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError('Reviewer GitHub App actor lookup failed.');\n }\n }\n : undefined;\n const authenticatedAuthor =\n input.role === 'author'\n ? async (signal?: AbortSignal) => {\n const requestSignal = signal ?? input.signal;\n try {\n const app = await new Octokit({\n auth: (await auth({ type: 'app' })).token,\n ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),\n }).rest.apps.getAuthenticated();\n if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {\n throw new DeliveryError('Author GitHub App identity did not match its configured App ID.');\n }\n return {\n actorLogin: `${app.data.slug}[bot]`,\n credentialIdentity: `app:${String(app.data.id)}:installation:${credentials.installationId}`,\n };\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError('Author GitHub App actor lookup failed.');\n }\n }\n : undefined;\n return buildClients(\n result.token,\n 'app',\n input.role,\n `app:${credentials.appId}:installation:${credentials.installationId}`,\n appActorLogin,\n authenticatedAuthor,\n (result.permissions as Record<string, DeliveryPermission | 'admin'>).contents,\n input.signal,\n );\n } catch (error) {\n input.signal?.throwIfAborted();\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError(`GitHub App authentication failed for ${input.role} role.`);\n }\n}\n\n/** Selected-source output stays in memory; the existing runner owns command cleanup. */\nasync function selectedPrivateKey(\n profile: ConfiguredApp,\n env: NodeJS.ProcessEnv,\n config: Pick<DeliveryConfig, 'roles'> & Pick<LoadedDeliverySettings, 'credentialKeyReferences'>,\n signal?: AbortSignal,\n): Promise<string> {\n const source = appCredentialSource(profile);\n const failure = (reason: string) =>\n new DeliveryError(`Reviewer ${profile.identity} credential source ${source.type}: ${reason}`);\n let bytes: Buffer;\n try {\n signal?.throwIfAborted();\n if (source.type === 'env') {\n const value = env[privateKeyVariable(profile)];\n if (!value) throw failure('selected variable is missing or empty; configure this identity.');\n if (Buffer.byteLength(value) > 64 * 1024) throw failure('response exceeds 64 KiB.');\n bytes = Buffer.from(value);\n } else if (source.type === 'file') {\n const fd = openSync(source.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const stat = fstatSync(fd);\n if (\n !stat.isFile() ||\n (stat.mode & 0o7777) !== 0o600 ||\n stat.nlink !== 1 ||\n (process.getuid !== undefined && stat.uid !== process.getuid())\n )\n throw failure('key file must be a regular, owned, single-link file with mode 0600.');\n const buffer = Buffer.alloc(64 * 1024 + 1);\n let size = 0;\n for (;;) {\n const read = readSync(fd, buffer, size, buffer.length - size, null);\n if (read === 0) break;\n size += read;\n if (size === buffer.length) throw failure('response exceeds 64 KiB.');\n }\n bytes = buffer.subarray(0, size);\n } finally {\n closeSync(fd);\n }\n } else {\n if (process.platform === 'win32')\n throw failure('command sources currently require a POSIX process supervisor; use env on Windows.');\n const commandEnv: NodeJS.ProcessEnv = {};\n const forbidden = new Set([\n ...(config.credentialKeyReferences ?? []),\n ...Object.values(config.roles).flatMap((role) =>\n 'credentialEnv' in role\n ? Object.values(role.credentialEnv)\n : appCredentialSource(role).type === 'env'\n ? [privateKeyVariable(role)]\n : [],\n ),\n ]);\n for (const name of [\n 'HOME',\n 'USER',\n 'LOGNAME',\n 'PATH',\n 'LANG',\n 'LC_ALL',\n 'TMPDIR',\n 'TEMP',\n 'TMP',\n 'SystemRoot',\n 'USERPROFILE',\n 'APPDATA',\n 'LOCALAPPDATA',\n ]) {\n if (forbidden.has(name)) throw failure('credential reference conflicts with an implicit OS selector.');\n if (env[name] !== undefined) commandEnv[name] = env[name];\n }\n for (const name of source.env ?? []) {\n if (\n forbidden.has(name) ||\n /^(?:NODE_|NPM_|DYLD_|LD_|BASH_|GIT_|GH_PRIVATE_KEY)/u.test(name) ||\n ['ENV', 'SHELLOPTS', 'CDPATH'].includes(name)\n )\n throw failure('helper environment reference conflicts with author/key or execution selectors.');\n if (env[name] === undefined) throw failure('a configured helper environment reference is missing.');\n commandEnv[name] = env[name];\n }\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), 30_000);\n let cleanupFailed = false;\n try {\n bytes = await runStageCommand(\n env.HOME ?? homedir(),\n source.argv,\n signal === undefined ? timeout.signal : AbortSignal.any([signal, timeout.signal]),\n undefined,\n undefined,\n {\n environment: commandEnv,\n cwd: env.HOME ?? homedir(),\n maxCapturedOutputBytes: 64 * 1024,\n stdoutOnly: true,\n failedOutput: () => '',\n onCleanupFailure: () => {\n cleanupFailed = true;\n },\n },\n );\n } catch {\n throw failure(\n cleanupFailed\n ? 'helper failed and owned process cleanup is unverified; reconcile before retrying.'\n : timeout.signal.aborted\n ? 'helper response timed out; verify the selected command.'\n : signal?.aborted\n ? 'helper request cancelled.'\n : 'helper failed; verify its executable, access and bounded output.',\n );\n } finally {\n clearTimeout(timer);\n }\n }\n if (bytes.length === 0 || bytes.length > 64 * 1024) throw failure('response is empty or exceeds 64 KiB.');\n let pem = bytes.toString('utf8');\n if (!Buffer.from(pem).equals(bytes)) throw failure('response must be valid UTF-8.');\n if (source.type !== 'file' && source.encoding === 'base64') {\n const encoded = pem.trim();\n if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded))\n throw failure('response must be canonical base64.');\n const decoded = Buffer.from(encoded, 'base64');\n if (decoded.toString('base64') !== encoded) throw failure('response must be canonical base64.');\n pem = decoded.toString('utf8');\n if (!Buffer.from(pem).equals(decoded)) throw failure('decoded response must be UTF-8 PEM.');\n }\n if (\n !/^-----BEGIN (?:RSA )?PRIVATE KEY-----\\r?\\n[\\s\\S]+\\r?\\n-----END (?:RSA )?PRIVATE KEY-----\\s*$/u.test(pem) ||\n createPrivateKey(pem).asymmetricKeyType !== 'rsa'\n )\n throw failure('response must be an unencrypted RSA private key in PEM format.');\n signal?.throwIfAborted();\n return pem;\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw failure('selected key is unavailable or malformed; verify this source.');\n }\n}\n\nfunction personalClients(\n token: string,\n credentialSource: string,\n signal?: AbortSignal,\n machineLogin?: string,\n): GitHubClients {\n if (!/^[A-Za-z0-9_-]{1,4096}$/u.test(token))\n throw new DeliveryError('Selected personal author token is malformed; verify the explicit credential.');\n if (machineLogin !== undefined && (credentialSource.includes(token) || machineLogin.includes(token)))\n throw new DeliveryError('Machine GitHub session readback is unsafe.');\n return buildClients(\n token,\n 'personal',\n 'author',\n credentialSource,\n undefined,\n async (requestSignal?: AbortSignal) => {\n const selectedSignal = requestSignal ?? signal;\n try {\n const user = (\n await new Octokit({\n auth: token,\n ...(machineLogin === undefined ? {} : { log: { debug() {}, info() {}, warn() {}, error() {} } }),\n ...(selectedSignal === undefined ? {} : { request: { signal: selectedSignal } }),\n }).rest.users.getAuthenticated()\n ).data;\n if (!Number.isSafeInteger(user.id) || user.id <= 0 || !user.login) {\n throw new DeliveryError('Personal author identity readback is incomplete.');\n }\n if (\n machineLogin !== undefined &&\n (user.type !== 'User' ||\n user.login.toLowerCase() !== machineLogin.toLowerCase() ||\n !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u.test(user.login) ||\n user.login.includes(token))\n )\n throw new DeliveryError('Machine GitHub session identity does not match the selected active account.');\n return { actorLogin: user.login, credentialIdentity: `user:${String(user.id)}` };\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n if ((error as { status?: number }).status === 401) {\n throw new DeliveryError(\n machineLogin === undefined\n ? 'Configured personal author token is invalid or expired; refresh the selected token.'\n : 'Machine GitHub session is invalid or expired; verify the selected github.com account.',\n );\n }\n throw new DeliveryError('Personal author identity readback failed.');\n }\n },\n undefined,\n signal,\n machineLogin !== undefined,\n );\n}\n\nfunction buildClients(\n token: string,\n authSource: GitHubClients['authSource'],\n role: DeliveryRole,\n credentialSource: string,\n appActorLogin?: GitHubClients['appActorLogin'],\n authenticatedAuthor?: GitHubClients['authenticatedAuthor'],\n effectiveContentsPermission?: GitHubClients['effectiveContentsPermission'],\n signal?: AbortSignal,\n machineSession = false,\n): GitHubClients {\n const rest = new Octokit({\n auth: token,\n ...(machineSession ? { log: { debug() {}, info() {}, warn() {}, error() {} } } : {}),\n ...(signal === undefined ? {} : { request: { signal } }),\n });\n const rawGraphql = graphql.defaults({\n headers: { authorization: `token ${token}` },\n ...(signal === undefined ? {} : { request: { signal } }),\n });\n let observedRateLimit: RateLimitDiagnostics | undefined;\n const observeRateLimit = (error: unknown, graphqlFailure = false) => {\n observedRateLimit = getRateLimitDiagnostics(error, graphqlFailure) ?? observedRateLimit;\n };\n rest.hook.error('request', (error) => {\n observeRateLimit(error);\n throw error;\n });\n if (machineSession)\n rest.hook.error('request', (error, options) => {\n const safe = safeMachineRequestError(error, 'rest.request', restMachineEndpoint(options));\n const target = branchProtectionTarget(options);\n const responseTarget = branchProtectionTarget({ method: 'GET', url: ownData(ownData(error, 'response'), 'url') });\n if (\n target &&\n responseTarget &&\n target.owner.toLowerCase() === responseTarget.owner.toLowerCase() &&\n target.repo.toLowerCase() === responseTarget.repo.toLowerCase() &&\n target.branch === responseTarget.branch &&\n exactBranchProtectionAbsence(error)\n )\n machineProtectionAbsence.set(safe, { clients, ...target });\n throw safe;\n });\n const clients: GitHubClients = {\n authSource,\n credentialSource,\n ...(effectiveContentsPermission ? { effectiveContentsPermission } : {}),\n role,\n ...(appActorLogin ? { appActorLogin } : {}),\n ...(authenticatedAuthor ? { authenticatedAuthor } : {}),\n graphql: new Proxy(rawGraphql, {\n apply(target, receiver, args: unknown[]) {\n return (Reflect.apply(target, receiver, args) as Promise<unknown>).catch((error: unknown) => {\n observeRateLimit(error, true);\n throw machineSession ? safeMachineRequestError(error, 'graphql.request', 'graphql') : error;\n });\n },\n }),\n rest,\n rateLimitObservation: () => observedRateLimit,\n };\n if (machineSession) machineClients.add(clients);\n if (role === 'author') authorGitTokens.set(clients, token);\n return clients;\n}\n\nfunction ownData(value: unknown, name: string): unknown {\n if (typeof value !== 'object' || value === null || types.isProxy(value) || Array.isArray(value)) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n return descriptor && 'value' in descriptor ? descriptor.value : undefined;\n}\n\nfunction exactBranchProtectionAbsence(error: unknown): boolean {\n const response = ownData(error, 'response');\n return (\n ownData(error, 'status') === 404 &&\n ownData(response, 'status') === 404 &&\n ownData(ownData(response, 'data'), 'message') === 'Branch not protected'\n );\n}\n\nfunction branchProtectionTarget(options: unknown): { owner: string; repo: string; branch: string } | undefined {\n const url = ownData(options, 'url');\n if (ownData(options, 'method') !== 'GET' || typeof url !== 'string' || url.length > 1024 || /[^\\x21-\\x7e]/u.test(url))\n return undefined;\n let path: string;\n if (url.startsWith('/')) {\n if (ownData(options, 'baseUrl') !== 'https://api.github.com' || /[?#]/u.test(url)) return undefined;\n path = url;\n } else {\n try {\n const parsed = new URL(url);\n if (\n parsed.origin !== 'https://api.github.com' ||\n parsed.username ||\n parsed.password ||\n parsed.search ||\n parsed.hash\n )\n return undefined;\n path = parsed.pathname;\n } catch {\n return undefined;\n }\n }\n let owner: unknown, repo: unknown, branch: unknown;\n if (path === '/repos/{owner}/{repo}/branches/{branch}/protection') {\n owner = ownData(options, 'owner');\n repo = ownData(options, 'repo');\n branch = ownData(options, 'branch');\n } else {\n const match = /^\\/repos\\/([^/]+)\\/([^/]+)\\/branches\\/(.+)\\/protection$/u.exec(path);\n if (!match) return undefined;\n try {\n [owner, repo, branch] = match.slice(1).map((part) => decodeURIComponent(part));\n } catch {\n return undefined;\n }\n }\n if (\n typeof owner !== 'string' ||\n !/^[A-Za-z0-9_-]{1,100}$/u.test(owner) ||\n typeof repo !== 'string' ||\n !/^[A-Za-z0-9_.-]{1,100}$/u.test(repo) ||\n typeof branch !== 'string' ||\n !branch.length ||\n branch.length > 1024 ||\n /[^\\x21-\\x7e]/u.test(branch)\n )\n return undefined;\n return { owner, repo, branch };\n}\n\n/** Internal read-only predicate: machine absence never comes from copied error fields. */\nexport function hasBranchProtectionAbsence(\n error: unknown,\n clients: GitHubClients,\n repository: { owner: string; repo: string },\n branch: string,\n): boolean {\n if (!machineClients.has(clients)) return exactBranchProtectionAbsence(error);\n if (typeof error !== 'object' || error === null || types.isProxy(error)) return false;\n const target = machineProtectionAbsence.get(error as DeliveryError);\n return (\n target?.clients === clients &&\n target.owner.toLowerCase() === repository.owner.toLowerCase() &&\n target.repo.toLowerCase() === repository.repo.toLowerCase() &&\n target.branch === branch\n );\n}\n\nfunction restMachineEndpoint(options: unknown): SafeMachineRequestDiagnostics['endpoint'] {\n const method = ownData(options, 'method'),\n url = ownData(options, 'url');\n if (typeof method !== 'string' || typeof url !== 'string' || url.length > 1024 || /[^\\x21-\\x7e]/u.test(url))\n return 'UNKNOWN';\n let path: string;\n if (url.startsWith('/')) {\n const base = ownData(options, 'baseUrl');\n if (base !== 'https://api.github.com') return 'UNKNOWN';\n path = url.split(/[?#]/u)[0]!;\n } else {\n try {\n const parsed = new URL(url);\n if (parsed.origin !== 'https://api.github.com' || parsed.username || parsed.password) return 'UNKNOWN';\n path = parsed.pathname;\n } catch {\n return 'UNKNOWN';\n }\n }\n const prefix = '/repos/[^/]{1,100}/[^/]{1,100}';\n const number = '(?:[0-9]{1,20}|\\\\{pull_number\\\\})';\n const routes: readonly [string, RegExp, SafeMachineRequestDiagnostics['endpoint']][] = [\n ['PUT', new RegExp(`^${prefix}/pulls/${number}/merge$`, 'u'), 'pulls.merge'],\n ['GET', new RegExp(`^${prefix}/pulls/${number}$`, 'u'), 'pulls.get'],\n ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews$`, 'u'), 'pulls.listReviews'],\n ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews/(?:[0-9]{1,20}|\\\\{review_id\\\\})$`, 'u'), 'pulls.getReview'],\n ['GET', new RegExp(`^${prefix}/git/commits/[^/]{1,100}$`, 'u'), 'git.getCommit'],\n ['GET', new RegExp(`^${prefix}/git/ref/.{1,300}$`, 'u'), 'git.getRef'],\n ['GET', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\\\{issue_number\\\\})$`, 'u'), 'issues.get'],\n ['PATCH', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\\\{issue_number\\\\})$`, 'u'), 'issues.update'],\n ];\n return routes.find(([verb, pattern]) => verb === method && pattern.test(path))?.[2] ?? 'UNKNOWN';\n}\n\nfunction safeMachineRequestError(\n error: unknown,\n phase: 'rest.request' | 'graphql.request',\n endpoint: SafeMachineRequestDiagnostics['endpoint'],\n): DeliveryError {\n const status = ownData(error, 'status');\n const safe = new DeliveryError(\n status === 401\n ? 'Machine GitHub session is invalid or expired; verify the selected github.com account.'\n : status === 403 || status === 404\n ? 'Machine GitHub session cannot access the selected repository or operation; verify its existing permissions.'\n : 'Machine GitHub request failed; verify the selected account and repository access.',\n );\n if (typeof status === 'number' && Number.isSafeInteger(status) && status >= 400 && status <= 599)\n Object.assign(safe, { status });\n const headers = ownData(error, 'headers') ?? ownData(ownData(error, 'response'), 'headers');\n setMachineRequestDiagnostics(safe, {\n phase,\n endpoint,\n status,\n code: ownData(error, 'code'),\n requestId: ownData(headers, 'x-github-request-id'),\n retryAfter: ownData(headers, 'retry-after'),\n resetAt: ownData(headers, 'x-ratelimit-reset'),\n remaining: ownData(headers, 'x-ratelimit-remaining'),\n });\n return safe;\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,qBAAqB;AAC9B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SAAS,wBACP,OACA,OACA,UACe;AACf,QAAM,SAAS,QAAQ,OAAO,QAAQ;AACtC,QAAM,OAAO,IAAI;AAAA,IACf,WAAW,MACP,0FACA,WAAW,OAAO,WAAW,MAC3B,gHACA;AAAA,EACR;AACA,MAAI,OAAO,WAAW,YAAY,OAAO,cAAc,MAAM,KAAK,UAAU,OAAO,UAAU;AAC3F,WAAO,OAAO,MAAM,EAAE,OAAO,CAAC;AAChC,QAAM,UAAU,QAAQ,OAAO,SAAS,KAAK,QAAQ,QAAQ,OAAO,UAAU,GAAG,SAAS;AAC1F,+BAA6B,MAAM;AAAA,IACjC;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM,QAAQ,OAAO,MAAM;AAAA,IAC3B,WAAW,QAAQ,SAAS,qBAAqB;AAAA,IACjD,YAAY,QAAQ,SAAS,aAAa;AAAA,IAC1C,SAAS,QAAQ,SAAS,mBAAmB;AAAA,IAC7C,WAAW,QAAQ,SAAS,uBAAuB;AAAA,EACrD,CAAC;AACD,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["import { createAppAuth } from '@octokit/auth-app';\nimport { graphql } from '@octokit/graphql';\nimport type { graphql as GraphQLType } from '@octokit/graphql';\nimport { Octokit } from '@octokit/rest';\nimport { closeSync, constants, fstatSync, openSync, readFileSync, readSync } from 'node:fs';\nimport { createPrivateKey } from 'node:crypto';\nimport { homedir } from 'node:os';\nimport { types } from 'node:util';\n\nimport type { DeliveryConfig, DeliveryRole, LoadedDeliverySettings } from '../config/deliveryConfig.js';\n\nimport {\n appCredentialSource,\n privateKeyVariable,\n resolveDeliveryRoleCredentials,\n type ConfiguredApp,\n} from '../config/deliveryConfig.js';\nimport { runStageCommand } from '../verification.js';\nimport {\n DeliveryError,\n ownData,\n setMachineRequestDiagnostics,\n getRateLimitDiagnostics,\n type RateLimitDiagnostics,\n type SafeMachineRequestDiagnostics,\n} from '../errors.js';\nimport {\n assertSupportedAuthorHost,\n machineAuthorEligible,\n withMachineAuthorCredential,\n MACHINE_AUTH_ENV_NAMES,\n} from './machineAuth.js';\n\nexport interface GitHubClients {\n authSource: 'app' | 'personal';\n credentialSource?: string;\n effectiveContentsPermission?: DeliveryPermission | 'admin';\n role: DeliveryRole;\n appActorLogin?: (signal?: AbortSignal) => Promise<string>;\n authenticatedAuthor?: (signal?: AbortSignal) => Promise<{ actorLogin: string; credentialIdentity: string }>;\n graphql: typeof GraphQLType;\n rest: Octokit;\n /** Last positively identified request limit; retained across legacy helper error wrapping. */\n rateLimitObservation?: () => RateLimitDiagnostics | undefined;\n}\n\nconst authorGitTokens = new WeakMap<GitHubClients, string>();\nconst machineClients = new WeakSet<GitHubClients>();\nconst machineProtectionAbsence = new WeakMap<\n DeliveryError,\n { clients: GitHubClients; owner: string; repo: string; branch: string }\n>();\ninterface MachineSelection {\n env: NodeJS.ProcessEnv;\n signal: AbortSignal | undefined;\n selectors: string;\n}\nconst machineAuthorSelections = new WeakMap<GitHubClients, MachineSelection>();\nconst resolvedMachineAuthors = new WeakMap<DeliveryConfig['roles'], MachineSelection & { clients: GitHubClients }>();\n\n/** Keep repository discovery and command execution on one resolved account. */\nexport function retainMachineAuthorForConfiguration(\n config: Pick<DeliveryConfig, 'roles'>,\n clients: GitHubClients,\n signal?: AbortSignal,\n): void {\n const selection = machineAuthorSelections.get(clients);\n if (selection !== undefined) {\n if (selection.signal !== signal)\n throw new DeliveryError('Machine GitHub session command context changed; resolve the command again.');\n resolvedMachineAuthors.set(config.roles, { clients, ...selection });\n }\n}\n\nfunction sessionSelectors(env: NodeJS.ProcessEnv): string {\n return JSON.stringify(MACHINE_AUTH_ENV_NAMES.map((name) => [name, env[name]]));\n}\n\n/** Pass the selected author token only to the operation that needs Git HTTP auth. */\nexport async function withAuthorGitToken<T>(\n clients: GitHubClients,\n callback: (token: string) => Promise<T> | T,\n): Promise<T> {\n const token = clients.role === 'author' ? authorGitTokens.get(clients) : undefined;\n if (!token) throw new DeliveryError('Git push requires the selected author credential token.');\n return callback(token);\n}\n\nexport type DeliveryPermission = 'read' | 'write';\n\nexport function assertDeliveryRolePermissions(input: {\n additional?: Readonly<Record<string, DeliveryPermission>>;\n permissions: unknown;\n role: DeliveryRole;\n}): void {\n if (typeof input.permissions !== 'object' || input.permissions === null || Array.isArray(input.permissions)) {\n throw new DeliveryError(`GitHub App ${input.role} role did not return installation permissions.`);\n }\n const permissions = input.permissions as Record<string, unknown>;\n const required =\n input.role === 'author'\n ? { contents: 'write', issues: 'write', organization_projects: 'write', pull_requests: 'write' }\n : { contents: 'read', pull_requests: 'write' };\n for (const [name, level] of [...Object.entries(required), ...Object.entries(input.additional ?? {})]) {\n const actual = permissions[name];\n if (actual !== 'admin' && actual !== 'write' && (level === 'write' || actual !== 'read')) {\n throw new DeliveryError(`GitHub App ${input.role} role lacks required ${name}:${level} permission.`);\n }\n }\n}\n\n/** The author role may use a personal token only after an explicit operator opt-in. */\nexport async function createDeliveryGitHubClients(input: {\n config: Pick<DeliveryConfig, 'roles'> & Pick<LoadedDeliverySettings, 'credentialKeyReferences'>;\n env?: NodeJS.ProcessEnv;\n identity: string;\n personalAuth?: { enabled: true; token?: string };\n selectedAuthor?: GitHubClients;\n additionalPermissions?: Readonly<Record<string, DeliveryPermission>>;\n role: DeliveryRole;\n signal?: AbortSignal;\n}): Promise<GitHubClients> {\n input.signal?.throwIfAborted();\n const env = input.env ?? process.env;\n const selected = input.config.roles[input.role];\n const retained = input.role === 'author' ? resolvedMachineAuthors.get(input.config.roles) : undefined;\n if (retained !== undefined) {\n // A command that discovered its repository as account A must not acquire\n // a newly supplied token/profile and then operate as account B.\n if (\n selected.authSource !== 'personal' ||\n input.identity.trim().toLowerCase() !== selected.identity.toLowerCase() ||\n !machineAuthorEligible(selected.credentialEnv.token, env) ||\n retained.env !== env ||\n retained.signal !== input.signal ||\n retained.selectors !== sessionSelectors(env)\n )\n throw new DeliveryError(\n 'Machine GitHub session environment changed after repository selection; resolve the command again.',\n );\n assertSupportedAuthorHost(env);\n return retained.clients;\n }\n if (selected.authSource === 'personal') {\n if (input.role !== 'author' || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {\n throw new DeliveryError('Personal author operation requires the configured author identity.');\n }\n assertSupportedAuthorHost(env);\n if (machineAuthorEligible(selected.credentialEnv.token, env)) {\n const selection: MachineSelection = { env, signal: input.signal, selectors: sessionSelectors(env) };\n return withMachineAuthorCredential(env, input.signal, async (token, session) => {\n const clients = personalClients(token, `gh:github.com:${session.executable}`, input.signal, session.login);\n await clients.authenticatedAuthor!(input.signal);\n machineAuthorSelections.set(clients, selection);\n return clients;\n });\n }\n const token = env[selected.credentialEnv.token]?.trim();\n if (!token) {\n throw new DeliveryError(`Missing personal author token in ${selected.credentialEnv.token}.`);\n }\n return personalClients(token, `env:${selected.credentialEnv.token}`, input.signal);\n }\n if (input.personalAuth !== undefined) {\n if (\n input.personalAuth.enabled !== true ||\n input.role !== 'author' ||\n input.identity.trim().toLowerCase() !== 'personal'\n ) {\n throw new DeliveryError('Personal-token auth requires the explicit personal author identity.');\n }\n assertSupportedAuthorHost(env);\n const token = (input.personalAuth.token ?? env.GH_TOKEN ?? env.GITHUB_TOKEN)?.trim();\n if (!token) throw new DeliveryError('Explicit personal-token auth requested but no token was supplied.');\n const source =\n input.personalAuth.token !== undefined\n ? 'explicit-personal-token'\n : env.GH_TOKEN !== undefined\n ? 'env:GH_TOKEN'\n : 'env:GITHUB_TOKEN';\n return personalClients(token, source, input.signal);\n }\n\n if (input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {\n throw new DeliveryError(`GitHub ${input.role} operation requires the configured ${input.role} identity.`);\n }\n const credentials = resolveDeliveryRoleCredentials({ config: input.config, env, role: input.role });\n const otherRole: DeliveryRole = input.role === 'author' ? 'reviewer' : 'author';\n const personalAuthorSelected =\n input.role === 'reviewer' &&\n input.selectedAuthor?.role === 'author' &&\n input.selectedAuthor.authSource === 'personal';\n if (!personalAuthorSelected && input.config.roles[otherRole].authSource !== 'personal') {\n const otherRoleConfig = input.config.roles[otherRole];\n // Explicit profiles compare only other-role metadata. Doctor must not need\n // another identity's key reference or resolve its credential source.\n const other =\n credentials.profile === undefined\n ? resolveDeliveryRoleCredentials({ config: input.config, env, role: otherRole })\n : 'appId' in otherRoleConfig\n ? {\n appId: String(otherRoleConfig.appId),\n installationId: otherRoleConfig.installationId,\n privateKeyPath: undefined,\n }\n : {\n appId: env[otherRoleConfig.credentialEnv.appId]?.trim(),\n installationId: Number(env[otherRoleConfig.credentialEnv.installationId]),\n privateKeyPath: undefined,\n };\n if (\n credentials.appId === other.appId ||\n credentials.installationId === other.installationId ||\n (credentials.privateKeyPath !== undefined && credentials.privateKeyPath === other.privateKeyPath)\n ) {\n throw new DeliveryError('Author and reviewer must use distinct GitHub App credentials.');\n }\n }\n let privateKey: string;\n if (credentials.profile !== undefined) {\n privateKey = await selectedPrivateKey(credentials.profile, env, input.config, input.signal);\n } else {\n try {\n privateKey = readFileSync(credentials.privateKeyPath!, 'utf8');\n } catch {\n throw new DeliveryError(`GitHub App private key for ${input.role} role is unavailable.`);\n }\n }\n try {\n const auth = createAppAuth({\n appId: credentials.appId,\n privateKey,\n ...(input.signal === undefined ? {} : { request: new Octokit({ request: { signal: input.signal } }).request }),\n });\n const result = await auth({ installationId: credentials.installationId, type: 'installation' });\n if (typeof result.token !== 'string' || !result.token.startsWith('ghs_')) {\n throw new DeliveryError(`GitHub ${input.role} role did not receive an App installation token.`);\n }\n assertDeliveryRolePermissions({\n ...(input.additionalPermissions === undefined ? {} : { additional: input.additionalPermissions }),\n permissions: result.permissions,\n role: input.role,\n });\n const appActorLogin =\n input.role === 'reviewer'\n ? async (signal?: AbortSignal) => {\n const requestSignal = signal ?? input.signal;\n try {\n const app = await new Octokit({\n auth: (await auth({ type: 'app' })).token,\n ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),\n }).rest.apps.getAuthenticated();\n if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {\n throw new DeliveryError('Reviewer GitHub App identity did not match its configured App ID.');\n }\n const actor = `${app.data.slug}[bot]`;\n if (credentials.profile !== undefined && actor !== credentials.profile.actorLogin)\n throw new DeliveryError('Reviewer GitHub App actor did not match its configured actorLogin.');\n return actor;\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError('Reviewer GitHub App actor lookup failed.');\n }\n }\n : undefined;\n const authenticatedAuthor =\n input.role === 'author'\n ? async (signal?: AbortSignal) => {\n const requestSignal = signal ?? input.signal;\n try {\n const app = await new Octokit({\n auth: (await auth({ type: 'app' })).token,\n ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),\n }).rest.apps.getAuthenticated();\n if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {\n throw new DeliveryError('Author GitHub App identity did not match its configured App ID.');\n }\n return {\n actorLogin: `${app.data.slug}[bot]`,\n credentialIdentity: `app:${String(app.data.id)}:installation:${credentials.installationId}`,\n };\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError('Author GitHub App actor lookup failed.');\n }\n }\n : undefined;\n return buildClients(\n result.token,\n 'app',\n input.role,\n `app:${credentials.appId}:installation:${credentials.installationId}`,\n appActorLogin,\n authenticatedAuthor,\n (result.permissions as Record<string, DeliveryPermission | 'admin'>).contents,\n input.signal,\n );\n } catch (error) {\n input.signal?.throwIfAborted();\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError(`GitHub App authentication failed for ${input.role} role.`);\n }\n}\n\n/** Selected-source output stays in memory; the existing runner owns command cleanup. */\nasync function selectedPrivateKey(\n profile: ConfiguredApp,\n env: NodeJS.ProcessEnv,\n config: Pick<DeliveryConfig, 'roles'> & Pick<LoadedDeliverySettings, 'credentialKeyReferences'>,\n signal?: AbortSignal,\n): Promise<string> {\n const source = appCredentialSource(profile);\n const failure = (reason: string) =>\n new DeliveryError(`Reviewer ${profile.identity} credential source ${source.type}: ${reason}`);\n let bytes: Buffer;\n try {\n signal?.throwIfAborted();\n if (source.type === 'env') {\n const value = env[privateKeyVariable(profile)];\n if (!value) throw failure('selected variable is missing or empty; configure this identity.');\n if (Buffer.byteLength(value) > 64 * 1024) throw failure('response exceeds 64 KiB.');\n bytes = Buffer.from(value);\n } else if (source.type === 'file') {\n const fd = openSync(source.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const stat = fstatSync(fd);\n if (\n !stat.isFile() ||\n (stat.mode & 0o7777) !== 0o600 ||\n stat.nlink !== 1 ||\n (process.getuid !== undefined && stat.uid !== process.getuid())\n )\n throw failure('key file must be a regular, owned, single-link file with mode 0600.');\n const buffer = Buffer.alloc(64 * 1024 + 1);\n let size = 0;\n for (;;) {\n const read = readSync(fd, buffer, size, buffer.length - size, null);\n if (read === 0) break;\n size += read;\n if (size === buffer.length) throw failure('response exceeds 64 KiB.');\n }\n bytes = buffer.subarray(0, size);\n } finally {\n closeSync(fd);\n }\n } else {\n if (process.platform === 'win32')\n throw failure('command sources currently require a POSIX process supervisor; use env on Windows.');\n const commandEnv: NodeJS.ProcessEnv = {};\n const forbidden = new Set([\n ...(config.credentialKeyReferences ?? []),\n ...Object.values(config.roles).flatMap((role) =>\n 'credentialEnv' in role\n ? Object.values(role.credentialEnv)\n : appCredentialSource(role).type === 'env'\n ? [privateKeyVariable(role)]\n : [],\n ),\n ]);\n for (const name of [\n 'HOME',\n 'USER',\n 'LOGNAME',\n 'PATH',\n 'LANG',\n 'LC_ALL',\n 'TMPDIR',\n 'TEMP',\n 'TMP',\n 'SystemRoot',\n 'USERPROFILE',\n 'APPDATA',\n 'LOCALAPPDATA',\n ]) {\n if (forbidden.has(name)) throw failure('credential reference conflicts with an implicit OS selector.');\n if (env[name] !== undefined) commandEnv[name] = env[name];\n }\n for (const name of source.env ?? []) {\n if (\n forbidden.has(name) ||\n /^(?:NODE_|NPM_|DYLD_|LD_|BASH_|GIT_|GH_PRIVATE_KEY)/u.test(name) ||\n ['ENV', 'SHELLOPTS', 'CDPATH'].includes(name)\n )\n throw failure('helper environment reference conflicts with author/key or execution selectors.');\n if (env[name] === undefined) throw failure('a configured helper environment reference is missing.');\n commandEnv[name] = env[name];\n }\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), 30_000);\n let cleanupFailed = false;\n try {\n bytes = await runStageCommand(\n env.HOME ?? homedir(),\n source.argv,\n signal === undefined ? timeout.signal : AbortSignal.any([signal, timeout.signal]),\n undefined,\n undefined,\n {\n environment: commandEnv,\n cwd: env.HOME ?? homedir(),\n maxCapturedOutputBytes: 64 * 1024,\n stdoutOnly: true,\n failedOutput: () => '',\n onCleanupFailure: () => {\n cleanupFailed = true;\n },\n },\n );\n } catch {\n throw failure(\n cleanupFailed\n ? 'helper failed and owned process cleanup is unverified; reconcile before retrying.'\n : timeout.signal.aborted\n ? 'helper response timed out; verify the selected command.'\n : signal?.aborted\n ? 'helper request cancelled.'\n : 'helper failed; verify its executable, access and bounded output.',\n );\n } finally {\n clearTimeout(timer);\n }\n }\n if (bytes.length === 0 || bytes.length > 64 * 1024) throw failure('response is empty or exceeds 64 KiB.');\n let pem = bytes.toString('utf8');\n if (!Buffer.from(pem).equals(bytes)) throw failure('response must be valid UTF-8.');\n if (source.type !== 'file' && source.encoding === 'base64') {\n const encoded = pem.trim();\n if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded))\n throw failure('response must be canonical base64.');\n const decoded = Buffer.from(encoded, 'base64');\n if (decoded.toString('base64') !== encoded) throw failure('response must be canonical base64.');\n pem = decoded.toString('utf8');\n if (!Buffer.from(pem).equals(decoded)) throw failure('decoded response must be UTF-8 PEM.');\n }\n if (\n !/^-----BEGIN (?:RSA )?PRIVATE KEY-----\\r?\\n[\\s\\S]+\\r?\\n-----END (?:RSA )?PRIVATE KEY-----\\s*$/u.test(pem) ||\n createPrivateKey(pem).asymmetricKeyType !== 'rsa'\n )\n throw failure('response must be an unencrypted RSA private key in PEM format.');\n signal?.throwIfAborted();\n return pem;\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw failure('selected key is unavailable or malformed; verify this source.');\n }\n}\n\nfunction personalClients(\n token: string,\n credentialSource: string,\n signal?: AbortSignal,\n machineLogin?: string,\n): GitHubClients {\n if (!/^[A-Za-z0-9_-]{1,4096}$/u.test(token))\n throw new DeliveryError('Selected personal author token is malformed; verify the explicit credential.');\n if (machineLogin !== undefined && (credentialSource.includes(token) || machineLogin.includes(token)))\n throw new DeliveryError('Machine GitHub session readback is unsafe.');\n return buildClients(\n token,\n 'personal',\n 'author',\n credentialSource,\n undefined,\n async (requestSignal?: AbortSignal) => {\n const selectedSignal = requestSignal ?? signal;\n try {\n const user = (\n await new Octokit({\n auth: token,\n ...(machineLogin === undefined ? {} : { log: { debug() {}, info() {}, warn() {}, error() {} } }),\n ...(selectedSignal === undefined ? {} : { request: { signal: selectedSignal } }),\n }).rest.users.getAuthenticated()\n ).data;\n if (!Number.isSafeInteger(user.id) || user.id <= 0 || !user.login) {\n throw new DeliveryError('Personal author identity readback is incomplete.');\n }\n if (\n machineLogin !== undefined &&\n (user.type !== 'User' ||\n user.login.toLowerCase() !== machineLogin.toLowerCase() ||\n !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u.test(user.login) ||\n user.login.includes(token))\n )\n throw new DeliveryError('Machine GitHub session identity does not match the selected active account.');\n return { actorLogin: user.login, credentialIdentity: `user:${String(user.id)}` };\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n if ((error as { status?: number }).status === 401) {\n throw new DeliveryError(\n machineLogin === undefined\n ? 'Configured personal author token is invalid or expired; refresh the selected token.'\n : 'Machine GitHub session is invalid or expired; verify the selected github.com account.',\n );\n }\n throw new DeliveryError('Personal author identity readback failed.');\n }\n },\n undefined,\n signal,\n machineLogin !== undefined,\n );\n}\n\nfunction buildClients(\n token: string,\n authSource: GitHubClients['authSource'],\n role: DeliveryRole,\n credentialSource: string,\n appActorLogin?: GitHubClients['appActorLogin'],\n authenticatedAuthor?: GitHubClients['authenticatedAuthor'],\n effectiveContentsPermission?: GitHubClients['effectiveContentsPermission'],\n signal?: AbortSignal,\n machineSession = false,\n): GitHubClients {\n const rest = new Octokit({\n auth: token,\n ...(machineSession ? { log: { debug() {}, info() {}, warn() {}, error() {} } } : {}),\n ...(signal === undefined ? {} : { request: { signal } }),\n });\n const rawGraphql = graphql.defaults({\n headers: { authorization: `token ${token}` },\n ...(signal === undefined ? {} : { request: { signal } }),\n });\n let observedRateLimit: RateLimitDiagnostics | undefined;\n const observeRateLimit = (error: unknown, graphqlFailure = false) => {\n observedRateLimit = getRateLimitDiagnostics(error, graphqlFailure) ?? observedRateLimit;\n };\n rest.hook.error('request', (error) => {\n observeRateLimit(error);\n throw error;\n });\n if (machineSession)\n rest.hook.error('request', (error, options) => {\n const safe = safeMachineRequestError(error, 'rest.request', restMachineEndpoint(options));\n const target = branchProtectionTarget(options);\n const responseTarget = branchProtectionTarget({ method: 'GET', url: ownData(ownData(error, 'response'), 'url') });\n if (\n target &&\n responseTarget &&\n target.owner.toLowerCase() === responseTarget.owner.toLowerCase() &&\n target.repo.toLowerCase() === responseTarget.repo.toLowerCase() &&\n target.branch === responseTarget.branch &&\n exactBranchProtectionAbsence(error)\n )\n machineProtectionAbsence.set(safe, { clients, ...target });\n throw safe;\n });\n const clients: GitHubClients = {\n authSource,\n credentialSource,\n ...(effectiveContentsPermission ? { effectiveContentsPermission } : {}),\n role,\n ...(appActorLogin ? { appActorLogin } : {}),\n ...(authenticatedAuthor ? { authenticatedAuthor } : {}),\n graphql: new Proxy(rawGraphql, {\n apply(target, receiver, args: unknown[]) {\n return (Reflect.apply(target, receiver, args) as Promise<unknown>).catch((error: unknown) => {\n observeRateLimit(error, true);\n throw machineSession ? safeMachineRequestError(error, 'graphql.request', 'graphql') : error;\n });\n },\n }),\n rest,\n rateLimitObservation: () => observedRateLimit,\n };\n if (machineSession) machineClients.add(clients);\n if (role === 'author') authorGitTokens.set(clients, token);\n return clients;\n}\n\nfunction exactBranchProtectionAbsence(error: unknown): boolean {\n const response = ownData(error, 'response');\n return (\n ownData(error, 'status') === 404 &&\n ownData(response, 'status') === 404 &&\n ownData(ownData(response, 'data'), 'message') === 'Branch not protected'\n );\n}\n\nfunction branchProtectionTarget(options: unknown): { owner: string; repo: string; branch: string } | undefined {\n const url = ownData(options, 'url');\n if (ownData(options, 'method') !== 'GET' || typeof url !== 'string' || url.length > 1024 || /[^\\x21-\\x7e]/u.test(url))\n return undefined;\n let path: string;\n if (url.startsWith('/')) {\n if (ownData(options, 'baseUrl') !== 'https://api.github.com' || /[?#]/u.test(url)) return undefined;\n path = url;\n } else {\n try {\n const parsed = new URL(url);\n if (\n parsed.origin !== 'https://api.github.com' ||\n parsed.username ||\n parsed.password ||\n parsed.search ||\n parsed.hash\n )\n return undefined;\n path = parsed.pathname;\n } catch {\n return undefined;\n }\n }\n let owner: unknown, repo: unknown, branch: unknown;\n if (path === '/repos/{owner}/{repo}/branches/{branch}/protection') {\n owner = ownData(options, 'owner');\n repo = ownData(options, 'repo');\n branch = ownData(options, 'branch');\n } else {\n const match = /^\\/repos\\/([^/]+)\\/([^/]+)\\/branches\\/(.+)\\/protection$/u.exec(path);\n if (!match) return undefined;\n try {\n [owner, repo, branch] = match.slice(1).map((part) => decodeURIComponent(part));\n } catch {\n return undefined;\n }\n }\n if (\n typeof owner !== 'string' ||\n !/^[A-Za-z0-9_-]{1,100}$/u.test(owner) ||\n typeof repo !== 'string' ||\n !/^[A-Za-z0-9_.-]{1,100}$/u.test(repo) ||\n typeof branch !== 'string' ||\n !branch.length ||\n branch.length > 1024 ||\n /[^\\x21-\\x7e]/u.test(branch)\n )\n return undefined;\n return { owner, repo, branch };\n}\n\n/** Internal read-only predicate: machine absence never comes from copied error fields. */\nexport function hasBranchProtectionAbsence(\n error: unknown,\n clients: GitHubClients,\n repository: { owner: string; repo: string },\n branch: string,\n): boolean {\n if (!machineClients.has(clients)) return exactBranchProtectionAbsence(error);\n if (typeof error !== 'object' || error === null || types.isProxy(error)) return false;\n const target = machineProtectionAbsence.get(error as DeliveryError);\n return (\n target?.clients === clients &&\n target.owner.toLowerCase() === repository.owner.toLowerCase() &&\n target.repo.toLowerCase() === repository.repo.toLowerCase() &&\n target.branch === branch\n );\n}\n\nfunction restMachineEndpoint(options: unknown): SafeMachineRequestDiagnostics['endpoint'] {\n const method = ownData(options, 'method'),\n url = ownData(options, 'url');\n if (typeof method !== 'string' || typeof url !== 'string' || url.length > 1024 || /[^\\x21-\\x7e]/u.test(url))\n return 'UNKNOWN';\n let path: string;\n if (url.startsWith('/')) {\n const base = ownData(options, 'baseUrl');\n if (base !== 'https://api.github.com') return 'UNKNOWN';\n path = url.split(/[?#]/u)[0]!;\n } else {\n try {\n const parsed = new URL(url);\n if (parsed.origin !== 'https://api.github.com' || parsed.username || parsed.password) return 'UNKNOWN';\n path = parsed.pathname;\n } catch {\n return 'UNKNOWN';\n }\n }\n const prefix = '/repos/[^/]{1,100}/[^/]{1,100}';\n const number = '(?:[0-9]{1,20}|\\\\{pull_number\\\\})';\n const routes: readonly [string, RegExp, SafeMachineRequestDiagnostics['endpoint']][] = [\n ['PUT', new RegExp(`^${prefix}/pulls/${number}/merge$`, 'u'), 'pulls.merge'],\n ['GET', new RegExp(`^${prefix}/pulls/${number}$`, 'u'), 'pulls.get'],\n ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews$`, 'u'), 'pulls.listReviews'],\n ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews/(?:[0-9]{1,20}|\\\\{review_id\\\\})$`, 'u'), 'pulls.getReview'],\n ['GET', new RegExp(`^${prefix}/git/commits/[^/]{1,100}$`, 'u'), 'git.getCommit'],\n ['GET', new RegExp(`^${prefix}/git/ref/.{1,300}$`, 'u'), 'git.getRef'],\n ['GET', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\\\{issue_number\\\\})$`, 'u'), 'issues.get'],\n ['PATCH', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\\\{issue_number\\\\})$`, 'u'), 'issues.update'],\n ];\n return routes.find(([verb, pattern]) => verb === method && pattern.test(path))?.[2] ?? 'UNKNOWN';\n}\n\nfunction safeMachineRequestError(\n error: unknown,\n phase: 'rest.request' | 'graphql.request',\n endpoint: SafeMachineRequestDiagnostics['endpoint'],\n): DeliveryError {\n const status = ownData(error, 'status');\n const safe = new DeliveryError(\n status === 401\n ? 'Machine GitHub session is invalid or expired; verify the selected github.com account.'\n : status === 403 || status === 404\n ? 'Machine GitHub session cannot access the selected repository or operation; verify its existing permissions.'\n : 'Machine GitHub request failed; verify the selected account and repository access.',\n );\n if (typeof status === 'number' && Number.isSafeInteger(status) && status >= 400 && status <= 599)\n Object.assign(safe, { status });\n const headers = ownData(error, 'headers') ?? ownData(ownData(error, 'response'), 'headers');\n setMachineRequestDiagnostics(safe, {\n phase,\n endpoint,\n status,\n code: ownData(error, 'code'),\n requestId: ownData(headers, 'x-github-request-id'),\n retryAfter: ownData(headers, 'retry-after'),\n resetAt: ownData(headers, 'x-ratelimit-reset'),\n remaining: ownData(headers, 'x-ratelimit-remaining'),\n });\n return safe;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;AAExB,SAAS,eAAe;AACxB,SAAS,WAAW,WAAW,WAAW,UAAU,cAAc,gBAAgB;AAClF,SAAS,wBAAwB;AACjC,SAAS,eAAe;AACxB,SAAS,aAAa;AAItB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAeP,MAAM,kBAAkB,oBAAI,QAA+B;AAC3D,MAAM,iBAAiB,oBAAI,QAAuB;AAClD,MAAM,2BAA2B,oBAAI,QAGnC;AAMF,MAAM,0BAA0B,oBAAI,QAAyC;AAC7E,MAAM,y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 export interface NativeIssueMetadataRest {
|
|
|
32
32
|
}>;
|
|
33
33
|
}
|
|
34
34
|
export type NativePointValue = number;
|
|
35
|
-
export type NativePriorityValue = string;
|
|
36
35
|
export declare function nativeIssueSettingsFromDeliveryConfig(config: Pick<DeliveryConfig, 'native'>): NativeIssueSettings;
|
|
37
36
|
export declare function clearConfiguredNativeIssuePoints(input: {
|
|
38
37
|
catalog?: NativeIssueFieldCatalog;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/github/nativeIssueMetadata.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod';\nimport type { DeliveryConfig } from '../config/deliveryConfig.js';\n\nimport { DeliveryError } from '../errors.js';\n\nexport const NATIVE_ISSUE_API_VERSION = '2026-03-10';\n\nexport interface ConfiguredNativeIssueMetadata {\n points?: number;\n priority?: string;\n}\nexport interface NativeIssueFieldCatalog {\n points: NativeIssueFieldReference;\n priority: NativeIssueFieldReference;\n}\n\nexport interface NativeIssueFieldReference {\n dataType: 'single_select';\n id: number;\n name: string;\n}\n\nexport interface NativeIssueSettings {\n points: { databaseId: string; name: string; values: readonly number[] };\n priority: { databaseId: string; name: string; values: readonly string[] };\n}\n\nexport interface NativeIssueMetadataRest {\n request: (route: string, parameters: Record<string, unknown>) => Promise<{ data: unknown }>;\n}\n\nexport type NativePointValue = number;\nexport type NativePriorityValue = string;\n\ninterface RawIssueField {\n data_type?: unknown;\n id?: unknown;\n name?: unknown;\n options?: unknown;\n}\n\ninterface RawIssueFieldValue {\n data_type?: unknown;\n issue_field_id?: unknown;\n issue_field_name?: unknown;\n single_select_option?: unknown;\n value?: unknown;\n}\n\nexport function nativeIssueSettingsFromDeliveryConfig(config: Pick<DeliveryConfig, 'native'>): NativeIssueSettings {\n return {\n points: {\n databaseId: config.native.points.databaseId,\n name: config.native.points.name,\n values: config.native.points.values.map((value) => Number(value)),\n },\n priority: {\n databaseId: config.native.priority.databaseId,\n name: config.native.priority.name,\n values: config.native.priority.values,\n },\n };\n}\n\nconst apiHeaders = { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION } as const;\n\nexport async function clearConfiguredNativeIssuePoints(input: {\n catalog?: NativeIssueFieldCatalog;\n issueNumber: number;\n org: string;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<void> {\n const existing = await getConfiguredNativeIssueMetadata(input);\n if (existing.points === undefined) {\n return;\n }\n const catalog = input.catalog ?? (await getConfiguredNativeIssueFieldCatalog(input));\n assertCatalogMatchesSettings(catalog, input.settings);\n await input.rest.request('DELETE /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values/{issue_field_id}', {\n headers: apiHeaders,\n issue_field_id: catalog.points.id,\n issue_number: input.issueNumber,\n owner: input.owner,\n repo: input.repo,\n });\n const readback = await getConfiguredNativeIssueMetadata(input);\n if (readback.points !== undefined) {\n throw new DeliveryError(\n `Native issue metadata readback retained Points ${String(readback.points)} after clearing issue #${String(input.issueNumber)}.`,\n );\n }\n}\n\nexport async function getConfiguredNativeIssueFieldCatalog(input: {\n org: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<NativeIssueFieldCatalog> {\n const response = await input.rest.request('GET /orgs/{org}/issue-fields', {\n headers: apiHeaders,\n org: input.org,\n });\n return resolveNativeIssueFieldCatalog(response.data, input.settings);\n}\n\nexport async function getConfiguredNativeIssueMetadata(input: {\n issueNumber: number;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<ConfiguredNativeIssueMetadata> {\n const response = await input.rest.request('GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {\n headers: apiHeaders,\n issue_number: input.issueNumber,\n owner: input.owner,\n repo: input.repo,\n });\n return parseConfiguredNativeIssueMetadata(response.data, input.settings);\n}\n\nexport function parseConfiguredNativeIssueMetadata(\n raw: unknown,\n settings: NativeIssueSettings,\n): ConfiguredNativeIssueMetadata {\n if (!Array.isArray(raw)) {\n throw new DeliveryError('GitHub returned an invalid issue-field value payload.');\n }\n\n const metadata: ConfiguredNativeIssueMetadata = {};\n const seen = new Set<NativeIssueFieldReference['name']>();\n for (const candidate of raw) {\n if (typeof candidate !== 'object' || candidate === null) {\n continue;\n }\n const value = candidate as RawIssueFieldValue;\n const name = value.issue_field_name;\n assertConfiguredReadbackField({ seen, settings, value });\n if (name === settings.points.name) {\n metadata.points = parseConfiguredPoints(value, settings);\n } else if (name === settings.priority.name) {\n metadata.priority = parseConfiguredPriority(value, settings);\n }\n }\n return metadata;\n}\n\nexport function resolveNativeIssueFieldCatalog(raw: unknown, settings: NativeIssueSettings): NativeIssueFieldCatalog {\n if (!Array.isArray(raw)) {\n throw new DeliveryError('GitHub returned an invalid organization issue-field payload.');\n }\n const fields = raw.filter((value): value is RawIssueField => typeof value === 'object' && value !== null);\n return {\n points: resolveSingleSelectField({\n expectedId: settings.points.databaseId,\n expectedValues: settings.points.values.map(String),\n fields,\n name: settings.points.name,\n }),\n priority: resolveSingleSelectField({\n expectedId: settings.priority.databaseId,\n expectedValues: settings.priority.values,\n fields,\n name: settings.priority.name,\n }),\n };\n}\n\nexport async function setConfiguredNativeIssueMetadata(input: {\n catalog?: NativeIssueFieldCatalog;\n issueNumber: number;\n metadata: ConfiguredNativeIssueMetadata;\n org: string;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<ConfiguredNativeIssueMetadata> {\n if (input.metadata.points === undefined && input.metadata.priority === undefined) {\n return {};\n }\n const catalog = input.catalog ?? (await getConfiguredNativeIssueFieldCatalog(input));\n assertCatalogMatchesSettings(catalog, input.settings);\n const issueFieldValues: { field_id: number; value: string }[] = [];\n if (input.metadata.points !== undefined) {\n if (!input.settings.points.values.includes(input.metadata.points)) {\n throw new DeliveryError(`Unsupported ${input.settings.points.name} value.`);\n }\n issueFieldValues.push({ field_id: catalog.points.id, value: String(input.metadata.points) });\n }\n if (input.metadata.priority !== undefined) {\n if (!input.settings.priority.values.includes(input.metadata.priority)) {\n throw new DeliveryError(`Unsupported ${input.settings.priority.name} value.`);\n }\n issueFieldValues.push({ field_id: catalog.priority.id, value: input.metadata.priority });\n }\n if (issueFieldValues.length === 0) {\n return {};\n }\n\n const response = await input.rest.request('POST /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {\n headers: apiHeaders,\n issue_field_values: issueFieldValues,\n issue_number: input.issueNumber,\n owner: input.owner,\n repo: input.repo,\n });\n const readback = parseConfiguredNativeIssueMetadata(response.data, input.settings);\n assertReadback(input.metadata, readback);\n return readback;\n}\n\nfunction assertCatalogMatchesSettings(catalog: NativeIssueFieldCatalog, settings: NativeIssueSettings): void {\n for (const field of ['points', 'priority'] as const) {\n const actual = catalog[field];\n const expected = settings[field];\n if (\n !Number.isSafeInteger(actual.id) ||\n actual.id <= 0 ||\n actual.name !== expected.name ||\n String(actual.id) !== expected.databaseId\n ) {\n throw new DeliveryError(`Native ${expected.name} catalog does not match configured issue field.`);\n }\n }\n if (catalog.points.id === catalog.priority.id) {\n throw new DeliveryError('Native Points and Priority catalogs must select distinct issue fields.');\n }\n}\n\nfunction assertConfiguredReadbackField(input: {\n seen: Set<string>;\n settings: NativeIssueSettings;\n value: RawIssueFieldValue;\n}): void {\n const { seen, settings, value } = input;\n const name = value.issue_field_name;\n if (name !== settings.points.name && name !== settings.priority.name) return;\n if (seen.has(name)) {\n throw new DeliveryError(`GitHub returned duplicate native ${name} field values.`);\n }\n seen.add(name);\n if (value.data_type !== 'single_select') {\n throw new DeliveryError(`Native ${name} readback must be a constrained single-select field value.`);\n }\n const expectedId = name === settings.points.name ? settings.points.databaseId : settings.priority.databaseId;\n if (expectedId !== undefined && String(value.issue_field_id) !== expectedId) {\n throw new DeliveryError(`Native ${name} readback does not match configured issue field.`);\n }\n}\n\nfunction assertReadback(expected: ConfiguredNativeIssueMetadata, actual: ConfiguredNativeIssueMetadata): void {\n for (const key of ['points', 'priority'] as const) {\n if (expected[key] !== undefined && actual[key] !== expected[key]) {\n throw new DeliveryError(\n `Native issue metadata readback mismatch for ${key}: expected ${String(expected[key])}, found ${String(actual[key])}.`,\n );\n }\n }\n}\n\nfunction parseConfiguredPoints(value: RawIssueFieldValue, settings: NativeIssueSettings): number {\n const rendered = readFieldValue(value);\n const points = typeof rendered === 'number' ? rendered : Number(rendered);\n if (\n !Number.isSafeInteger(points) ||\n !settings.points.values.includes(points) ||\n (settings.points.databaseId !== undefined && String(rendered) !== String(points))\n ) {\n throw new DeliveryError(`GitHub returned unsupported ${settings.points.name} value ${String(rendered)}.`);\n }\n return points;\n}\n\nfunction parseConfiguredPriority(value: RawIssueFieldValue, settings: NativeIssueSettings): string {\n const rendered = readFieldValue(value);\n if (typeof rendered !== 'string' || !settings.priority.values.includes(rendered)) {\n throw new DeliveryError(`GitHub returned unsupported ${settings.priority.name} value ${String(rendered)}.`);\n }\n return rendered;\n}\n\nfunction readFieldValue(value: RawIssueFieldValue): unknown {\n if (typeof value.single_select_option === 'object' && value.single_select_option !== null) {\n const option = value.single_select_option as { name?: unknown };\n if (option.name !== undefined) {\n return option.name;\n }\n }\n return value.value;\n}\n\nfunction resolveSingleSelectField({\n expectedId,\n expectedValues,\n fields,\n name,\n}: {\n expectedId?: string | undefined;\n expectedValues?: readonly string[] | undefined;\n fields: RawIssueField[];\n name: string;\n}): NativeIssueFieldReference {\n const matches = fields.filter((field) => field.name === name);\n if (matches.length !== 1) {\n throw new DeliveryError(`Expected exactly one native ${name} issue field, found ${String(matches.length)}.`);\n }\n const [field] = matches;\n if (field === undefined || field.data_type !== 'single_select' || !Number.isSafeInteger(field.id)) {\n throw new DeliveryError(`Native ${name} must be a constrained single-select issue field.`);\n }\n if (expectedId !== undefined && String(field.id) !== expectedId) {\n throw new DeliveryError(`Native ${name} does not match configured issue field ${expectedId}.`);\n }\n if (expectedValues !== undefined) {\n const options = Array.isArray(field.options)\n ? field.options.map((option) =>\n typeof option === 'object' && option !== null ? (option as { name?: unknown }).name : null,\n )\n : [];\n if (\n options.length !== expectedValues.length ||\n new Set(options).size !== expectedValues.length ||\n options.some((option) => typeof option !== 'string' || !expectedValues.includes(option))\n ) {\n throw new DeliveryError(`Native ${name} options do not match configured values.`);\n }\n }\n return { dataType: 'single_select', id: field.id as number, name };\n}\n\n/** Optional native fields: omission preserves, null clears only the named field. */\nexport const NativeIssueDateFields = {\n startDate: z.iso.date().nullable().optional(),\n targetDate: z.iso.date().nullable().optional(),\n};\nexport interface NativeIssueDatePatch {\n startDate?: string | null;\n targetDate?: string | null;\n}\nexport interface NativeIssueDateChange {\n fieldId: number;\n name: string;\n value: string | null;\n}\n\nexport function prepareNativeIssueDates(\n patch: NativeIssueDatePatch,\n catalog: readonly { id: number; name: string; data_type: string }[],\n): NativeIssueDateChange[] {\n return (['startDate', 'targetDate'] as const).flatMap((key) => {\n const value = patch[key];\n if (value === undefined) return [];\n NativeIssueDateFields[key].parse(value);\n const name = key === 'startDate' ? 'Start date' : 'Target date';\n const matches = catalog.filter((field) => field.name === name);\n if (matches.length !== 1 || matches[0]!.data_type !== 'date')\n throw new DeliveryError(`Expected one configured native date field named ${name}.`);\n return [{ fieldId: matches[0]!.id, name, value }];\n });\n}\n\nexport async function applyNativeIssueDates(input: {\n changes: readonly NativeIssueDateChange[];\n issueNumber: number;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n}): Promise<void> {\n if (!input.changes.length) return;\n const parameters = { headers: apiHeaders, issue_number: input.issueNumber, owner: input.owner, repo: input.repo };\n const read = async () => {\n const response = await input.rest.request(\n 'GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values',\n parameters,\n );\n if (!Array.isArray(response.data)) throw new DeliveryError('Incomplete native date field readback.');\n return response.data as RawIssueFieldValue[];\n };\n const selected = (values: RawIssueFieldValue[], change: NativeIssueDateChange) => {\n const matches = values.filter((field) => field.issue_field_id === change.fieldId);\n if (\n matches.length > 1 ||\n matches.some((field) => field.issue_field_name !== change.name || field.data_type !== 'date')\n )\n throw new DeliveryError(`Native ${change.name} readback conflicts with its configured identity.`);\n return matches[0];\n };\n const before = await read();\n for (const change of input.changes) selected(before, change);\n const additions = input.changes.filter((change) => change.value !== null);\n if (additions.length)\n await input.rest.request('POST /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {\n ...parameters,\n issue_field_values: additions.map((change) => ({ field_id: change.fieldId, value: change.value })),\n });\n for (const change of input.changes) {\n if (change.value === null && selected(before, change)?.value != null)\n await input.rest.request(\n 'DELETE /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values/{issue_field_id}',\n {\n ...parameters,\n issue_field_id: change.fieldId,\n },\n );\n }\n const after = await read();\n for (const change of input.changes) {\n if ((selected(after, change)?.value ?? null) !== change.value)\n throw new DeliveryError(`Native ${change.name} readback differs from the requested date.`);\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,qBAAqB;AAEvB,MAAM,2BAA2B;
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod';\nimport type { DeliveryConfig } from '../config/deliveryConfig.js';\n\nimport { DeliveryError } from '../errors.js';\n\nexport const NATIVE_ISSUE_API_VERSION = '2026-03-10';\n\nexport interface ConfiguredNativeIssueMetadata {\n points?: number;\n priority?: string;\n}\nexport interface NativeIssueFieldCatalog {\n points: NativeIssueFieldReference;\n priority: NativeIssueFieldReference;\n}\n\nexport interface NativeIssueFieldReference {\n dataType: 'single_select';\n id: number;\n name: string;\n}\n\nexport interface NativeIssueSettings {\n points: { databaseId: string; name: string; values: readonly number[] };\n priority: { databaseId: string; name: string; values: readonly string[] };\n}\n\nexport interface NativeIssueMetadataRest {\n request: (route: string, parameters: Record<string, unknown>) => Promise<{ data: unknown }>;\n}\n\nexport type NativePointValue = number;\n\ninterface RawIssueField {\n data_type?: unknown;\n id?: unknown;\n name?: unknown;\n options?: unknown;\n}\n\ninterface RawIssueFieldValue {\n data_type?: unknown;\n issue_field_id?: unknown;\n issue_field_name?: unknown;\n single_select_option?: unknown;\n value?: unknown;\n}\n\nexport function nativeIssueSettingsFromDeliveryConfig(config: Pick<DeliveryConfig, 'native'>): NativeIssueSettings {\n return {\n points: {\n databaseId: config.native.points.databaseId,\n name: config.native.points.name,\n values: config.native.points.values.map((value) => Number(value)),\n },\n priority: {\n databaseId: config.native.priority.databaseId,\n name: config.native.priority.name,\n values: config.native.priority.values,\n },\n };\n}\n\nconst apiHeaders = { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION } as const;\n\nexport async function clearConfiguredNativeIssuePoints(input: {\n catalog?: NativeIssueFieldCatalog;\n issueNumber: number;\n org: string;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<void> {\n const existing = await getConfiguredNativeIssueMetadata(input);\n if (existing.points === undefined) {\n return;\n }\n const catalog = input.catalog ?? (await getConfiguredNativeIssueFieldCatalog(input));\n assertCatalogMatchesSettings(catalog, input.settings);\n await input.rest.request('DELETE /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values/{issue_field_id}', {\n headers: apiHeaders,\n issue_field_id: catalog.points.id,\n issue_number: input.issueNumber,\n owner: input.owner,\n repo: input.repo,\n });\n const readback = await getConfiguredNativeIssueMetadata(input);\n if (readback.points !== undefined) {\n throw new DeliveryError(\n `Native issue metadata readback retained Points ${String(readback.points)} after clearing issue #${String(input.issueNumber)}.`,\n );\n }\n}\n\nexport async function getConfiguredNativeIssueFieldCatalog(input: {\n org: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<NativeIssueFieldCatalog> {\n const response = await input.rest.request('GET /orgs/{org}/issue-fields', {\n headers: apiHeaders,\n org: input.org,\n });\n return resolveNativeIssueFieldCatalog(response.data, input.settings);\n}\n\nexport async function getConfiguredNativeIssueMetadata(input: {\n issueNumber: number;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<ConfiguredNativeIssueMetadata> {\n const response = await input.rest.request('GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {\n headers: apiHeaders,\n issue_number: input.issueNumber,\n owner: input.owner,\n repo: input.repo,\n });\n return parseConfiguredNativeIssueMetadata(response.data, input.settings);\n}\n\nexport function parseConfiguredNativeIssueMetadata(\n raw: unknown,\n settings: NativeIssueSettings,\n): ConfiguredNativeIssueMetadata {\n if (!Array.isArray(raw)) {\n throw new DeliveryError('GitHub returned an invalid issue-field value payload.');\n }\n\n const metadata: ConfiguredNativeIssueMetadata = {};\n const seen = new Set<NativeIssueFieldReference['name']>();\n for (const candidate of raw) {\n if (typeof candidate !== 'object' || candidate === null) {\n continue;\n }\n const value = candidate as RawIssueFieldValue;\n const name = value.issue_field_name;\n assertConfiguredReadbackField({ seen, settings, value });\n if (name === settings.points.name) {\n metadata.points = parseConfiguredPoints(value, settings);\n } else if (name === settings.priority.name) {\n metadata.priority = parseConfiguredPriority(value, settings);\n }\n }\n return metadata;\n}\n\nexport function resolveNativeIssueFieldCatalog(raw: unknown, settings: NativeIssueSettings): NativeIssueFieldCatalog {\n if (!Array.isArray(raw)) {\n throw new DeliveryError('GitHub returned an invalid organization issue-field payload.');\n }\n const fields = raw.filter((value): value is RawIssueField => typeof value === 'object' && value !== null);\n return {\n points: resolveSingleSelectField({\n expectedId: settings.points.databaseId,\n expectedValues: settings.points.values.map(String),\n fields,\n name: settings.points.name,\n }),\n priority: resolveSingleSelectField({\n expectedId: settings.priority.databaseId,\n expectedValues: settings.priority.values,\n fields,\n name: settings.priority.name,\n }),\n };\n}\n\nexport async function setConfiguredNativeIssueMetadata(input: {\n catalog?: NativeIssueFieldCatalog;\n issueNumber: number;\n metadata: ConfiguredNativeIssueMetadata;\n org: string;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n settings: NativeIssueSettings;\n}): Promise<ConfiguredNativeIssueMetadata> {\n if (input.metadata.points === undefined && input.metadata.priority === undefined) {\n return {};\n }\n const catalog = input.catalog ?? (await getConfiguredNativeIssueFieldCatalog(input));\n assertCatalogMatchesSettings(catalog, input.settings);\n const issueFieldValues: { field_id: number; value: string }[] = [];\n if (input.metadata.points !== undefined) {\n if (!input.settings.points.values.includes(input.metadata.points)) {\n throw new DeliveryError(`Unsupported ${input.settings.points.name} value.`);\n }\n issueFieldValues.push({ field_id: catalog.points.id, value: String(input.metadata.points) });\n }\n if (input.metadata.priority !== undefined) {\n if (!input.settings.priority.values.includes(input.metadata.priority)) {\n throw new DeliveryError(`Unsupported ${input.settings.priority.name} value.`);\n }\n issueFieldValues.push({ field_id: catalog.priority.id, value: input.metadata.priority });\n }\n if (issueFieldValues.length === 0) {\n return {};\n }\n\n const response = await input.rest.request('POST /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {\n headers: apiHeaders,\n issue_field_values: issueFieldValues,\n issue_number: input.issueNumber,\n owner: input.owner,\n repo: input.repo,\n });\n const readback = parseConfiguredNativeIssueMetadata(response.data, input.settings);\n assertReadback(input.metadata, readback);\n return readback;\n}\n\nfunction assertCatalogMatchesSettings(catalog: NativeIssueFieldCatalog, settings: NativeIssueSettings): void {\n for (const field of ['points', 'priority'] as const) {\n const actual = catalog[field];\n const expected = settings[field];\n if (\n !Number.isSafeInteger(actual.id) ||\n actual.id <= 0 ||\n actual.name !== expected.name ||\n String(actual.id) !== expected.databaseId\n ) {\n throw new DeliveryError(`Native ${expected.name} catalog does not match configured issue field.`);\n }\n }\n if (catalog.points.id === catalog.priority.id) {\n throw new DeliveryError('Native Points and Priority catalogs must select distinct issue fields.');\n }\n}\n\nfunction assertConfiguredReadbackField(input: {\n seen: Set<string>;\n settings: NativeIssueSettings;\n value: RawIssueFieldValue;\n}): void {\n const { seen, settings, value } = input;\n const name = value.issue_field_name;\n if (name !== settings.points.name && name !== settings.priority.name) return;\n if (seen.has(name)) {\n throw new DeliveryError(`GitHub returned duplicate native ${name} field values.`);\n }\n seen.add(name);\n if (value.data_type !== 'single_select') {\n throw new DeliveryError(`Native ${name} readback must be a constrained single-select field value.`);\n }\n const expectedId = name === settings.points.name ? settings.points.databaseId : settings.priority.databaseId;\n if (expectedId !== undefined && String(value.issue_field_id) !== expectedId) {\n throw new DeliveryError(`Native ${name} readback does not match configured issue field.`);\n }\n}\n\nfunction assertReadback(expected: ConfiguredNativeIssueMetadata, actual: ConfiguredNativeIssueMetadata): void {\n for (const key of ['points', 'priority'] as const) {\n if (expected[key] !== undefined && actual[key] !== expected[key]) {\n throw new DeliveryError(\n `Native issue metadata readback mismatch for ${key}: expected ${String(expected[key])}, found ${String(actual[key])}.`,\n );\n }\n }\n}\n\nfunction parseConfiguredPoints(value: RawIssueFieldValue, settings: NativeIssueSettings): number {\n const rendered = readFieldValue(value);\n const points = typeof rendered === 'number' ? rendered : Number(rendered);\n if (\n !Number.isSafeInteger(points) ||\n !settings.points.values.includes(points) ||\n (settings.points.databaseId !== undefined && String(rendered) !== String(points))\n ) {\n throw new DeliveryError(`GitHub returned unsupported ${settings.points.name} value ${String(rendered)}.`);\n }\n return points;\n}\n\nfunction parseConfiguredPriority(value: RawIssueFieldValue, settings: NativeIssueSettings): string {\n const rendered = readFieldValue(value);\n if (typeof rendered !== 'string' || !settings.priority.values.includes(rendered)) {\n throw new DeliveryError(`GitHub returned unsupported ${settings.priority.name} value ${String(rendered)}.`);\n }\n return rendered;\n}\n\nfunction readFieldValue(value: RawIssueFieldValue): unknown {\n if (typeof value.single_select_option === 'object' && value.single_select_option !== null) {\n const option = value.single_select_option as { name?: unknown };\n if (option.name !== undefined) {\n return option.name;\n }\n }\n return value.value;\n}\n\nfunction resolveSingleSelectField({\n expectedId,\n expectedValues,\n fields,\n name,\n}: {\n expectedId?: string | undefined;\n expectedValues?: readonly string[] | undefined;\n fields: RawIssueField[];\n name: string;\n}): NativeIssueFieldReference {\n const matches = fields.filter((field) => field.name === name);\n if (matches.length !== 1) {\n throw new DeliveryError(`Expected exactly one native ${name} issue field, found ${String(matches.length)}.`);\n }\n const [field] = matches;\n if (field === undefined || field.data_type !== 'single_select' || !Number.isSafeInteger(field.id)) {\n throw new DeliveryError(`Native ${name} must be a constrained single-select issue field.`);\n }\n if (expectedId !== undefined && String(field.id) !== expectedId) {\n throw new DeliveryError(`Native ${name} does not match configured issue field ${expectedId}.`);\n }\n if (expectedValues !== undefined) {\n const options = Array.isArray(field.options)\n ? field.options.map((option) =>\n typeof option === 'object' && option !== null ? (option as { name?: unknown }).name : null,\n )\n : [];\n if (\n options.length !== expectedValues.length ||\n new Set(options).size !== expectedValues.length ||\n options.some((option) => typeof option !== 'string' || !expectedValues.includes(option))\n ) {\n throw new DeliveryError(`Native ${name} options do not match configured values.`);\n }\n }\n return { dataType: 'single_select', id: field.id as number, name };\n}\n\n/** Optional native fields: omission preserves, null clears only the named field. */\nexport const NativeIssueDateFields = {\n startDate: z.iso.date().nullable().optional(),\n targetDate: z.iso.date().nullable().optional(),\n};\nexport interface NativeIssueDatePatch {\n startDate?: string | null;\n targetDate?: string | null;\n}\nexport interface NativeIssueDateChange {\n fieldId: number;\n name: string;\n value: string | null;\n}\n\nexport function prepareNativeIssueDates(\n patch: NativeIssueDatePatch,\n catalog: readonly { id: number; name: string; data_type: string }[],\n): NativeIssueDateChange[] {\n return (['startDate', 'targetDate'] as const).flatMap((key) => {\n const value = patch[key];\n if (value === undefined) return [];\n NativeIssueDateFields[key].parse(value);\n const name = key === 'startDate' ? 'Start date' : 'Target date';\n const matches = catalog.filter((field) => field.name === name);\n if (matches.length !== 1 || matches[0]!.data_type !== 'date')\n throw new DeliveryError(`Expected one configured native date field named ${name}.`);\n return [{ fieldId: matches[0]!.id, name, value }];\n });\n}\n\nexport async function applyNativeIssueDates(input: {\n changes: readonly NativeIssueDateChange[];\n issueNumber: number;\n owner: string;\n repo: string;\n rest: NativeIssueMetadataRest;\n}): Promise<void> {\n if (!input.changes.length) return;\n const parameters = { headers: apiHeaders, issue_number: input.issueNumber, owner: input.owner, repo: input.repo };\n const read = async () => {\n const response = await input.rest.request(\n 'GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values',\n parameters,\n );\n if (!Array.isArray(response.data)) throw new DeliveryError('Incomplete native date field readback.');\n return response.data as RawIssueFieldValue[];\n };\n const selected = (values: RawIssueFieldValue[], change: NativeIssueDateChange) => {\n const matches = values.filter((field) => field.issue_field_id === change.fieldId);\n if (\n matches.length > 1 ||\n matches.some((field) => field.issue_field_name !== change.name || field.data_type !== 'date')\n )\n throw new DeliveryError(`Native ${change.name} readback conflicts with its configured identity.`);\n return matches[0];\n };\n const before = await read();\n for (const change of input.changes) selected(before, change);\n const additions = input.changes.filter((change) => change.value !== null);\n if (additions.length)\n await input.rest.request('POST /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {\n ...parameters,\n issue_field_values: additions.map((change) => ({ field_id: change.fieldId, value: change.value })),\n });\n for (const change of input.changes) {\n if (change.value === null && selected(before, change)?.value != null)\n await input.rest.request(\n 'DELETE /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values/{issue_field_id}',\n {\n ...parameters,\n issue_field_id: change.fieldId,\n },\n );\n }\n const after = await read();\n for (const change of input.changes) {\n if ((selected(after, change)?.value ?? null) !== change.value)\n throw new DeliveryError(`Native ${change.name} readback differs from the requested date.`);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,qBAAqB;AAEvB,MAAM,2BAA2B;AA2CjC,SAAS,sCAAsC,QAA6D;AACjH,SAAO;AAAA,IACL,QAAQ;AAAA,MACN,YAAY,OAAO,OAAO,OAAO;AAAA,MACjC,MAAM,OAAO,OAAO,OAAO;AAAA,MAC3B,QAAQ,OAAO,OAAO,OAAO,OAAO,IAAI,CAAC,UAAU,OAAO,KAAK,CAAC;AAAA,IAClE;AAAA,IACA,UAAU;AAAA,MACR,YAAY,OAAO,OAAO,SAAS;AAAA,MACnC,MAAM,OAAO,OAAO,SAAS;AAAA,MAC7B,QAAQ,OAAO,OAAO,SAAS;AAAA,IACjC;AAAA,EACF;AACF;AAEA,MAAM,aA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
} from "./errors.js";
|
|
12
13
|
import { createDeliveryGitHubClients } from "./github/client.js";
|
|
@@ -58,6 +59,7 @@ import {
|
|
|
58
59
|
requireIssueStatus,
|
|
59
60
|
parseIssueBody,
|
|
60
61
|
requireIssue,
|
|
62
|
+
addedLocalPaths,
|
|
61
63
|
renderIssueBody,
|
|
62
64
|
issueWarnings,
|
|
63
65
|
issueBodyDiff,
|
|
@@ -269,6 +271,10 @@ function prepareIssueWrite(input, current, forIntent = false) {
|
|
|
269
271
|
},
|
|
270
272
|
requireBuilder ? { requireBuilder: true } : {}
|
|
271
273
|
);
|
|
274
|
+
if (currentParsed !== void 0 && !currentParsed.issue.draft && !issue.draft) {
|
|
275
|
+
const added = addedLocalPaths(currentParsed.issue, issue);
|
|
276
|
+
if (added.length) throw new IssueValidationError(added);
|
|
277
|
+
}
|
|
272
278
|
const unchangedContract = currentParsed !== void 0 && JSON.stringify(issue) === JSON.stringify(currentParsed.issue);
|
|
273
279
|
const legacyFormatting = unchangedContract && parsed.legacyFormatting === true;
|
|
274
280
|
const base = parsed.status ?? currentParsed?.status;
|
|
@@ -986,9 +992,7 @@ function rebuildableWrite(input, current) {
|
|
|
986
992
|
"draft",
|
|
987
993
|
"openQuestions",
|
|
988
994
|
"context",
|
|
989
|
-
...["builder", "extends", "priorWork", "decisions", "surface", "fences", "proof"].filter(
|
|
990
|
-
(key) => carried.has(key)
|
|
991
|
-
)
|
|
995
|
+
...["builder", "extends", "priorWork", "decisions", "moneyPath", "ownerOk", "surface", "fences", "proof"].filter((key) => carried.has(key))
|
|
992
996
|
].filter((key) => input[key] === void 0);
|
|
993
997
|
if (reset.length) {
|
|
994
998
|
const message = `Rebuilt the hand-edited body (old one in the history comment); reset because not sent: ${reset.join(", ")}.`;
|
|
@@ -1722,8 +1726,7 @@ function localBatchFailureReason(error) {
|
|
|
1722
1726
|
const prototype = Object.getPrototypeOf(error);
|
|
1723
1727
|
if (prototype === IssueValidationError.prototype) return "Requested issue fields do not satisfy the issue contract.";
|
|
1724
1728
|
if (prototype !== DeliveryError.prototype) return void 0;
|
|
1725
|
-
const
|
|
1726
|
-
const message = descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
1729
|
+
const message = ownData(error, "message");
|
|
1727
1730
|
if (typeof message !== "string") return void 0;
|
|
1728
1731
|
if ([
|
|
1729
1732
|
"Choose a valid defer condition or explicit undefer, never both.",
|