@dev-loops/core 0.7.1 → 0.8.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,380 @@
1
+ import { runChild as _runChild } from "../cli/primitives.mjs";
2
+ import { parseJsonText } from "../github/review-threads.mjs";
3
+ import { resolveProjectSelector, findProject } from "./resolve-project.mjs";
4
+
5
+ // ── Validation ───────────────────────────────────────────────────────────
6
+
7
+ const OWNER_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
8
+ const REPO_NAME_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9_.-]*[a-zA-Z0-9])?$/;
9
+
10
+ function validateRepo(repo) {
11
+ if (!repo || typeof repo !== "string") {
12
+ throw Object.assign(new Error("--repo is required"), { code: "INVALID_REPO" });
13
+ }
14
+ const trimmed = repo.trim();
15
+ if (trimmed !== repo) {
16
+ throw Object.assign(
17
+ new Error(`--repo must not have leading/trailing whitespace, got "${repo}"`),
18
+ { code: "INVALID_REPO" },
19
+ );
20
+ }
21
+ const slashIdx = repo.indexOf("/");
22
+ if (slashIdx === -1) {
23
+ throw Object.assign(new Error(`--repo must be exactly owner/name, got "${repo}"`), { code: "INVALID_REPO" });
24
+ }
25
+ const owner = repo.slice(0, slashIdx);
26
+ const name = repo.slice(slashIdx + 1);
27
+ if (!owner || !name || !OWNER_RE.test(owner) || !REPO_NAME_RE.test(name)) {
28
+ throw Object.assign(new Error(`--repo must be exactly owner/name, got "${repo}"`), { code: "INVALID_REPO" });
29
+ }
30
+ return repo;
31
+ }
32
+
33
+ // ── API helpers ──────────────────────────────────────────────────────────
34
+
35
+ async function ghGraphql(query, vars, env, runChild = _runChild) {
36
+ const fieldArgs = [];
37
+ for (const [key, value] of Object.entries(vars)) {
38
+ fieldArgs.push("--field", `${key}=${value}`);
39
+ }
40
+ const result = await runChild(
41
+ "gh",
42
+ ["api", "graphql", "--field", `query=${query}`, ...fieldArgs],
43
+ env,
44
+ );
45
+ if (result.code !== 0) {
46
+ const detail = result.stderr.trim() || `exit code ${result.code}`;
47
+ throw Object.assign(new Error(`gh api graphql failed: ${detail}`), { code: "GH_API_ERROR" });
48
+ }
49
+ const payload = parseJsonText(result.stdout);
50
+ if (payload.errors && payload.errors.length > 0) {
51
+ throw Object.assign(
52
+ new Error(`GraphQL errors: ${payload.errors.map((e) => e.message).join("; ")}`),
53
+ { code: "GRAPHQL_ERROR" },
54
+ );
55
+ }
56
+ return payload;
57
+ }
58
+
59
+ // ── GraphQL fragments ────────────────────────────────────────────────────
60
+
61
+ const GET_USER_ID = [
62
+ "query($login:String!) {",
63
+ " user(login:$login) { id }",
64
+ "}"
65
+ ].join("\n");
66
+
67
+ const GET_ORG_ID = [
68
+ "query($login:String!) {",
69
+ " organization(login:$login) { id }",
70
+ "}"
71
+ ].join("\n");
72
+
73
+ const LIST_USER_PROJECTS = [
74
+ "query($login:String!, $after:String) {",
75
+ " user(login:$login) {",
76
+ " projectsV2(first:50, after:$after) {",
77
+ " pageInfo { hasNextPage endCursor }",
78
+ " nodes { id number title url }",
79
+ " }",
80
+ " }",
81
+ "}"
82
+ ].join("\n");
83
+
84
+ const LIST_ORG_PROJECTS = [
85
+ "query($login:String!, $after:String) {",
86
+ " organization(login:$login) {",
87
+ " projectsV2(first:50, after:$after) {",
88
+ " pageInfo { hasNextPage endCursor }",
89
+ " nodes { id number title url }",
90
+ " }",
91
+ " }",
92
+ "}"
93
+ ].join("\n");
94
+
95
+ const GET_PROJECT_FIELDS = [
96
+ "query($projectId:ID!, $after:String) {",
97
+ " node(id:$projectId) {",
98
+ " ... on ProjectV2 {",
99
+ " fields(first:50, after:$after) {",
100
+ " pageInfo { hasNextPage endCursor }",
101
+ " nodes {",
102
+ " ... on ProjectV2SingleSelectField {",
103
+ " id name",
104
+ " options { id name }",
105
+ " }",
106
+ " }",
107
+ " }",
108
+ " }",
109
+ " }",
110
+ "}"
111
+ ].join("\n");
112
+
113
+ const GET_PROJECT_ITEMS = [
114
+ "query($projectId:ID!, $after:String) {",
115
+ " node(id:$projectId) {",
116
+ " ... on ProjectV2 {",
117
+ " items(first:100, after:$after) {",
118
+ " pageInfo { hasNextPage endCursor }",
119
+ " nodes {",
120
+ " id",
121
+ " fieldValues(first:20) {",
122
+ " nodes {",
123
+ " ... on ProjectV2ItemFieldSingleSelectValue {",
124
+ " field { ... on ProjectV2SingleSelectField { id name } }",
125
+ " name",
126
+ " }",
127
+ " }",
128
+ " }",
129
+ " content {",
130
+ " ... on Issue { number title url id }",
131
+ " ... on PullRequest { number title url id }",
132
+ " }",
133
+ " }",
134
+ " }",
135
+ " }",
136
+ " }",
137
+ "}"
138
+ ].join("\n");
139
+
140
+ // ── Owner resolution ────────────────────────────────────────────────────
141
+
142
+ async function resolveOwner(login, env, runChild) {
143
+ const userPayload = await ghGraphql(GET_USER_ID, { login }, env, runChild);
144
+ if (userPayload?.data?.user?.id) {
145
+ return { id: userPayload.data.user.id, kind: "user" };
146
+ }
147
+ const orgPayload = await ghGraphql(GET_ORG_ID, { login }, env, runChild);
148
+ if (orgPayload?.data?.organization?.id) {
149
+ return { id: orgPayload.data.organization.id, kind: "org" };
150
+ }
151
+ throw Object.assign(
152
+ new Error(`Could not resolve owner ID for "${login}"`),
153
+ { code: "NO_USER_ID" },
154
+ );
155
+ }
156
+
157
+ // ── Paginated project listing ────────────────────────────────────────────
158
+
159
+ async function listAllProjects(login, kind, env, runChild) {
160
+ const query = kind === "org" ? LIST_ORG_PROJECTS : LIST_USER_PROJECTS;
161
+ const projects = [];
162
+ let after = null;
163
+ while (true) {
164
+ const vars = { login };
165
+ if (after) vars.after = after;
166
+ const payload = await ghGraphql(query, vars, env, runChild);
167
+ const connection = kind === "org"
168
+ ? payload?.data?.organization?.projectsV2
169
+ : payload?.data?.user?.projectsV2;
170
+ const nodes = connection?.nodes ?? [];
171
+ projects.push(...nodes);
172
+ const pageInfo = connection?.pageInfo ?? {};
173
+ if (!pageInfo.hasNextPage) break;
174
+ if (!pageInfo.endCursor) {
175
+ throw Object.assign(
176
+ new Error("Invalid projects list payload: hasNextPage is true but endCursor is missing"),
177
+ { code: "GH_API_ERROR" },
178
+ );
179
+ }
180
+ after = pageInfo.endCursor;
181
+ }
182
+ return projects;
183
+ }
184
+
185
+ // ── Paginated field listing ──────────────────────────────────────────────
186
+
187
+ async function listAllFields(projectId, env, runChild) {
188
+ const fields = [];
189
+ let after = null;
190
+ while (true) {
191
+ const vars = { projectId };
192
+ if (after) vars.after = after;
193
+ const payload = await ghGraphql(GET_PROJECT_FIELDS, vars, env, runChild);
194
+ const connection = payload?.data?.node?.fields;
195
+ const nodes = connection?.nodes ?? [];
196
+ fields.push(...nodes);
197
+ const pageInfo = connection?.pageInfo ?? {};
198
+ if (!pageInfo.hasNextPage) break;
199
+ if (!pageInfo.endCursor) {
200
+ throw Object.assign(
201
+ new Error("Invalid fields payload: hasNextPage is true but endCursor is missing"),
202
+ { code: "GH_API_ERROR" },
203
+ );
204
+ }
205
+ after = pageInfo.endCursor;
206
+ }
207
+ return fields;
208
+ }
209
+
210
+ // ── Paginated item listing ───────────────────────────────────────────────
211
+
212
+ async function listAllItems(projectId, env, runChild) {
213
+ const items = [];
214
+ let after = null;
215
+ while (true) {
216
+ const vars = { projectId };
217
+ if (after) vars.after = after;
218
+ const payload = await ghGraphql(GET_PROJECT_ITEMS, vars, env, runChild);
219
+ const connection = payload?.data?.node?.items;
220
+ const nodes = connection?.nodes ?? [];
221
+ items.push(...nodes);
222
+ const pageInfo = connection?.pageInfo ?? {};
223
+ if (!pageInfo.hasNextPage) break;
224
+ if (!pageInfo.endCursor) {
225
+ throw Object.assign(
226
+ new Error("Invalid items payload: hasNextPage is true but endCursor is missing"),
227
+ { code: "GH_API_ERROR" },
228
+ );
229
+ }
230
+ after = pageInfo.endCursor;
231
+ }
232
+ return items;
233
+ }
234
+
235
+ // ── Exit code classification ────────────────────────────────────────────
236
+
237
+ function classifyExitCode(err) {
238
+ if (err.code === "INVALID_REPO" || err.code === "INVALID_PROJECT" || err.code === "INVALID_ARGS") return 1;
239
+ if (err.code === "PROJECT_NOT_FOUND" || err.code === "FIELD_NOT_FOUND" || err.code === "COLUMN_NOT_FOUND") return 3;
240
+ return 2;
241
+ }
242
+
243
+ // ── Main logic ──────────────────────────────────────────────────────────
244
+
245
+ async function main(args, { env = process.env, runChild } = {}) {
246
+ const child = runChild ?? _runChild;
247
+ const repo = validateRepo(args.repo);
248
+ const [owner] = repo.split("/");
249
+ const selector = resolveProjectSelector(args);
250
+
251
+ // Mutual exclusion: --summary is the whole-board grouped view; --column/--limit
252
+ // are flat-mode knobs. Combining them is ambiguous.
253
+ if (args.summary && args.column) {
254
+ throw Object.assign(
255
+ new Error("--summary and --column are mutually exclusive (--column filters to one status; --summary groups the whole board)"),
256
+ { code: "INVALID_ARGS" },
257
+ );
258
+ }
259
+ if (args.summary && args.limit) {
260
+ throw Object.assign(
261
+ new Error("--summary and --limit are mutually exclusive; use --done-limit to cap the Done group (or terminal column if no Done column exists)"),
262
+ { code: "INVALID_ARGS" },
263
+ );
264
+ }
265
+ if (args.doneLimit !== undefined && !args.summary) {
266
+ throw Object.assign(
267
+ new Error("--done-limit only applies with --summary"),
268
+ { code: "INVALID_ARGS" },
269
+ );
270
+ }
271
+
272
+ // 1. Resolve owner (user or org).
273
+ // URI refs encode owner+kind directly; skip the API round-trip for owner resolution.
274
+ const projectOwner = selector.projectRef?.kind === "uri" ? selector.projectRef.owner : owner;
275
+ const ownerKind = selector.projectRef?.kind === "uri"
276
+ ? selector.projectRef.ownerKind
277
+ : (await resolveOwner(owner, env, child)).kind;
278
+
279
+ // 2. Resolve project
280
+ const projects = await listAllProjects(projectOwner, ownerKind, env, child);
281
+ const project = findProject(projects, selector, projectOwner);
282
+
283
+ // 3. Resolve Status field and target column
284
+ const fieldNodes = await listAllFields(project.id, env, child);
285
+ const statusField = fieldNodes.find((f) => f.name === "Status" && f.options);
286
+ if (!statusField) {
287
+ throw Object.assign(
288
+ new Error(`Status field not found in project "${project.title}" (number ${project.number})`),
289
+ { code: "FIELD_NOT_FOUND" },
290
+ );
291
+ }
292
+
293
+ let targetOption = null;
294
+ if (args.column) {
295
+ targetOption = statusField.options.find(
296
+ (o) => o.name === args.column,
297
+ );
298
+ if (!targetOption) {
299
+ const available = statusField.options.map((o) => o.name).join(", ");
300
+ throw Object.assign(
301
+ new Error(
302
+ `Column "${args.column}" not found in Status field. Available: ${available}`,
303
+ ),
304
+ { code: "COLUMN_NOT_FOUND" },
305
+ );
306
+ }
307
+ }
308
+
309
+ // 4. List and filter items (ordered by position ascending, GraphQL default)
310
+ const rawItems = await listAllItems(project.id, env, child);
311
+
312
+ const results = [];
313
+ for (const item of rawItems) {
314
+ const content = item.content;
315
+ if (!content) continue;
316
+
317
+ // Determine status from field values
318
+ let status = null;
319
+ const fieldValues = item.fieldValues?.nodes ?? [];
320
+ for (const fv of fieldValues) {
321
+ if (fv && fv.field && fv.field.name === "Status") {
322
+ status = fv.name;
323
+ break;
324
+ }
325
+ }
326
+
327
+ // Filter by column
328
+ if (args.column && status !== args.column) continue;
329
+
330
+ const isPr = content.__typename === "PullRequest";
331
+
332
+ results.push({
333
+ issueNumber: isPr ? null : content.number,
334
+ prNumber: isPr ? content.number : null,
335
+ title: content.title ?? null,
336
+ url: content.url ?? null,
337
+ itemId: item.id,
338
+ contentId: content.id ?? null,
339
+ status: status ?? null,
340
+ });
341
+ }
342
+
343
+ // 5a. Summary mode: group by Status column in board option order.
344
+ if (args.summary) {
345
+ // Object.create(null): board option names are free text, so a column named
346
+ // "__proto__"/"constructor" must be an own key, not touch Object.prototype.
347
+ const groups = Object.create(null);
348
+ for (const option of statusField.options) {
349
+ groups[option.name] = { count: 0, items: [] };
350
+ }
351
+ for (const r of results) {
352
+ // Items with null status belong to no Status option, so they are excluded here — matches --column filtering behavior.
353
+ if (r.status === null) continue;
354
+ const group = groups[r.status];
355
+ if (!group) continue; // status value not among current board options
356
+ group.count += 1;
357
+ group.items.push(r);
358
+ }
359
+ if (args.doneLimit !== undefined) {
360
+ // Cap "Done" per the issue AC; if no column is literally named "Done",
361
+ // fall back to the last board option (conventionally the terminal column)
362
+ // so --done-limit is honest instead of a silent no-op.
363
+ const doneGroup = groups.Done ?? groups[statusField.options.at(-1)?.name];
364
+ if (doneGroup) {
365
+ doneGroup.items = doneGroup.items.slice(0, args.doneLimit);
366
+ }
367
+ }
368
+ return { ok: true, groups };
369
+ }
370
+
371
+ // 5b. Flat mode: items are returned in position order from GraphQL. Apply limit.
372
+ const limited = args.limit ? results.slice(0, args.limit) : results;
373
+
374
+ return {
375
+ ok: true,
376
+ items: limited,
377
+ };
378
+ }
379
+
380
+ export { main, classifyExitCode };