dsh-git-desk 0.18.1 → 0.20.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.
@@ -0,0 +1,168 @@
1
+ const MAX_BODY = 2 * 1024 * 1024;
2
+ const PREFIX = '/git-rpc';
3
+ /**
4
+ * Write one JSON response.
5
+ * @param res the response.
6
+ * @param status the HTTP status.
7
+ * @param payload the JSON body.
8
+ */
9
+ function respond(res, status, payload) {
10
+ const body = JSON.stringify(payload);
11
+ res.writeHead(status, {
12
+ 'content-type': 'application/json',
13
+ 'content-length': Buffer.byteLength(body, 'utf8'),
14
+ 'cache-control': 'no-store',
15
+ });
16
+ res.end(body);
17
+ }
18
+ /**
19
+ * Build one failure envelope.
20
+ * @param rpcId the request id.
21
+ * @param code the stable error code.
22
+ * @param message the message.
23
+ * @returns the envelope.
24
+ */
25
+ function failure(rpcId, code, message) {
26
+ return {
27
+ type: 'server-response',
28
+ rpcId,
29
+ result: {
30
+ ok: false,
31
+ error: { code, message, details: {} },
32
+ },
33
+ };
34
+ }
35
+ /**
36
+ * Read a request body under the size cap.
37
+ * @param req the request.
38
+ * @returns the body text.
39
+ */
40
+ function readBody(req) {
41
+ return new Promise((resolve, reject) => {
42
+ const chunks = [];
43
+ let size = 0;
44
+ let tooLarge = false;
45
+ req.on('data', (chunk) => {
46
+ size += chunk.length;
47
+ if (size > MAX_BODY) {
48
+ tooLarge = true;
49
+ chunks.length = 0;
50
+ return;
51
+ }
52
+ if (!tooLarge)
53
+ chunks.push(chunk);
54
+ });
55
+ req.on('end', () => {
56
+ if (tooLarge)
57
+ reject(new Error('body-too-large'));
58
+ else
59
+ resolve(Buffer.concat(chunks).toString('utf8'));
60
+ });
61
+ req.on('error', reject);
62
+ });
63
+ }
64
+ /**
65
+ * Recognise the request envelope a client sends.
66
+ * @param value the parsed body.
67
+ * @returns whether it is a request envelope.
68
+ */
69
+ function isRequestEnvelope(value) {
70
+ if (value === null || typeof value !== 'object')
71
+ return false;
72
+ const candidate = value;
73
+ return (candidate.type === 'client-request' && typeof candidate.rpcId === 'string' && typeof candidate.method === 'string');
74
+ }
75
+ /**
76
+ * The generic RPC channel helper in this build reaches `webServer` from the
77
+ * connection context, which does not inject it. This route speaks the same
78
+ * envelope the browser caller expects and applies the connection admission
79
+ * check itself.
80
+ *
81
+ * @param ctx the host context.
82
+ * @param handler the endpoint handler.
83
+ * @returns the route disposer.
84
+ */
85
+ export function registerGitRoute(ctx, handler) {
86
+ return ctx.webServer.register({
87
+ kind: 'prefix',
88
+ path: PREFIX,
89
+ handler: async (req, res) => {
90
+ let admission;
91
+ try {
92
+ admission = ctx.connection.admit(req);
93
+ }
94
+ catch (error) {
95
+ respond(res, 500, failure('unknown', 'git/internal', String(error)));
96
+ return;
97
+ }
98
+ if ('rejection' in admission) {
99
+ res.writeHead(admission.rejection);
100
+ res.end(admission.rejection === 401 ? 'unauthorized' : 'forbidden');
101
+ return;
102
+ }
103
+ if (req.method !== 'POST') {
104
+ res.writeHead(405, { allow: 'POST' });
105
+ res.end('method not allowed');
106
+ return;
107
+ }
108
+ let endpoint;
109
+ try {
110
+ const url = new URL(req.url ?? '/', 'http://localhost');
111
+ if (!url.pathname.startsWith(`${PREFIX}/`)) {
112
+ respond(res, 404, failure('unknown', 'git/not-found', 'Unknown Git endpoint.'));
113
+ return;
114
+ }
115
+ endpoint = decodeURIComponent(url.pathname.slice(PREFIX.length + 1));
116
+ }
117
+ catch {
118
+ respond(res, 400, failure('unknown', 'git/bad-request', 'The Git endpoint is invalid.'));
119
+ return;
120
+ }
121
+ let text;
122
+ try {
123
+ text = await readBody(req);
124
+ }
125
+ catch {
126
+ respond(res, 413, failure('unknown', 'git/body-too-large', 'The Git request is too large.'));
127
+ return;
128
+ }
129
+ let parsed;
130
+ try {
131
+ parsed = JSON.parse(text);
132
+ }
133
+ catch {
134
+ respond(res, 400, failure('unknown', 'git/bad-request', 'The Git request is not valid JSON.'));
135
+ return;
136
+ }
137
+ if (!isRequestEnvelope(parsed)) {
138
+ respond(res, 400, failure('unknown', 'git/bad-request', 'The Git request envelope is invalid.'));
139
+ return;
140
+ }
141
+ const message = parsed;
142
+ if (message.method !== endpoint) {
143
+ respond(res, 400, failure(message.rpcId, 'git/bad-request', 'The Git endpoint does not match the request method.'));
144
+ return;
145
+ }
146
+ const peer = admission.peer;
147
+ if (peer.principal?.kind !== 'owner') {
148
+ respond(res, 200, failure(message.rpcId, 'git/forbidden', 'Git actions are available only to the local user.'));
149
+ return;
150
+ }
151
+ let result;
152
+ try {
153
+ result = await handler(endpoint, message.payload, undefined, peer);
154
+ }
155
+ catch (error) {
156
+ result = {
157
+ ok: false,
158
+ error: {
159
+ code: 'git/internal',
160
+ message: error instanceof Error ? error.message : String(error),
161
+ details: {},
162
+ },
163
+ };
164
+ }
165
+ respond(res, 200, { type: 'server-response', rpcId: message.rpcId, result });
166
+ },
167
+ });
168
+ }
@@ -0,0 +1,381 @@
1
+ const STATUS_LETTERS = new Set(['A', 'C', 'D', 'M', 'R', 'T', 'U', 'X']);
2
+ /**
3
+ * Split a porcelain record after its fixed leading fields, keeping spaces in the path.
4
+ * @param record the record.
5
+ * @param count the number of fields to skip.
6
+ * @returns the prefix and the path, or null when the record is short.
7
+ */
8
+ function splitFields(record, count) {
9
+ let index = 0;
10
+ for (let field = 0; field < count; field += 1) {
11
+ const space = record.indexOf(' ', index);
12
+ if (space === -1)
13
+ return null;
14
+ index = space + 1;
15
+ }
16
+ return [record.slice(0, index - 1), record.slice(index)];
17
+ }
18
+ /**
19
+ * Read the two-letter porcelain code into display flags.
20
+ * @param entry the entry being built.
21
+ * @param xy the two-letter code.
22
+ * @returns the flags.
23
+ */
24
+ function branchCode(entry, xy) {
25
+ const index = xy[0] ?? '.';
26
+ const worktree = xy[1] ?? '.';
27
+ const conflicted = entry.kind === 'unmerged' || index === 'U' || worktree === 'U';
28
+ const untracked = entry.kind === 'untracked';
29
+ const staged = !untracked && index !== '.' && index !== '?';
30
+ const unstaged = untracked || (worktree !== '.' && worktree !== '?');
31
+ let letter = 'M';
32
+ if (conflicted)
33
+ letter = 'C';
34
+ else if (untracked)
35
+ letter = 'U';
36
+ else if (index === 'A')
37
+ letter = 'A';
38
+ else if (index === 'D' || worktree === 'D')
39
+ letter = 'D';
40
+ else if (index === 'R' || worktree === 'R')
41
+ letter = 'R';
42
+ else if (index === 'C' || worktree === 'C')
43
+ letter = 'C';
44
+ else if (index === 'T' || worktree === 'T')
45
+ letter = 'T';
46
+ return {
47
+ index,
48
+ worktree,
49
+ conflicted,
50
+ untracked,
51
+ staged,
52
+ unstaged,
53
+ letter,
54
+ both: staged && unstaged,
55
+ };
56
+ }
57
+ /**
58
+ * Parse one porcelain v2 status document.
59
+ * @param text the document.
60
+ * @returns the branch, entries, and operation flags.
61
+ */
62
+ export function parseStatus(text) {
63
+ const branch = {
64
+ oid: null,
65
+ name: null,
66
+ upstream: null,
67
+ ahead: 0,
68
+ behind: 0,
69
+ detached: false,
70
+ initial: false,
71
+ };
72
+ const entries = [];
73
+ let skipNext = false;
74
+ let pendingRename = null;
75
+ for (const record of text.split('\0')) {
76
+ if (record === '')
77
+ continue;
78
+ if (skipNext) {
79
+ skipNext = false;
80
+ if (pendingRename !== null)
81
+ pendingRename.from = record;
82
+ pendingRename = null;
83
+ continue;
84
+ }
85
+ if (record.startsWith('# ')) {
86
+ const header = record.slice(2);
87
+ const space = header.indexOf(' ');
88
+ const key = space === -1 ? header : header.slice(0, space);
89
+ const value = space === -1 ? '' : header.slice(space + 1);
90
+ if (key === 'branch.oid') {
91
+ branch.oid = value === '(initial)' ? null : value;
92
+ branch.initial = value === '(initial)';
93
+ }
94
+ else if (key === 'branch.head') {
95
+ branch.detached = value === '(detached)';
96
+ branch.name = value === '(detached)' ? null : value;
97
+ }
98
+ else if (key === 'branch.upstream') {
99
+ branch.upstream = value;
100
+ }
101
+ else if (key === 'branch.ab') {
102
+ const match = /^\+(\d+) -(\d+)$/.exec(value);
103
+ if (match !== null) {
104
+ branch.ahead = Number(match[1]);
105
+ branch.behind = Number(match[2]);
106
+ }
107
+ }
108
+ continue;
109
+ }
110
+ if (record.startsWith('1 ')) {
111
+ const fields = splitFields(record, 8);
112
+ if (fields === null)
113
+ continue;
114
+ const xy = fields[0].split(' ')[1] ?? '.';
115
+ entries.push({ path: fields[1], kind: 'tracked', ...branchCode({ kind: 'tracked' }, xy) });
116
+ continue;
117
+ }
118
+ if (record.startsWith('2 ')) {
119
+ const fields = splitFields(record, 9);
120
+ if (fields === null)
121
+ continue;
122
+ const xy = fields[0].split(' ')[1] ?? '.';
123
+ const entry = {
124
+ path: fields[1],
125
+ kind: 'renamed',
126
+ from: null,
127
+ ...branchCode({ kind: 'renamed' }, xy),
128
+ };
129
+ entries.push(entry);
130
+ pendingRename = entry;
131
+ skipNext = true;
132
+ continue;
133
+ }
134
+ if (record.startsWith('u ')) {
135
+ const fields = splitFields(record, 10);
136
+ if (fields === null)
137
+ continue;
138
+ const xy = fields[0].split(' ')[1] ?? '.';
139
+ entries.push({ path: fields[1], kind: 'unmerged', ...branchCode({ kind: 'unmerged' }, xy) });
140
+ continue;
141
+ }
142
+ if (record.startsWith('? ')) {
143
+ const path = record.slice(2);
144
+ entries.push({ path, kind: 'untracked', ...branchCode({ kind: 'untracked' }, '??') });
145
+ continue;
146
+ }
147
+ }
148
+ for (const entry of entries) {
149
+ if (!STATUS_LETTERS.has(entry.letter))
150
+ entry.letter = 'M';
151
+ }
152
+ return {
153
+ branch,
154
+ entries,
155
+ merging: entries.some((entry) => entry.conflicted),
156
+ rebasing: false,
157
+ };
158
+ }
159
+ /**
160
+ * Parse one numstat document.
161
+ * @param text the document.
162
+ * @returns the counts per path.
163
+ */
164
+ export function parseNumstat(text) {
165
+ const result = new Map();
166
+ for (const record of text.split('\0')) {
167
+ if (record === '')
168
+ continue;
169
+ const parts = record.split('\t');
170
+ if (parts.length < 3)
171
+ continue;
172
+ const path = parts.slice(2).join('\t');
173
+ const rawAdd = parts[0] ?? '';
174
+ const rawDel = parts[1] ?? '';
175
+ const add = rawAdd === '-' ? null : Number(rawAdd);
176
+ const del = rawDel === '-' ? null : Number(rawDel);
177
+ result.set(path, {
178
+ add: add !== null && Number.isFinite(add) ? add : null,
179
+ del: del !== null && Number.isFinite(del) ? del : null,
180
+ binary: add === null || del === null,
181
+ });
182
+ }
183
+ return result;
184
+ }
185
+ /**
186
+ * Parse the zero-context hunk boundaries Git already computed.
187
+ * @param patch the patch text.
188
+ * @returns the hunks.
189
+ */
190
+ export function parseHunks(patch) {
191
+ const hunks = [];
192
+ for (const line of patch.split('\n')) {
193
+ if (!line.startsWith('@@ '))
194
+ continue;
195
+ const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
196
+ if (match === null)
197
+ continue;
198
+ hunks.push({
199
+ oldStart: Number(match[1]),
200
+ oldCount: match[2] === undefined ? 1 : Number(match[2]),
201
+ newStart: Number(match[3]),
202
+ newCount: match[4] === undefined ? 1 : Number(match[4]),
203
+ });
204
+ }
205
+ return hunks;
206
+ }
207
+ /**
208
+ * Split text into lines, remembering whether it ended with a newline.
209
+ * @param text the text.
210
+ * @returns the lines and the trailing newline state.
211
+ */
212
+ export function splitLines(text) {
213
+ if (text === '')
214
+ return { lines: [], trailing: false };
215
+ const lines = text.split('\n');
216
+ let trailing = false;
217
+ if (lines[lines.length - 1] === '') {
218
+ lines.pop();
219
+ trailing = true;
220
+ }
221
+ return { lines, trailing };
222
+ }
223
+ /**
224
+ * Join lines back into text.
225
+ * @param lines the lines.
226
+ * @param trailing whether the text ends with a newline.
227
+ * @returns the text.
228
+ */
229
+ export function joinLines(lines, trailing) {
230
+ if (lines.length === 0)
231
+ return '';
232
+ return lines.join('\n') + (trailing ? '\n' : '');
233
+ }
234
+ /**
235
+ * Build display rows from two complete versions and Git's hunk boundaries.
236
+ * Every unchanged line becomes a context row, so the caller can render the
237
+ * full file without asking Git for context.
238
+ *
239
+ * @param leftLines the old version.
240
+ * @param rightLines the new version.
241
+ * @param hunks the hunk boundaries.
242
+ * @returns the rows, blocks, and line counts.
243
+ */
244
+ export function buildRows(leftLines, rightLines, hunks) {
245
+ const rows = [];
246
+ const blocks = [];
247
+ let left = 0;
248
+ let right = 0;
249
+ const pushContext = (count) => {
250
+ for (let index = 0; index < count; index += 1) {
251
+ rows.push({ l: left + 1, r: right + 1, k: 'ctx' });
252
+ left += 1;
253
+ right += 1;
254
+ }
255
+ };
256
+ for (const hunk of hunks) {
257
+ if (hunk.oldCount === 0) {
258
+ pushContext(Math.max(0, hunk.oldStart - left));
259
+ const row = rows.length;
260
+ for (let index = 0; index < hunk.newCount; index += 1) {
261
+ rows.push({ l: null, r: right + 1, k: 'add' });
262
+ right += 1;
263
+ }
264
+ blocks.push({
265
+ leftStart: hunk.oldStart + 1,
266
+ leftEnd: hunk.oldStart,
267
+ rightStart: hunk.newStart,
268
+ rightEnd: hunk.newStart + hunk.newCount - 1,
269
+ kind: 'add',
270
+ row,
271
+ });
272
+ continue;
273
+ }
274
+ if (hunk.newCount === 0) {
275
+ pushContext(Math.max(0, hunk.oldStart - 1 - left));
276
+ const row = rows.length;
277
+ for (let index = 0; index < hunk.oldCount; index += 1) {
278
+ rows.push({ l: left + 1, r: null, k: 'del' });
279
+ left += 1;
280
+ }
281
+ blocks.push({
282
+ leftStart: hunk.oldStart,
283
+ leftEnd: hunk.oldStart + hunk.oldCount - 1,
284
+ rightStart: hunk.newStart + 1,
285
+ rightEnd: hunk.newStart,
286
+ kind: 'del',
287
+ row,
288
+ });
289
+ continue;
290
+ }
291
+ pushContext(Math.max(0, hunk.oldStart - 1 - left));
292
+ const row = rows.length;
293
+ const count = Math.max(hunk.oldCount, hunk.newCount);
294
+ for (let index = 0; index < count; index += 1) {
295
+ const hasLeft = index < hunk.oldCount;
296
+ const hasRight = index < hunk.newCount;
297
+ rows.push({
298
+ l: hasLeft ? left + 1 : null,
299
+ r: hasRight ? right + 1 : null,
300
+ k: hasLeft && hasRight ? 'mod' : hasLeft ? 'del' : 'add',
301
+ });
302
+ if (hasLeft)
303
+ left += 1;
304
+ if (hasRight)
305
+ right += 1;
306
+ }
307
+ blocks.push({
308
+ leftStart: hunk.oldStart,
309
+ leftEnd: hunk.oldStart + hunk.oldCount - 1,
310
+ rightStart: hunk.newStart,
311
+ rightEnd: hunk.newStart + hunk.newCount - 1,
312
+ kind: 'mod',
313
+ row,
314
+ });
315
+ }
316
+ pushContext(Math.max(0, leftLines.length - left));
317
+ let add = 0;
318
+ let del = 0;
319
+ for (const row of rows) {
320
+ if (row.k === 'add')
321
+ add += 1;
322
+ else if (row.k === 'del')
323
+ del += 1;
324
+ else if (row.k === 'mod') {
325
+ add += 1;
326
+ del += 1;
327
+ }
328
+ }
329
+ return { rows, blocks, add, del };
330
+ }
331
+ /**
332
+ * Parse one log document.
333
+ * @param text the document.
334
+ * @returns the commits.
335
+ */
336
+ export function parseLog(text) {
337
+ const commits = [];
338
+ for (const record of text.split('\x1e')) {
339
+ const raw = record.trim();
340
+ if (raw === '')
341
+ continue;
342
+ const [rawHash, parents, author, email, date, refs, subject] = raw.split('\x00');
343
+ const hash = rawHash?.trim();
344
+ if (hash === undefined || hash === '')
345
+ continue;
346
+ commits.push({
347
+ hash,
348
+ parents: parents !== undefined && parents !== '' ? parents.split(' ').filter(Boolean) : [],
349
+ author: author ?? '',
350
+ email: email ?? '',
351
+ date: date ?? '',
352
+ refs: refs !== undefined && refs !== ''
353
+ ? refs
354
+ .split(', ')
355
+ .map((ref) => ref.trim())
356
+ .filter(Boolean)
357
+ : [],
358
+ subject: subject ?? '',
359
+ });
360
+ }
361
+ return commits;
362
+ }
363
+ /**
364
+ * Parse one stash list document.
365
+ * @param text the document.
366
+ * @returns the stash entries.
367
+ */
368
+ export function parseStashes(text) {
369
+ const stashes = [];
370
+ for (const record of text.split('\x1e')) {
371
+ const raw = record.trim();
372
+ if (raw === '')
373
+ continue;
374
+ const [rawRef, message, rawHash] = raw.split('\x00');
375
+ const ref = rawRef?.trim();
376
+ if (ref === undefined || ref === '')
377
+ continue;
378
+ stashes.push({ ref, message: message ?? '', hash: rawHash?.trim() ?? '' });
379
+ }
380
+ return stashes;
381
+ }