uptide 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +0,0 @@
1
- import { createRequire as __uptideCreateRequire } from 'node:module';
2
- import { fileURLToPath as __uptideFileURLToPath } from 'node:url';
3
- const require = __uptideCreateRequire(import.meta.url);
4
- const __filename = __uptideFileURLToPath(import.meta.url);
5
- const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
6
- import{UptideError,uptideVersionInfo}from"./chunk-W7QEZJ57.js";import{readFileSync}from"fs";import{execFileSync,spawn}from"child_process";import{existsSync,mkdirSync,realpathSync}from"fs";import{tmpdir}from"os";import{dirname,join,relative,resolve}from"path";function noHooksDir(){let dir=join(tmpdir(),"uptide-no-hooks");return mkdirSync(dir,{recursive:!0}),dir}function quietEnv(){return{CI:"true",npm_config_ignore_scripts:"true",npm_config_enable_pre_post_scripts:"false",npm_config_verify_deps_before_run:"false",pnpm_config_ignore_scripts:"true",pnpm_config_enable_pre_post_scripts:"false",pnpm_config_verify_deps_before_run:"false",YARN_ENABLE_SCRIPTS:"false",YARN_ENABLE_TELEMETRY:"0",SKIP_SIMPLE_GIT_HOOKS:"1",HUSKY:"0",LEFTHOOK:"0",GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.hooksPath",GIT_CONFIG_VALUE_0:noHooksDir()}}function git(cwd,...args){return execFileSync("git",["-c","core.hooksPath=/dev/null",...args],{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}function command(cwd,bin,args,timeoutMs=12e4,extraEnv={}){return new Promise(resolve2=>{let output="",timeout=!1,child=spawn(bin,args,{cwd,detached:process.platform!=="win32",env:{...Object.fromEntries(Object.entries(process.env).filter(([key])=>!/(?:TOKEN|SECRET|API_KEY|PASSWORD)/i.test(key))),...quietEnv(),...extraEnv},stdio:["ignore","pipe","pipe"]}),append=data=>{output=(output+data.toString()).slice(-2e5)};child.stdout.on("data",append),child.stderr.on("data",append);let timer=setTimeout(()=>{timeout=!0;try{process.platform!=="win32"&&child.pid?process.kill(-child.pid,"SIGKILL"):child.kill("SIGKILL")}catch{}},timeoutMs);child.on("error",e=>{clearTimeout(timer),resolve2({code:1,output:String(e),timeout:!1})}),child.on("close",code=>{clearTimeout(timer),resolve2({code:code??1,output,timeout})})})}function projectRoot(cwd){let root=realpathSync(resolve(cwd)),top=realpathSync(git(root,"rev-parse","--show-toplevel"));if(!existsSync(join(root,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`${root}: no package.json; run fix at the project root`);for(let dir=dirname(root);dir.startsWith(top)&&dir!==root;dir=dirname(dir)){if(existsSync(join(dir,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`run fix at the project root, ${dir} (workspace versions are upgraded together)`);if(dir===top)break}return{root,top,project:relative(top,root)||"."}}var count=(n,one)=>`${n} ${one}${n===1?"":"s"}`;function publicationBlockers(report,tool=uptideVersionInfo()){let blockers=[],v=report.verification;if(report.verificationPending)blockers.push("verification has not run");else if(!v.passed){let failed=(v.tests??[]).filter(t=>t.status==="failed"||t.status==="timeout"),reasons=[...v.newErrors?.length?[count(v.newErrors.length,"new type error")]:[],...(v.lint??[]).filter(l=>l.status==="failed").map(l=>`lint (${l.tool}) fails on the edited files`),...failed.map(t=>`tests ${t.status==="timeout"?"timed out":"failed"} in ${t.workspace}`)];blockers.push(`verification failed${reasons.length?`: ${reasons.join(", ")}`:" (files were left uncommitted)"}`)}return report.sourceChanged?.length&&blockers.push(`your checkout changed during the run (${report.sourceChanged.join("; ")})`),(report.uptideDirty||tool.uptideDirty)&&blockers.push("Uptide ran from a checkout with uncommitted changes; rerun from a committed build so the run is reproducible"),blockers}var GITHUB_BODY_LIMIT=65536;function remoteBranchHead(cwd,branch,io){try{let line=io.git(cwd,"ls-remote","--heads","origin",`refs/heads/${branch}`);return/^([0-9a-f]{40})\s/.exec(line)?.[1]}catch{return}}var defaults={git,command,print:console.log};async function publishTarget(cwd,repo,io=defaults){let auth=await io.command(cwd,"gh",["auth","status"]);if(auth.code)throw new UptideError("PUBLICATION_REFUSED",`--pr needs GitHub CLI signed in: ${auth.output.trim().split(`
7
- `).at(-1)??"gh auth status failed"}; run \`gh auth login\``);let remote=io.git(cwd,"remote","get-url","origin"),owner=/github\.com[:/]([^/]+)\/([^/\s]+?)(?:\.git)?$/.exec(remote)?.[1],scopes=/Token scopes: (.*)$/m.exec(auth.output)?.[1],lacksRepoScope=scopes!==void 0&&!/'repo'/.test(scopes),own;try{own=await viewRepository(cwd,remote,io)}catch(error){let message=error instanceof Error?error.message:String(error);throw new UptideError("PUBLICATION_REFUSED",[`--pr cannot reach ${remote} with the GitHub token: ${firstLine(message.replace(/^cannot resolve target repository: /,""))}`,"Likely causes, and what fixes each:",` the token lacks the \`repo\` scope${lacksRepoScope?` (it does: its scopes are ${scopes})`:""}: gh auth refresh -h github.com -s repo`,...owner?[` ${owner} enforces SSO and the token is not authorized for it: https://github.com/orgs/${owner}/sso`]:[]," the account has no access to the repository: ask for it, or run from a fork you own","Nothing was cloned or changed."].join(`
8
- `))}if(own.viewerPermission&&!["WRITE","MAINTAIN","ADMIN"].includes(own.viewerPermission))throw new UptideError("PUBLICATION_REFUSED",[`--pr needs push access to ${own.nameWithOwner??remote}; this account has ${own.viewerPermission.toLowerCase()} access only.`,"What fixes it:"," ask for write access to the repository, or",` fork it and run from the fork (gh repo fork ${own.nameWithOwner??""} --clone), then \`uptide pr --repo ${own.nameWithOwner??"<owner/name>"}\` opens the PR upstream`,...owner?[` if you do have write access through ${owner}, authorize the token for its SSO: https://github.com/orgs/${owner}/sso`]:[],"Nothing was cloned or changed. Without --pr the migration still runs, and `uptide pr` publishes it later."].join(`
9
- `));let target=repo?await viewRepository(cwd,repo,io):own;if(!target.defaultBranchRef?.name||!target.nameWithOwner)throw new UptideError("PUBLICATION_REFUSED","target repository has no default branch");return{nameWithOwner:target.nameWithOwner,base:target.defaultBranchRef.name,...own.isFork&&own.parent?.nameWithOwner?{parent:own.parent.nameWithOwner}:{}}}async function viewRepository(cwd,target,io){let metadata=await io.command(cwd,"gh",["repo","view",target,"--json","defaultBranchRef,nameWithOwner,isFork,parent,viewerPermission"]);if(metadata.code)throw new Error(`cannot resolve target repository: ${metadata.output}`);let parsed=JSON.parse(metadata.output),parent=parsed.parent?parsed.parent.nameWithOwner??(parsed.parent.owner?.login&&parsed.parent.name?`${parsed.parent.owner.login}/${parsed.parent.name}`:void 0):void 0;return{...parsed,parent:parent?{nameWithOwner:parent}:null}}var firstLine=text=>text.trim().split(`
10
- `)[0]??"";async function ensureLabel(cwd,nameWithOwner,io){let labels=await io.command(cwd,"gh",["label","list","--repo",nameWithOwner,"--search","uptide","--json","name"]);if(labels.code)return{ok:!1,step:"read",output:labels.output};let names=[];try{names=JSON.parse(labels.output.trim()||"[]")}catch{return{ok:!1,step:"read",output:labels.output}}if(names.some(l=>l.name==="uptide"))return{ok:!0};let label=await io.command(cwd,"gh",["label","create","uptide","--repo",nameWithOwner,"--description","Verified dependency migration proposed by Uptide","--color","2563EB"]);return label.code?{ok:!1,step:"created",output:label.output}:{ok:!0}}async function publish(report,yes=!1,io=defaults,options={}){let blockers=publicationBlockers(report,{uptideDirty:!1});if(blockers.length)throw new UptideError("PUBLICATION_REFUSED",`cannot publish an unverified migration: ${blockers.join("; ")}`);let cwd=options.cwd??report.repo,branch=report.branch;if(!/^uptide\//.test(branch))throw new Error("publication branch does not match the verified migration");if(options.cwd){let at=io.git(cwd,"rev-parse",branch);if(report.head&&at!==report.head)throw new UptideError("RUN_STALE",`${branch} is at ${at.slice(0,12)}, not the verified ${report.head.slice(0,12)}; run \`uptide verify --branch ${branch}\` first`)}else if(io.git(cwd,"branch","--show-current")!==branch)throw new Error("publication branch does not match the verified migration");let head=io.git(cwd,"rev-parse",branch),remote=io.git(cwd,"remote","get-url","origin"),own=await viewRepository(cwd,remote,io),target=options.repo?await viewRepository(cwd,options.repo,io):own,{defaultBranchRef,nameWithOwner}=target;if(!defaultBranchRef?.name||!nameWithOwner)throw new Error("target repository has no default branch");let base=defaultBranchRef.name,headRef=own.nameWithOwner&&own.nameWithOwner!==nameWithOwner?`${own.nameWithOwner.split("/")[0]}:${branch}`:branch,against=[`origin/${base}`,base].find(ref=>{try{return io.git(cwd,"rev-parse","--verify","--quiet",ref),!0}catch{return!1}}),commits=against?io.git(cwd,"log","--oneline",`${against}..${branch}`):"(base not fetched)",stat=against?io.git(cwd,"diff","--stat",`${against}...${branch}`):"";io.print(`Publication plan
11
- Branch: ${branch}
12
- Target remote: ${remote}
13
- Opening the PR on: ${nameWithOwner}${own.isFork&&own.parent?.nameWithOwner?` (a fork of ${own.parent.nameWithOwner}; pass --repo ${own.parent.nameWithOwner} to open it there)`:""}
14
- Base: ${base}
15
- Commits:
16
- ${commits}
17
- Diffstat:
18
- ${stat}`);let body=(io.readBody??(file=>readFileSync(file,"utf8")))(report.prBody);if(body.length>GITHUB_BODY_LIMIT)throw new UptideError("PUBLICATION_REFUSED",`the PR description is ${body.length.toLocaleString("en-US")} characters; GitHub accepts ${GITHUB_BODY_LIMIT.toLocaleString("en-US")}. Nothing was pushed. \`uptide pr --branch ${branch}\` renders it again within the limit`);if(!yes)throw new Error("publication requires --yes; nothing pushed");if(io.git(cwd,"rev-parse",branch)!==head)throw new Error("HEAD changed after publication planning");let labelled=await ensureLabel(cwd,nameWithOwner,io);labelled.ok||io.print(`Warning: the \`uptide\` label could not be ${labelled.step} (${firstLine(labelled.output)}); opening the PR without it.`),remoteBranchHead(cwd,branch,io)===head?io.print(`${branch} is already on origin at ${head.slice(0,12)}; not pushed again.`):io.git(cwd,"push","--set-upstream","origin",`${branch}:${branch}`);let existing=await io.command(cwd,"gh",["pr","list","--repo",nameWithOwner,"--head",branch,"--state","open","--json","number,url"]),open;try{existing.code||(open=JSON.parse(existing.output.trim()||"[]")[0])}catch{open=void 0}if(open){let edited=await io.command(cwd,"gh",["pr","edit",String(open.number),"--repo",nameWithOwner,"--body-file",report.prBody]);if(edited.code&&/projectCards|Projects \(classic\)/.test(edited.output)&&(edited=await io.command(cwd,"gh",["api","--method","PATCH",`repos/${nameWithOwner}/pulls/${open.number}`,"--field",`body=@${report.prBody}`,"--silent"])),edited.code)throw new Error(`cannot update the description of ${open.url}: ${edited.output}`);return io.print(`A pull request is already open for ${branch}: its description was updated.`),open.url}let create=label=>io.command(cwd,"gh",["pr","create","--repo",nameWithOwner,...options.draft===!1?[]:["--draft"],"--base",base,...label?["--label","uptide"]:[],"--title",report.mode==="pin"?`Pin the Stripe API version to ${report.apiVersion??""}`.trim():`Upgrade ${report.package} to ${report.target}`,"--body-file",report.prBody,"--head",headRef]),result=await create(labelled.ok);if(result.code&&labelled.ok&&/label/i.test(result.output)&&(io.print(`Warning: the \`uptide\` label could not be applied (${firstLine(result.output)}); opening the PR without it.`),result=await create(!1)),result.code)throw new Error(`gh pr create failed: ${result.output}`);let url=result.output.match(/https:\/\/[^\s]+\/pull\/\d+/g)?.at(-1);if(!url)throw new Error(`gh did not return a pull request URL: ${result.output}`);return url}export{git,command,projectRoot,publicationBlockers,GITHUB_BODY_LIMIT,publishTarget,publish};
@@ -1,7 +0,0 @@
1
- import { createRequire as __uptideCreateRequire } from 'node:module';
2
- import { fileURLToPath as __uptideFileURLToPath } from 'node:url';
3
- const require = __uptideCreateRequire(import.meta.url);
4
- const __filename = __uptideFileURLToPath(import.meta.url);
5
- const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
6
- var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));import{execFileSync}from"child_process";import{readFileSync}from"fs";import{dirname,join,resolve}from"path";import{fileURLToPath}from"url";var __defProp2=Object.defineProperty,__export=(target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},NoTypesError=class extends Error{constructor(packageName,version2){super(`${packageName}@${version2}: no type declarations, cannot analyze`),this.packageName=packageName,this.version=version2}packageName;version;code="NO_TYPES";name="NoTypesError"},PackageNotFoundError=class extends Error{constructor(packageName,registry){super(`${packageName}: not found on ${registry}`),this.packageName=packageName,this.registry=registry}packageName;registry;code="PACKAGE_NOT_FOUND";name="PackageNotFoundError"},RegistryAuthError=class extends Error{constructor(packageName,registry,status){super(`${packageName}: ${registry} answered HTTP ${status} (registry auth)`),this.packageName=packageName,this.registry=registry,this.status=status}packageName;registry;status;code="REGISTRY_AUTH";name="RegistryAuthError"},VersionNotFoundError=class extends Error{constructor(packageName,version2,available){super(`${packageName}@${version2}: version not published (${available.length} versions available)`),this.packageName=packageName,this.version=version2,this.available=available}packageName;version;available;code="VERSION_NOT_FOUND";name="VersionNotFoundError"},IntegrityError=class extends Error{constructor(packageName,version2,expected,actual){super(`${packageName}@${version2}: tarball integrity mismatch (expected ${expected}, got ${actual})`),this.packageName=packageName,this.version=version2,this.expected=expected,this.actual=actual}packageName;version;expected;actual;name="IntegrityError"},AdapterCapabilityError=class extends Error{constructor(adapter,capability){super(`adapter "${adapter}" does not implement ${capability}; cannot check usages`),this.adapter=adapter,this.capability=capability}adapter;capability;name="AdapterCapabilityError"},UptideError=class extends Error{constructor(code,message,options){super(message,options),this.code=code}code;name="UptideError"};function errorCode(error){return error&&typeof error=="object"&&"code"in error&&typeof error.code=="string"?error.code:"ANALYSIS_FAILED"}var version="0.1.0";function dirtyLines(porcelain){return porcelain.split(`
7
- `).filter(line=>line.trim()!=="").filter(line=>!/(?:^|\/)tsup\.config\.bundled_[\w-]+\.[cm]?js$/.test(line.slice(3)))}function uptideVersionInfo(env=process.env){return{uptideVersion:version,uptideCommit:"71e3ebf33cfc2de044fd64cb97bedca0abc4e066",uptideDirty:!1}}function uptideCommand(cliVersion){let tag=/^\d+\.\d+\.\d+-([a-z]+)/.exec(cliVersion)?.[1];return tag?`npx uptide@${tag}`:"npx uptide"}var UPTIDE_COMMAND=uptideCommand("0.3.0");export{__require,__commonJS,__toESM,__export,NoTypesError,PackageNotFoundError,RegistryAuthError,VersionNotFoundError,IntegrityError,AdapterCapabilityError,UptideError,errorCode,uptideVersionInfo,uptideCommand,UPTIDE_COMMAND};