@feng0531/dsh-vcs 0.7.3 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -5
- package/amend-host.mjs +48 -0
- package/branch-create-host.mjs +42 -0
- package/branch-create-preview.mjs +196 -0
- package/branch-delete-preview.mjs +214 -0
- package/branch-switch-host.mjs +13 -33
- package/commit-host.mjs +49 -0
- package/commit-object-publish.mjs +123 -0
- package/commit-preview.mjs +335 -0
- package/confirmed-operation.mjs +50 -0
- package/dist/client.js +25 -2
- package/dist/frontend.json +1 -1
- package/dist/interface.js +25 -2
- package/docs/RELEASING.md +2 -0
- package/git-blob-store.mjs +151 -0
- package/git-branch-create.mjs +156 -0
- package/git-branch-delete.mjs +175 -0
- package/git-lightweight-tag-create.mjs +181 -0
- package/git-object-store.mjs +162 -0
- package/git-ref-cas.mjs +119 -0
- package/git-tag-create.mjs +186 -0
- package/index-change-host.mjs +19 -0
- package/index-change.mjs +418 -0
- package/index-lock.mjs +231 -0
- package/index-stage-host.mjs +19 -0
- package/index.mjs +301 -4
- package/latest-commit.mjs +109 -0
- package/lightweight-tag-host.mjs +42 -0
- package/lightweight-tag-preview.mjs +183 -0
- package/line-index-host.mjs +58 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +47 -2
- package/partial-stage-host.mjs +52 -0
- package/partial-unstage-host.mjs +52 -0
- package/src/amend-plan.mjs +74 -0
- package/src/branch-delete-plan.mjs +113 -0
- package/src/commit-plan.mjs +78 -0
- package/src/git-commit-object.mjs +99 -0
- package/src/git-index.mjs +113 -0
- package/src/git-tag-object.mjs +110 -0
- package/src/index-tree.mjs +77 -0
- package/src/lightweight-tag-plan.mjs +64 -0
- package/src/line-index.mjs +168 -0
- package/src/partial-index.mjs +199 -0
- package/src/reflog.mjs +33 -0
- package/src/settled-reads.mjs +5 -0
- package/src/verified-branch-delete-plan.mjs +95 -0
- package/src/verified-commit-metadata.mjs +57 -0
- package/src/verified-commit-plan.mjs +49 -0
- package/src/verified-commit.mjs +84 -0
- package/src/verified-tag-plan.mjs +72 -0
- package/tag-create-host.mjs +31 -0
- package/tag-create-preview.mjs +215 -0
- package/tag-object-publish.mjs +49 -0
- package/vcs.mjs +29 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Internal preview and single-use apply. Caller owns repository writer exclusion.
|
|
2
|
+
// Observation barriers do not isolate hostile directory swaps or external ABA.
|
|
3
|
+
import * as fs from 'node:fs/promises';
|
|
4
|
+
import {constants} from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {git as safeGit} from './local-command.mjs';
|
|
7
|
+
import {readLatestCommit} from './latest-commit.mjs';
|
|
8
|
+
import {createVerifiedLightweightTagPlan} from './src/lightweight-tag-plan.mjs';
|
|
9
|
+
import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
|
|
10
|
+
import {createLightweightTag} from './git-lightweight-tag-create.mjs';
|
|
11
|
+
const snapshots=new WeakMap();
|
|
12
|
+
const fail=message=>Object.assign(new Error(message),{code:'vcs/lightweight-tag-preview'});
|
|
13
|
+
const check=()=>currentOperationBudget().throwIfExpired();
|
|
14
|
+
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
15
|
+
const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
|
|
16
|
+
const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
|
|
17
|
+
const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
|
|
18
|
+
function record(value,keys,required,label){
|
|
19
|
+
if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
|
|
20
|
+
const out=Object.create(null);
|
|
21
|
+
for(const key of Reflect.ownKeys(value)){
|
|
22
|
+
if(typeof key!=='string'||!keys.includes(key))throw fail('Unsupported '+label+' field');
|
|
23
|
+
const d=Object.getOwnPropertyDescriptor(value,key);
|
|
24
|
+
if(!d||!Object.hasOwn(d,'value'))throw fail(label+' requires own data properties');
|
|
25
|
+
out[key]=d.value;
|
|
26
|
+
}
|
|
27
|
+
for(const key of required)if(!Object.hasOwn(out,key))throw fail('Missing '+label+' '+key);
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
async function directory(file){
|
|
31
|
+
check();const s=await fs.lstat(file,{bigint:true});
|
|
32
|
+
if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(file)!==file)throw fail('Canonical metadata directory required');
|
|
33
|
+
return s;
|
|
34
|
+
}
|
|
35
|
+
async function raw(file,max){
|
|
36
|
+
check();const before=await fs.lstat(file,{bigint:true});
|
|
37
|
+
if(!plain(before)||before.size>BigInt(max))throw fail('Bounded single-link metadata file required');
|
|
38
|
+
const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
|
|
39
|
+
try{
|
|
40
|
+
const opened=await handle.stat({bigint:true});
|
|
41
|
+
if(!plain(opened)||!equal(version(before),version(opened)))throw fail('Stale metadata opening');
|
|
42
|
+
const bytes=Buffer.alloc(max+1);let n=0;
|
|
43
|
+
while(n<bytes.length){check();const r=await handle.read(bytes,n,bytes.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
|
|
44
|
+
const after=await handle.stat({bigint:true}),now=await fs.lstat(file,{bigint:true});
|
|
45
|
+
if(n>max||!plain(now)||!equal(version(opened),version(after))||!equal(version(after),version(now))||BigInt(n)!==after.size)throw fail('Stale metadata reading');
|
|
46
|
+
return [version(after),bytes.subarray(0,n).toString('hex')];
|
|
47
|
+
}finally{await handle.close();}
|
|
48
|
+
}
|
|
49
|
+
const forbidden=new Set(['packed-refs','reftable','commondir','gitdir','shallow','config.worktree','MERGE_HEAD','MERGE_MSG','CHERRY_PICK_HEAD','REVERT_HEAD','REBASE_HEAD','BISECT_LOG','BISECT_START','rebase-merge','rebase-apply','sequencer','worktrees','info/sparse-checkout','info/attributes','objects/info/alternates','objects/info/http-alternates'].map(s=>s.toLowerCase()));
|
|
50
|
+
async function metadata(git){
|
|
51
|
+
const rows=[];let nodes=0;
|
|
52
|
+
async function visit(file,rel){
|
|
53
|
+
check();if(++nodes>20000)throw fail('Metadata inspection limit exceeded');
|
|
54
|
+
const key=rel.toLowerCase();
|
|
55
|
+
if(forbidden.has(key)||key.endsWith('.lock')||key.endsWith('.promisor')||key.startsWith('sharedindex.')||key.startsWith('hooks/')&&!key.endsWith('.sample'))throw fail('Unsupported repository metadata: '+rel);
|
|
56
|
+
const s=await fs.lstat(file,{bigint:true});
|
|
57
|
+
if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('Linked or special repository metadata');
|
|
58
|
+
rows.push([rel,version(s)]);
|
|
59
|
+
if(s.isDirectory()){
|
|
60
|
+
const entries=await fs.readdir(file);
|
|
61
|
+
// Reject an excessive immediate fanout before sorting or visiting any child.
|
|
62
|
+
if(entries.length>20000-nodes)throw fail('Metadata inspection limit exceeded');
|
|
63
|
+
for(const name of entries.sort())await visit(path.join(file,name),rel?rel+'/'+name:name);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
await visit(git,'');return rows;
|
|
67
|
+
}
|
|
68
|
+
function absence(rows,name){
|
|
69
|
+
const entries=new Map(rows);
|
|
70
|
+
for(const parts of [['refs','tags',...name.split('/')],['logs','refs','tags',...name.split('/')]]){
|
|
71
|
+
let parent='';
|
|
72
|
+
for(let i=0;i<parts.length;i++){
|
|
73
|
+
const target=parent?parent+'/'+parts[i]:parts[i];
|
|
74
|
+
const matches=rows.filter(([rel])=>rel.toLowerCase()===target.toLowerCase());
|
|
75
|
+
if(!matches.length)break;
|
|
76
|
+
if(matches.length!==1||matches[0][0]!==target||i===parts.length-1)throw fail('Portable target namespace collision');
|
|
77
|
+
const v=entries.get(target);
|
|
78
|
+
if((Number(v[6])&0o170000)!==0o040000)throw fail('Target prefix or reflog collision');
|
|
79
|
+
parent=target;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
for(const expected of ['HEAD','config','refs','logs'])if(rows.some(([rel])=>rel.toLowerCase()===expected.toLowerCase()&&rel!==expected))throw fail('Noncanonical metadata spelling');
|
|
83
|
+
}
|
|
84
|
+
async function capture(root,name,created=false){
|
|
85
|
+
const rootStat=await directory(root),git=path.join(root,'.git'),gitStat=await directory(git);
|
|
86
|
+
const rows=await metadata(git);if(!created)absence(rows,name);
|
|
87
|
+
const head=await raw(path.join(git,'HEAD'),4096),config=await raw(path.join(git,'config'),256*1024);
|
|
88
|
+
const closing=await metadata(git);if(!created)absence(closing,name);
|
|
89
|
+
if(!equal(rows,closing)||!equal(identity(rootStat),identity(await directory(root)))||!equal(identity(gitStat),identity(await directory(git))))throw fail('Stale repository during capture');
|
|
90
|
+
check();return {root:identity(rootStat),git:identity(gitStat),head,config,rows};
|
|
91
|
+
}
|
|
92
|
+
// Observation barriers do not isolate external ABA or hostile directory swaps.
|
|
93
|
+
// Embedded born symbolic HEAD, loose absent tag namespace; <=20k metadata entries.
|
|
94
|
+
export async function prepareLightweightTagCreate(repo,options={}){
|
|
95
|
+
const r=record(repo,['type','root'],['type','root'],'repository');
|
|
96
|
+
const o=record(options,['name','signal'],['name'],'options');
|
|
97
|
+
if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Canonical Git root required');
|
|
98
|
+
// Validate names before I/O using the same pure policy; no fake object is published.
|
|
99
|
+
const name=o.name;
|
|
100
|
+
if(typeof name!=='string'||!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name)>1000||name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/'))throw fail('Safe portable short tag name required');
|
|
101
|
+
const forbiddenChars=/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u;
|
|
102
|
+
if(forbiddenChars.test(name)||name.includes('..')||name.includes('@{')||name.split('/').some(p=>!p||Buffer.byteLength(p)>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))throw fail('Safe portable short tag name required');
|
|
103
|
+
if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
|
|
104
|
+
return withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
|
|
105
|
+
const before=await capture(r.root,name),first=await readLatestCommit({type:r.type,root:r.root});
|
|
106
|
+
const body=await safeGit(r.root,['cat-file','commit',first.head],2*1024*1024);
|
|
107
|
+
const plan=createVerifiedLightweightTagPlan(body,{objectFormat:first.objectFormat,target:first.head,name,signal:currentOperationBudget().signal});
|
|
108
|
+
const last=await readLatestCommit({type:r.type,root:r.root}),after=await capture(r.root,name);
|
|
109
|
+
if(!equal(first,last)||plan.targetTree!==first.tree||!equal(before,after))throw fail('Stale repository changed during lightweight tag preview');
|
|
110
|
+
check();const summary=Object.freeze({action:plan.action,name,ref:plan.ref,objectFormat:plan.objectFormat,head:plan.target,currentRef:first.ref,targetTree:plan.targetTree,planId:plan.id});
|
|
111
|
+
snapshots.set(summary,{root:r.root,name,ref:plan.ref,original:before,facts:first,body:Buffer.from(body)});
|
|
112
|
+
return summary;
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Exact summary identity is a single-use capability; caller MUST hold writer exclusion.
|
|
117
|
+
// Never retry or roll back after the synchronous start boundary.
|
|
118
|
+
export async function applyLightweightTagCreate(repo,options={}){
|
|
119
|
+
const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
|
|
120
|
+
const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
|
|
121
|
+
const saved=snapshots.get(snapshot);snapshots.delete(snapshot);
|
|
122
|
+
if(!saved)throw fail('Invalid or consumed lightweight tag snapshot');
|
|
123
|
+
const o=record(options,['snapshot','signal','assertAuthorized','onStart'],['snapshot','assertAuthorized','onStart'],'apply options');
|
|
124
|
+
const r=record(repo,['type','root'],['type','root'],'repository');
|
|
125
|
+
if(r.type!=='git'||r.root!==saved.root||typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw fail('Snapshot repository or callbacks mismatch');
|
|
126
|
+
if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
|
|
127
|
+
let started=false;
|
|
128
|
+
try{return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
|
|
129
|
+
const {root,name,ref,original,facts}=saved,git=path.join(root,'.git'),logPath='logs/'+ref;
|
|
130
|
+
const effectiveConfig=()=>safeGit(root,['--git-dir='+git,'--work-tree='+root,'config','--no-includes','--null','--list'],256*1024);
|
|
131
|
+
const configBaseline=await effectiveConfig();
|
|
132
|
+
const isDir=v=>(Number(v[6])&0o170000)===0o040000;
|
|
133
|
+
let createdRows;
|
|
134
|
+
function envelope(rows){
|
|
135
|
+
const before=new Map(original.rows),now=new Map(rows),files=[ref,...(now.has(logPath)?[logPath]:[])];
|
|
136
|
+
const dirs=new Set(files.flatMap(file=>{const parts=file.split('/'),out=[''];for(let i=1;i<parts.length;i++)out.push(parts.slice(0,i).join('/'));return out;}));
|
|
137
|
+
for(const [p,v] of before){const n=now.get(p);
|
|
138
|
+
if(!n||!(dirs.has(p)&&isDir(v)?equal([...v.slice(0,3),v[6]],[...n.slice(0,3),n[6]]):equal(v,n)))throw fail('Original metadata changed: '+p);
|
|
139
|
+
}
|
|
140
|
+
for(const [p,v] of rows)if(!before.has(p)&&!files.includes(p)&&!(dirs.has(p)&&isDir(v)))throw fail('Foreign metadata addition: '+p);
|
|
141
|
+
}
|
|
142
|
+
async function verify(){
|
|
143
|
+
check();if(!(await effectiveConfig()).equals(configBaseline))throw fail('Effective Git configuration changed');
|
|
144
|
+
const state=await capture(root,name,started);
|
|
145
|
+
if(!equal(state.root,original.root)||!equal(state.git,original.git)||!equal(state.head,original.head)||!equal(state.config,original.config))throw fail('Original HEAD/config/identity changed');
|
|
146
|
+
if(!started){if(!equal(state,original))throw fail('Original metadata changed');}
|
|
147
|
+
else{
|
|
148
|
+
envelope(state.rows);
|
|
149
|
+
if(!new Map(state.rows).has(ref))throw fail('Created lightweight tag missing');
|
|
150
|
+
const [,hex]=await raw(path.join(git,...ref.split('/')),4096);
|
|
151
|
+
if(Buffer.from(hex,'hex').toString()!==facts.head+'\n')throw fail('Created ref changed');
|
|
152
|
+
if(new Map(state.rows).has(logPath)){
|
|
153
|
+
const [,hex]=await raw(path.join(git,...logPath.split('/')),4096);
|
|
154
|
+
if(!new RegExp('^'+'0'.repeat(facts.head.length)+' '+facts.head+' Dsh <dsh@localhost> [0-9]+ [+-][0-9]{4}\\tdsh: create lightweight tag\\n$').test(Buffer.from(hex,'hex').toString()))throw fail('Created reflog changed');
|
|
155
|
+
}
|
|
156
|
+
if(createdRows&&!equal(state.rows,createdRows))throw fail('Created metadata changed after verification');
|
|
157
|
+
createdRows=state.rows;
|
|
158
|
+
}
|
|
159
|
+
const [,branchHex]=await raw(path.join(git,...facts.ref.split('/')),4096);
|
|
160
|
+
if(Buffer.from(branchHex,'hex').toString()!==facts.head+'\n')throw fail('Current HEAD facts changed');
|
|
161
|
+
const closing=await capture(root,name,started);
|
|
162
|
+
if(!equal(closing,state))throw fail('Metadata changed during validation');
|
|
163
|
+
check();
|
|
164
|
+
}
|
|
165
|
+
const authorize=async()=>{
|
|
166
|
+
check();const signal=currentOperationBudget().signal;let abort;
|
|
167
|
+
try{await Promise.race([Promise.resolve(o.assertAuthorized()),new Promise((_,reject)=>{abort=()=>reject(signal.reason);signal.addEventListener('abort',abort,{once:true});if(signal.aborted)abort();})]);check();}
|
|
168
|
+
finally{if(abort)signal.removeEventListener('abort',abort);}
|
|
169
|
+
};
|
|
170
|
+
const authorized=async()=>{await verify();await authorize();await verify();};
|
|
171
|
+
// Authenticate full current facts once; original metadata pins the target object.
|
|
172
|
+
// The low-level writer authenticates the target bytes again before zero-old CAS.
|
|
173
|
+
if(!equal(await readLatestCommit({type:'git',root}),facts))throw fail('Current repository facts changed');
|
|
174
|
+
await authorized();
|
|
175
|
+
await createLightweightTag({type:'git',root},{ref,expectedCommitOid:facts.head,objectFormat:facts.objectFormat,signal:currentOperationBudget().signal,
|
|
176
|
+
assertAuthorized:authorized,onStart:()=>{if(started)throw fail('Duplicate lightweight tag start');started=true;return o.onStart();}});
|
|
177
|
+
await verify();await authorize();await verify();check();
|
|
178
|
+
return {name,ref,commit:facts.head,currentRef:facts.ref};
|
|
179
|
+
});}catch(cause){
|
|
180
|
+
if(!started)throw cause;
|
|
181
|
+
throw Object.assign(new Error('Lightweight tag creation started; inspect repository before further action. Never roll back or retry automatically.',{cause}),{code:'vcs/lightweight-tag-create-outcome-unknown',outcomeUnknown:true});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {randomBytes} from 'node:crypto';
|
|
2
|
+
import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
|
|
3
|
+
|
|
4
|
+
// Direction is selected only by these fixed host factories, never client input.
|
|
5
|
+
export function createLineStageCoordinator(options){return createLineCoordinator(options,'stage');}
|
|
6
|
+
export function createLineUnstageCoordinator(options){return createLineCoordinator(options,'unstage');}
|
|
7
|
+
|
|
8
|
+
// Host owns read access around plan/prepare; only confirmation acquires a lock.
|
|
9
|
+
function createLineCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32},direction){
|
|
10
|
+
const suffix=direction==='stage'?'Stage':'Unstage',action='line-'+direction;
|
|
11
|
+
const plans=new Map();
|
|
12
|
+
const invalid=()=>Object.assign(new Error('Line '+direction+' plan is expired, used, invalid, or belongs to a different Session/repository. Plan again.'),{code:'vcs/index-confirmation-invalid'});
|
|
13
|
+
const purge=()=>{const time=now();for(const [token,row]of plans)if(row.expiresAt<=time)plans.delete(token);};
|
|
14
|
+
const confirmation=createConfirmedOperationCoordinator({
|
|
15
|
+
operationKind:'line-index-'+direction,now,ttlMs,maxTokens,
|
|
16
|
+
prepare:(repository,{address,signal})=>{
|
|
17
|
+
purge();const row=plans.get(address.planToken);plans.delete(address.planToken);
|
|
18
|
+
const {entry,repository:identity,cwd}=address.binding;
|
|
19
|
+
if(!row||row.entry!==entry||row.repository!==identity||row.cwd!==cwd||row.sessionId!==address.sessionId||row.repositoryId!==address.repositoryId)throw invalid();
|
|
20
|
+
// Burn first. Validate the exact line-model array schema and copy own data
|
|
21
|
+
// before any await, without evaluating accessors or accepting inherited IDs.
|
|
22
|
+
const source=address.operationIds;
|
|
23
|
+
if(!Array.isArray(source)||Object.getPrototypeOf(source)!==Array.prototype)throw invalid();
|
|
24
|
+
const length=Object.getOwnPropertyDescriptor(source,'length').value;
|
|
25
|
+
if(!length||length>8000||length>row.snapshot.plan.operations.length||Reflect.ownKeys(source).length!==length+1)throw invalid();
|
|
26
|
+
const known=new Set(row.snapshot.plan.operations.map(operation=>operation.id)),seen=new Set(),ids=[];
|
|
27
|
+
for(let i=0;i<length;i++){
|
|
28
|
+
const descriptor=Object.getOwnPropertyDescriptor(source,String(i));
|
|
29
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value')||!descriptor.enumerable||typeof descriptor.value!=='string'||!known.has(descriptor.value)||seen.has(descriptor.value))throw invalid();
|
|
30
|
+
seen.add(descriptor.value);ids.push(descriptor.value);
|
|
31
|
+
}
|
|
32
|
+
return api['selectLineIndex'+suffix](repository,{snapshot:row.snapshot,operationIds:Object.freeze(ids),signal});
|
|
33
|
+
},
|
|
34
|
+
execute:(repository,request)=>api['applyLineIndex'+suffix](repository,request),
|
|
35
|
+
project:snapshot=>({action,path:snapshot.path,head:snapshot.head,index:snapshot.index,target:snapshot.target,planId:snapshot.planId,operationIds:[...snapshot.operationIds]}),
|
|
36
|
+
invalidCode:'vcs/index-confirmation-invalid',
|
|
37
|
+
unknownCode:'vcs/index-outcome-unknown',
|
|
38
|
+
unknownMessage:'Line '+(direction==='stage'?'staging':'unstaging')+' started but its final result could not be confirmed. Append-only object writes may remain even if the index was not updated. Refresh the repository and inspect the index before preparing another '+direction+'.',
|
|
39
|
+
});
|
|
40
|
+
return {
|
|
41
|
+
async plan(address,{entry,repository,cwd,signal,assertAuthorized}){
|
|
42
|
+
const {sessionId,repositoryId,id}=address;
|
|
43
|
+
const snapshot=await api['prepareLineIndex'+suffix]({...repository},{id,signal});
|
|
44
|
+
await assertAuthorized();signal?.throwIfAborted();purge();
|
|
45
|
+
while(plans.size>=maxTokens)plans.delete(plans.keys().next().value);
|
|
46
|
+
const planToken=randomBytes(32).toString('hex'),expiresAt=now()+ttlMs;
|
|
47
|
+
plans.set(planToken,{snapshot,expiresAt,entry,repository,cwd,sessionId,repositoryId});
|
|
48
|
+
return {action,path:snapshot.path,head:snapshot.head,index:snapshot.index,plan:snapshot.plan,planToken,expiresAt};
|
|
49
|
+
},
|
|
50
|
+
prepare(address,binding){
|
|
51
|
+
const captured={...binding};
|
|
52
|
+
return confirmation.prepare({sessionId:address.sessionId,repositoryId:address.repositoryId,planToken:address.planToken,operationIds:address.operationIds,binding:captured},captured);
|
|
53
|
+
},
|
|
54
|
+
confirm:(address,binding)=>confirmation.confirm(address,binding),
|
|
55
|
+
invalidate(entry){for(const [token,row]of plans)if(row.entry===entry)plans.delete(token);confirmation.invalidate(entry);},
|
|
56
|
+
clear(){plans.clear();confirmation.clear();},
|
|
57
|
+
};
|
|
58
|
+
}
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "VCS changes",
|
|
4
|
-
"description": "Git / SVN
|
|
4
|
+
"description": "Git / SVN review; confirmed restricted Git stage/unstage, commit/amend, branches and tags; read-only deletion assessment"
|
|
5
5
|
}
|
|
6
6
|
}
|
package/locale/zh.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@feng0531/dsh-vcs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
|
|
6
6
|
"type": "module",
|
|
@@ -17,6 +17,50 @@
|
|
|
17
17
|
"vcs.mjs",
|
|
18
18
|
"branch-switch.mjs",
|
|
19
19
|
"branch-switch-host.mjs",
|
|
20
|
+
"branch-create-host.mjs",
|
|
21
|
+
"branch-create-preview.mjs",
|
|
22
|
+
"git-branch-create.mjs",
|
|
23
|
+
"branch-delete-preview.mjs",
|
|
24
|
+
"git-branch-delete.mjs",
|
|
25
|
+
"src/branch-delete-plan.mjs",
|
|
26
|
+
"src/verified-branch-delete-plan.mjs",
|
|
27
|
+
"tag-create-host.mjs",
|
|
28
|
+
"tag-create-preview.mjs",
|
|
29
|
+
"tag-object-publish.mjs",
|
|
30
|
+
"git-tag-create.mjs",
|
|
31
|
+
"src/git-tag-object.mjs",
|
|
32
|
+
"src/verified-tag-plan.mjs",
|
|
33
|
+
"lightweight-tag-host.mjs",
|
|
34
|
+
"lightweight-tag-preview.mjs",
|
|
35
|
+
"git-lightweight-tag-create.mjs",
|
|
36
|
+
"src/lightweight-tag-plan.mjs",
|
|
37
|
+
"confirmed-operation.mjs",
|
|
38
|
+
"index-change.mjs",
|
|
39
|
+
"index-change-host.mjs",
|
|
40
|
+
"index-stage-host.mjs",
|
|
41
|
+
"partial-stage-host.mjs",
|
|
42
|
+
"partial-unstage-host.mjs",
|
|
43
|
+
"line-index-host.mjs",
|
|
44
|
+
"commit-host.mjs",
|
|
45
|
+
"amend-host.mjs",
|
|
46
|
+
"latest-commit.mjs",
|
|
47
|
+
"src/verified-commit-metadata.mjs",
|
|
48
|
+
"commit-preview.mjs",
|
|
49
|
+
"src/settled-reads.mjs",
|
|
50
|
+
"commit-object-publish.mjs",
|
|
51
|
+
"git-object-store.mjs",
|
|
52
|
+
"git-ref-cas.mjs",
|
|
53
|
+
"src/git-commit-object.mjs",
|
|
54
|
+
"src/index-tree.mjs",
|
|
55
|
+
"src/commit-plan.mjs",
|
|
56
|
+
"src/amend-plan.mjs",
|
|
57
|
+
"src/verified-commit.mjs",
|
|
58
|
+
"src/verified-commit-plan.mjs",
|
|
59
|
+
"index-lock.mjs",
|
|
60
|
+
"git-blob-store.mjs",
|
|
61
|
+
"src/git-index.mjs",
|
|
62
|
+
"src/partial-index.mjs",
|
|
63
|
+
"src/line-index.mjs",
|
|
20
64
|
"git-history.mjs",
|
|
21
65
|
"conflict-stages.mjs",
|
|
22
66
|
"image-preview.mjs",
|
|
@@ -29,6 +73,7 @@
|
|
|
29
73
|
"src/svn-path.mjs",
|
|
30
74
|
"src/svn-revision.mjs",
|
|
31
75
|
"src/commit-signature.mjs",
|
|
76
|
+
"src/reflog.mjs",
|
|
32
77
|
"src/operation-budget.mjs",
|
|
33
78
|
"src/historical-access.mjs",
|
|
34
79
|
"src/content-search.mjs",
|
|
@@ -44,7 +89,7 @@
|
|
|
44
89
|
"icon": "./icon.svg",
|
|
45
90
|
"scripts": {
|
|
46
91
|
"build": "node build.mjs",
|
|
47
|
-
"test": "node --test test/*.test.mjs",
|
|
92
|
+
"test": "node --test --test-concurrency=2 test/*.test.mjs",
|
|
48
93
|
"check": "npm run build && npm test",
|
|
49
94
|
"prepare": "npm run build",
|
|
50
95
|
"prepack": "npm run check",
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {randomBytes} from 'node:crypto';
|
|
2
|
+
import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
|
|
3
|
+
|
|
4
|
+
// Internal adapter: the host resolves ID-only addresses, supplies authenticated
|
|
5
|
+
// bindings, and holds read access around plan/prepare. Only confirm takes a lock.
|
|
6
|
+
export function createPartialStageCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32}){
|
|
7
|
+
const plans=new Map();
|
|
8
|
+
const invalid=()=>Object.assign(new Error('Partial stage plan is expired, used, or belongs to a different Session/repository. Plan again.'),{code:'vcs/index-confirmation-invalid'});
|
|
9
|
+
const purge=()=>{const time=now();for(const [token,row]of plans)if(row.expiresAt<=time)plans.delete(token);};
|
|
10
|
+
const confirmation=createConfirmedOperationCoordinator({
|
|
11
|
+
operationKind:'partial-index-stage',now,ttlMs,maxTokens,
|
|
12
|
+
prepare:(repository,{address,signal})=>{
|
|
13
|
+
purge();const row=plans.get(address.planToken);plans.delete(address.planToken);
|
|
14
|
+
const {entry,repository:identity,cwd}=address.binding;
|
|
15
|
+
if(!row||row.entry!==entry||row.repository!==identity||row.cwd!==cwd||row.sessionId!==address.sessionId||row.repositoryId!==address.repositoryId)throw invalid();
|
|
16
|
+
// Consume before validation or selection, and capture data properties before
|
|
17
|
+
// any await; neither the caller nor a deferred adapter can change the IDs.
|
|
18
|
+
const source=address.unitIds;
|
|
19
|
+
if(!Array.isArray(source)||!source.length||source.length>row.snapshot.plan.units.length)throw invalid();
|
|
20
|
+
const ids=[];
|
|
21
|
+
for(let i=0;i<source.length;i++){
|
|
22
|
+
const descriptor=Object.getOwnPropertyDescriptor(source,String(i));
|
|
23
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value')||typeof descriptor.value!=='string')throw invalid();
|
|
24
|
+
ids.push(descriptor.value);
|
|
25
|
+
}
|
|
26
|
+
return api.selectPartialIndexStage(repository,{snapshot:row.snapshot,unitIds:Object.freeze(ids),signal});
|
|
27
|
+
},
|
|
28
|
+
execute:(repository,request)=>api.applyIndexStage(repository,request),
|
|
29
|
+
project:snapshot=>({action:'partial-stage',path:snapshot.path,head:snapshot.head,index:snapshot.index,target:snapshot.target,planId:snapshot.planId,unitIds:[...snapshot.unitIds]}),
|
|
30
|
+
invalidCode:'vcs/index-confirmation-invalid',
|
|
31
|
+
unknownCode:'vcs/index-outcome-unknown',
|
|
32
|
+
unknownMessage:'Partial staging started but its final result could not be confirmed. Append-only object writes may remain even if the index was not updated. Refresh the repository and inspect the index before preparing another stage.',
|
|
33
|
+
});
|
|
34
|
+
return {
|
|
35
|
+
async plan(address,{entry,repository,cwd,signal,assertAuthorized}){
|
|
36
|
+
const {sessionId,repositoryId,id}=address;
|
|
37
|
+
const snapshot=await api.preparePartialIndexStage({...repository},{id,signal});
|
|
38
|
+
await assertAuthorized();signal?.throwIfAborted();purge();
|
|
39
|
+
while(plans.size>=maxTokens)plans.delete(plans.keys().next().value);
|
|
40
|
+
const planToken=randomBytes(32).toString('hex'),expiresAt=now()+ttlMs;
|
|
41
|
+
plans.set(planToken,{snapshot,expiresAt,entry,repository,cwd,sessionId,repositoryId});
|
|
42
|
+
return {action:'partial-stage',path:snapshot.path,head:snapshot.head,index:snapshot.index,plan:snapshot.plan,planToken,expiresAt};
|
|
43
|
+
},
|
|
44
|
+
prepare(address,binding){
|
|
45
|
+
const captured={...binding};
|
|
46
|
+
return confirmation.prepare({sessionId:address.sessionId,repositoryId:address.repositoryId,planToken:address.planToken,unitIds:address.unitIds,binding:captured},captured);
|
|
47
|
+
},
|
|
48
|
+
confirm:(address,binding)=>confirmation.confirm(address,binding),
|
|
49
|
+
invalidate(entry){for(const [token,row]of plans)if(row.entry===entry)plans.delete(token);confirmation.invalidate(entry);},
|
|
50
|
+
clear(){plans.clear();confirmation.clear();},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {randomBytes} from 'node:crypto';
|
|
2
|
+
import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
|
|
3
|
+
|
|
4
|
+
// Internal adapter: the host resolves ID-only addresses, supplies authenticated
|
|
5
|
+
// bindings, and holds read access around plan/prepare. Only confirm takes a lock.
|
|
6
|
+
export function createPartialUnstageCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32}){
|
|
7
|
+
const plans=new Map();
|
|
8
|
+
const invalid=()=>Object.assign(new Error('Partial unstage plan is expired, used, or belongs to a different Session/repository. Plan again.'),{code:'vcs/index-confirmation-invalid'});
|
|
9
|
+
const purge=()=>{const time=now();for(const [token,row]of plans)if(row.expiresAt<=time)plans.delete(token);};
|
|
10
|
+
const confirmation=createConfirmedOperationCoordinator({
|
|
11
|
+
operationKind:'partial-index-unstage',now,ttlMs,maxTokens,
|
|
12
|
+
prepare:(repository,{address,signal})=>{
|
|
13
|
+
purge();const row=plans.get(address.planToken);plans.delete(address.planToken);
|
|
14
|
+
const {entry,repository:identity,cwd}=address.binding;
|
|
15
|
+
if(!row||row.entry!==entry||row.repository!==identity||row.cwd!==cwd||row.sessionId!==address.sessionId||row.repositoryId!==address.repositoryId)throw invalid();
|
|
16
|
+
// Consume before validation or selection, and capture data properties before
|
|
17
|
+
// any await; neither the caller nor a deferred adapter can change the IDs.
|
|
18
|
+
const source=address.unitIds;
|
|
19
|
+
if(!Array.isArray(source)||!source.length||source.length>row.snapshot.plan.units.length)throw invalid();
|
|
20
|
+
const ids=[];
|
|
21
|
+
for(let i=0;i<source.length;i++){
|
|
22
|
+
const descriptor=Object.getOwnPropertyDescriptor(source,String(i));
|
|
23
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value')||typeof descriptor.value!=='string')throw invalid();
|
|
24
|
+
ids.push(descriptor.value);
|
|
25
|
+
}
|
|
26
|
+
return api.selectPartialIndexUnstage(repository,{snapshot:row.snapshot,unitIds:Object.freeze(ids),signal});
|
|
27
|
+
},
|
|
28
|
+
execute:(repository,request)=>api.applyPartialIndexUnstage(repository,request),
|
|
29
|
+
project:snapshot=>({action:'partial-unstage',path:snapshot.path,head:snapshot.head,index:snapshot.index,target:snapshot.target,planId:snapshot.planId,unitIds:[...snapshot.unitIds]}),
|
|
30
|
+
invalidCode:'vcs/index-confirmation-invalid',
|
|
31
|
+
unknownCode:'vcs/index-outcome-unknown',
|
|
32
|
+
unknownMessage:'Partial unstaging started but its final result could not be confirmed. Append-only object writes may remain even if the index was not updated. Refresh the repository and inspect the index before preparing another unstage.',
|
|
33
|
+
});
|
|
34
|
+
return {
|
|
35
|
+
async plan(address,{entry,repository,cwd,signal,assertAuthorized}){
|
|
36
|
+
const {sessionId,repositoryId,id}=address;
|
|
37
|
+
const snapshot=await api.preparePartialIndexUnstage({...repository},{id,signal});
|
|
38
|
+
await assertAuthorized();signal?.throwIfAborted();purge();
|
|
39
|
+
while(plans.size>=maxTokens)plans.delete(plans.keys().next().value);
|
|
40
|
+
const planToken=randomBytes(32).toString('hex'),expiresAt=now()+ttlMs;
|
|
41
|
+
plans.set(planToken,{snapshot,expiresAt,entry,repository,cwd,sessionId,repositoryId});
|
|
42
|
+
return {action:'partial-unstage',path:snapshot.path,head:snapshot.head,index:snapshot.index,plan:snapshot.plan,planToken,expiresAt};
|
|
43
|
+
},
|
|
44
|
+
prepare(address,binding){
|
|
45
|
+
const captured={...binding};
|
|
46
|
+
return confirmation.prepare({sessionId:address.sessionId,repositoryId:address.repositoryId,planToken:address.planToken,unitIds:address.unitIds,binding:captured},captured);
|
|
47
|
+
},
|
|
48
|
+
confirm:(address,binding)=>confirmation.confirm(address,binding),
|
|
49
|
+
invalidate(entry){for(const [token,row]of plans)if(row.entry===entry)plans.delete(token);confirmation.invalidate(entry);},
|
|
50
|
+
clear(){plans.clear();confirmation.clear();},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {parseGitIndex} from './git-index.mjs';
|
|
3
|
+
import {buildIndexTree} from './index-tree.mjs';
|
|
4
|
+
import {encodeGitCommit} from './git-commit-object.mjs';
|
|
5
|
+
import {readVerifiedCommitMetadata} from './verified-commit-metadata.mjs';
|
|
6
|
+
|
|
7
|
+
const MAX_INDEX_BYTES=8*1024*1024,MAX_HEAD_BYTES=2*1024*1024,MAX_MESSAGE_BYTES=64*1024;
|
|
8
|
+
const APPROVED_EXTENSIONS=new Set(['TREE','EOIE','IEOT']);
|
|
9
|
+
const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
10
|
+
function owned(bytes){const copy=Buffer.alloc(bytes.length);Buffer.prototype.copy.call(bytes,copy);return copy;}
|
|
11
|
+
function dataRecord(value,keys,label){
|
|
12
|
+
if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error('Invalid Git amend plan '+label+' record');
|
|
13
|
+
const copy=Object.create(null);
|
|
14
|
+
for(const key of Reflect.ownKeys(value)){
|
|
15
|
+
if(!keys.includes(key))throw Error('Unsupported Git amend plan '+label+' field');
|
|
16
|
+
const descriptor=Object.getOwnPropertyDescriptor(value,key);
|
|
17
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value'))throw Error('Git amend plan '+label+' fields must be own data properties');
|
|
18
|
+
copy[key]=descriptor.value;
|
|
19
|
+
}
|
|
20
|
+
return copy;
|
|
21
|
+
}
|
|
22
|
+
function captureCommitter(value){
|
|
23
|
+
const copy=dataRecord(value,['name','email','timestamp','timezone'],'committer');
|
|
24
|
+
for(const key of ['name','email','timezone'])if(typeof copy[key]!=='string')throw Error('Git identity '+key+' must be a string');
|
|
25
|
+
if(typeof copy.timestamp!=='number')throw Error('Invalid Git identity timestamp');
|
|
26
|
+
return copy;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Pure synchronous amend assembly; no repository, object lookup, refs or I/O.
|
|
30
|
+
// Own both bounded raw inputs before any option/identity Proxy traps or callbacks.
|
|
31
|
+
// Authenticate HEAD before using its exact parsed author and ordered 0..16 parents.
|
|
32
|
+
// UTF-8 encoding headers are supported by the metadata reader; signatures and other
|
|
33
|
+
// headers are rejected rather than silently discarded. New commits use the encoder's
|
|
34
|
+
// canonical UTF-8 headers. Only the complete new commit OID determines a no-op.
|
|
35
|
+
// Freeze metadata, not Buffer contents. All bodies are independent owned mutable
|
|
36
|
+
// copies; neither these bytes nor the deterministic ID confer publication authority.
|
|
37
|
+
// ID = SHA256(UTF8(JSON.stringify([domain,indexDigest,format,oldHead,oldTree,
|
|
38
|
+
// originalParents,newTree,newCommitOID]))). Tree graph caps come from buildIndexTree.
|
|
39
|
+
export function createAmendPlan(indexBuffer,headBody,inputs={}){
|
|
40
|
+
if(!Buffer.isBuffer(indexBuffer))throw Error('Git index must be a Buffer');
|
|
41
|
+
if(indexBuffer.length>MAX_INDEX_BYTES)throw Error('Git index byte limit exceeded');
|
|
42
|
+
if(!Buffer.isBuffer(headBody))throw Error('Git HEAD commit bytes must be a Buffer');
|
|
43
|
+
if(headBody.length>MAX_HEAD_BYTES)throw Error('Git HEAD commit body byte limit exceeded');
|
|
44
|
+
const indexSnapshot=owned(indexBuffer),headSnapshot=owned(headBody);
|
|
45
|
+
const captured=dataRecord(inputs,['objectFormat','head','committer','message','signal'],'input');
|
|
46
|
+
const {objectFormat='sha1',head,message,signal}=captured;
|
|
47
|
+
const committer=captureCommitter(captured.committer);
|
|
48
|
+
if(Buffer.isBuffer(message)&&message.length>MAX_MESSAGE_BYTES)throw Error('Git commit message byte limit exceeded');
|
|
49
|
+
const messageSnapshot=Buffer.isBuffer(message)?owned(message):message;
|
|
50
|
+
const check=()=>{
|
|
51
|
+
signal?.throwIfAborted?.();
|
|
52
|
+
if(signal?.aborted){const error=new Error('Git amend plan aborted');error.name='AbortError';throw error;}
|
|
53
|
+
};
|
|
54
|
+
check();
|
|
55
|
+
const previous=readVerifiedCommitMetadata(headSnapshot,{oid:head,objectFormat});
|
|
56
|
+
check();
|
|
57
|
+
const parsed=parseGitIndex(indexSnapshot,{objectFormat});
|
|
58
|
+
if(parsed.extensions.some(extension=>!APPROVED_EXTENSIONS.has(extension.signature)))throw Error('Unsupported semantic Git index extension for amend plan');
|
|
59
|
+
check();
|
|
60
|
+
const built=buildIndexTree(parsed.entries,{objectFormat});
|
|
61
|
+
check();
|
|
62
|
+
const encoded=encodeGitCommit({tree:built.root,parents:previous.parents,author:previous.author,committer,message:messageSnapshot},{objectFormat});
|
|
63
|
+
const messageText=typeof messageSnapshot==='string'?messageSnapshot:messageSnapshot.toString('utf8');
|
|
64
|
+
if(!messageText.trim())throw Error('Git amend plan message must be nonblank');
|
|
65
|
+
if(encoded.oid===previous.oid)throw Error('Git amend plan is a no-op: commit object is unchanged');
|
|
66
|
+
check();
|
|
67
|
+
const indexDigest=sha256(indexSnapshot),tree=built.root;
|
|
68
|
+
const id=sha256(JSON.stringify(['dsh-amend-plan-v1',indexDigest,objectFormat,previous.oid,previous.tree,previous.parents,tree,encoded.oid]));
|
|
69
|
+
const commit=Object.freeze({oid:encoded.oid,body:owned(encoded.body)});
|
|
70
|
+
const trees=Object.freeze(built.trees.map(value=>Object.freeze({path:value.path,oid:value.oid,body:owned(value.body)})));
|
|
71
|
+
const result=Object.freeze({id,objectFormat,indexDigest,head:previous.oid,previousTree:previous.tree,parents:previous.parents,author:previous.author,committer:Object.freeze({...committer}),message:messageText,tree,commit,trees});
|
|
72
|
+
check();
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const MAX_NODES=10000,MAX_PARENTS=16;
|
|
4
|
+
const fail=message=>new Error('Git branch delete plan: '+message);
|
|
5
|
+
function record(value,required,optional,label){
|
|
6
|
+
if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
|
|
7
|
+
const out=Object.create(null);
|
|
8
|
+
for(const key of Reflect.ownKeys(value)){
|
|
9
|
+
if(!required.includes(key)&&!optional.includes(key))throw fail('Unsupported '+label+' field');
|
|
10
|
+
const descriptor=Object.getOwnPropertyDescriptor(value,key);
|
|
11
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value'))throw fail(label+' requires own data properties');
|
|
12
|
+
out[key]=descriptor.value;
|
|
13
|
+
}
|
|
14
|
+
for(const key of required)if(!Object.hasOwn(out,key))throw fail('Missing '+label+' '+key);
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
function array(value,max,label){
|
|
18
|
+
if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)throw fail('Invalid '+label+' array');
|
|
19
|
+
const length=Object.getOwnPropertyDescriptor(value,'length');
|
|
20
|
+
if(!length||!Object.hasOwn(length,'value')||!Number.isInteger(length.value)||length.value>max)throw fail(label+' limit exceeded');
|
|
21
|
+
const size=length.value,keys=Reflect.ownKeys(value);
|
|
22
|
+
if(keys.length!==size+1)throw fail(label+' must be dense without extra fields');
|
|
23
|
+
const out=[];
|
|
24
|
+
for(let i=0;i<size;i++){
|
|
25
|
+
const descriptor=Object.getOwnPropertyDescriptor(value,String(i));
|
|
26
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value'))throw fail(label+' requires dense own data elements');
|
|
27
|
+
out.push(descriptor.value);
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
function oid(value,width){
|
|
32
|
+
if(typeof value!=='string'||value.length!==width||/[^0-9a-f]/.test(value)||/^0+$/.test(value))throw fail('Invalid object id');
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
function ref(value){
|
|
36
|
+
if(typeof value!=='string'||!value.startsWith('refs/heads/'))throw fail('Full refs/heads branch required');
|
|
37
|
+
const name=value.slice(11);
|
|
38
|
+
// Same portable short-name policy as branch-create-preview (without importing I/O).
|
|
39
|
+
if(!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name,'utf8')>1000||
|
|
40
|
+
name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
|
|
41
|
+
name.split('/').some(p=>!p||Buffer.byteLength(p,'utf8')>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))throw fail('Safe portable branch name required');
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Pure synchronous proposal, NOT deletion authorization. No filesystem, subprocess,
|
|
46
|
+
// network, object bytes, reference lookup or writes. Supplied OIDs/parent assertions
|
|
47
|
+
// are not authenticated: a future consumer must verify objects and fresh refs,
|
|
48
|
+
// worktrees, configuration and repository safety independently before any deletion.
|
|
49
|
+
// Require a CLOSED graph, both tip rows (even identical tips), and no cycle ANYWHERE.
|
|
50
|
+
// This deliberately rejects truncated histories even when a path could prove ancestry.
|
|
51
|
+
// <=10,000 rows, <=16 unique parents each (<=160,000 edges); iterative DFS only.
|
|
52
|
+
// Parent sets and rows sort by lowercase ASCII hex OID; canonical parent-order DFS
|
|
53
|
+
// produces the same proof/ID regardless of input row or parent permutations.
|
|
54
|
+
// ID = SHA256(UTF8(JSON.stringify([domain,format,[currentRef,currentOID],
|
|
55
|
+
// [targetRef,targetOID],sortedRowsOf[oid,sortedParents]]))). No force/merged inputs.
|
|
56
|
+
// Case-insensitive aliases of the current ref are rejected conservatively on ALL OSes.
|
|
57
|
+
// All records, arrays and scalar values are captured/validated before signal access.
|
|
58
|
+
// Signal callbacks can mutate caller inputs, never the owned graph. Cancellation is
|
|
59
|
+
// synchronous/cooperative; event-loop aborts cannot interrupt a synchronous call.
|
|
60
|
+
export function createBranchDeletePlan(inputs){
|
|
61
|
+
const captured=record(inputs,['current','target','commits'],['objectFormat','signal'],'input');
|
|
62
|
+
const {objectFormat='sha1',signal}=captured;
|
|
63
|
+
if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw fail('Unsupported object format');
|
|
64
|
+
const width=objectFormat==='sha1'?40:64;
|
|
65
|
+
const captureTip=(value,label)=>{
|
|
66
|
+
const tip=record(value,['ref','oid'],[],label);
|
|
67
|
+
return Object.freeze({ref:ref(tip.ref),oid:oid(tip.oid,width)});
|
|
68
|
+
};
|
|
69
|
+
const current=captureTip(captured.current,'current'),target=captureTip(captured.target,'target');
|
|
70
|
+
if(current.ref.toLowerCase()===target.ref.toLowerCase())throw fail('Cannot delete current branch or case-insensitive alias');
|
|
71
|
+
const rows=array(captured.commits,MAX_NODES,'commits').map(value=>{
|
|
72
|
+
const row=record(value,['oid','parents'],[],'commit');
|
|
73
|
+
const parents=array(row.parents,MAX_PARENTS,'parents').map(value=>oid(value,width));
|
|
74
|
+
if(new Set(parents).size!==parents.length)throw fail('Duplicate parent');
|
|
75
|
+
return {oid:oid(row.oid,width),parents:parents.sort()};
|
|
76
|
+
}).sort((a,b)=>a.oid<b.oid?-1:a.oid>b.oid?1:0);
|
|
77
|
+
const graph=new Map();
|
|
78
|
+
for(const row of rows){if(graph.has(row.oid))throw fail('Duplicate commit node');graph.set(row.oid,row.parents);}
|
|
79
|
+
if(!graph.has(current.oid)||!graph.has(target.oid))throw fail('Missing current or target commit node');
|
|
80
|
+
for(const row of rows)for(const parent of row.parents)if(!graph.has(parent))throw fail('Missing parent commit node: graph must be closed');
|
|
81
|
+
const check=()=>{
|
|
82
|
+
signal?.throwIfAborted?.();
|
|
83
|
+
if(signal?.aborted){const error=fail('Aborted');error.name='AbortError';throw error;}
|
|
84
|
+
};
|
|
85
|
+
check();
|
|
86
|
+
const colors=new Map();
|
|
87
|
+
for(const row of rows){
|
|
88
|
+
if(colors.has(row.oid))continue;
|
|
89
|
+
colors.set(row.oid,1);
|
|
90
|
+
const stack=[{oid:row.oid,next:0}];
|
|
91
|
+
while(stack.length){
|
|
92
|
+
check();
|
|
93
|
+
const frame=stack[stack.length-1],parents=graph.get(frame.oid);
|
|
94
|
+
if(frame.next===parents.length){colors.set(frame.oid,2);stack.pop();continue;}
|
|
95
|
+
const parent=parents[frame.next++],color=colors.get(parent);
|
|
96
|
+
if(color===1)throw fail('Cyclic commit graph');
|
|
97
|
+
if(color!==2){colors.set(parent,1);stack.push({oid:parent,next:0});}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const seen=new Set([current.oid]),path=[current.oid],stack=[{oid:current.oid,next:0}];
|
|
101
|
+
while(stack.length&&path[path.length-1]!==target.oid){
|
|
102
|
+
check();
|
|
103
|
+
const frame=stack[stack.length-1],parents=graph.get(frame.oid);
|
|
104
|
+
if(frame.next===parents.length){stack.pop();path.pop();continue;}
|
|
105
|
+
const parent=parents[frame.next++];
|
|
106
|
+
if(!seen.has(parent)){seen.add(parent);stack.push({oid:parent,next:0});path.push(parent);}
|
|
107
|
+
}
|
|
108
|
+
if(!path.length)throw fail('Target is not merged into current tip');
|
|
109
|
+
const id=createHash('sha256').update(JSON.stringify(['dsh-branch-delete-plan-v1',objectFormat,[current.ref,current.oid],[target.ref,target.oid],rows.map(row=>[row.oid,row.parents])])).digest('hex');
|
|
110
|
+
const result=Object.freeze({id,action:'branch-delete',objectFormat,current,target,merged:true,proof:Object.freeze(path)});
|
|
111
|
+
check();
|
|
112
|
+
return result;
|
|
113
|
+
}
|