nerdgram1337 1.4.6 → 1.4.8

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,1265 @@
1
+ import "./chunk-I5EOFHBL.js";
2
+ import {
3
+ ensureDataRoot,
4
+ getMetaPath,
5
+ httpFail,
6
+ isDataFileName
7
+ } from "./chunk-ULY5YEBR.js";
8
+ import "./chunk-5C6VO4LC.js";
9
+ import "./chunk-AFGGIQ22.js";
10
+
11
+ // server/src/sync/engine.ts
12
+ import fsp2 from "node:fs/promises";
13
+
14
+ // server/src/sync/configStore.ts
15
+ import fs2 from "node:fs/promises";
16
+
17
+ // server/src/sync/constants.ts
18
+ var SYNC_DOCS_URL = "https://github.com/NetworkNerd1337/NerdGram1337/blob/main/docs/github-sync.md";
19
+ var DEFAULT_IDLE_MS = 2e4;
20
+ var STRUCTURAL_IDLE_MS = 1e3;
21
+ var DEFAULT_GITHUB_TIMEOUT_MS = 2e4;
22
+ var MIRROR_DIR_NAME = ".nerdgram-git";
23
+ var TOKEN_FILE_NAME = "github-token";
24
+ var CONFIG_FILE_NAME = "github-sync.json";
25
+ var CONFLICTS_FILE_NAME = "github-conflicts.json";
26
+ var BRANCH = "main";
27
+ var BOILERPLATE = /* @__PURE__ */ new Set(["README.md", ".gitignore", ".gitattributes"]);
28
+ function idleMs() {
29
+ return boundedInt(process.env.NERDGRAM_SYNC_IDLE_MS, DEFAULT_IDLE_MS, 0, 10 * 60 * 1e3);
30
+ }
31
+ function githubTimeoutMs() {
32
+ return boundedInt(process.env.NERDGRAM_GITHUB_TIMEOUT_MS, DEFAULT_GITHUB_TIMEOUT_MS, 100, 12e4);
33
+ }
34
+ function boundedInt(raw, fallback, min, max) {
35
+ if (raw == null || raw.trim() === "") return fallback;
36
+ const value = Number(raw);
37
+ if (!Number.isFinite(value)) return fallback;
38
+ return Math.min(max, Math.max(min, Math.trunc(value)));
39
+ }
40
+
41
+ // server/src/sync/layout.ts
42
+ import fs from "node:fs/promises";
43
+ import path from "node:path";
44
+ function tokenPath() {
45
+ return path.join(getMetaPath(), TOKEN_FILE_NAME);
46
+ }
47
+ function configPath() {
48
+ return path.join(getMetaPath(), CONFIG_FILE_NAME);
49
+ }
50
+ function conflictsPath() {
51
+ return path.join(getMetaPath(), CONFLICTS_FILE_NAME);
52
+ }
53
+ function mirrorPath() {
54
+ const override = process.env.NERDGRAM_SYNC_MIRROR?.trim();
55
+ const root = ensureDataRoot();
56
+ const chosen = override ? path.resolve(override) : path.join(root, MIRROR_DIR_NAME);
57
+ assertSafeMirror(chosen, root);
58
+ return chosen;
59
+ }
60
+ function assertSafeMirror(mirror, dataRoot) {
61
+ const resolved = path.resolve(mirror);
62
+ const root = path.resolve(dataRoot);
63
+ if (resolved === root) {
64
+ throw httpFail(500, "Refusing to use the data directory as the git mirror.", "invalid");
65
+ }
66
+ const relative = path.relative(root, resolved);
67
+ const inside = relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
68
+ if (!inside) return;
69
+ const first = relative.split(path.sep)[0] ?? "";
70
+ if (!first.startsWith(".")) {
71
+ throw httpFail(
72
+ 500,
73
+ "A mirror inside the data directory must be a hidden folder the editor cannot address.",
74
+ "invalid"
75
+ );
76
+ }
77
+ }
78
+ function safeWorkspacePath(relativePath) {
79
+ if (!relativePath || relativePath.includes("\0")) return false;
80
+ const parts = relativePath.split("/");
81
+ return !parts.some((part) => part.length === 0 || part === "." || part === ".." || part.startsWith("."));
82
+ }
83
+ function isUserDiagram(relativePath) {
84
+ if (!safeWorkspacePath(relativePath)) return false;
85
+ return relativePath.split("/").pop()?.toLowerCase().endsWith(".mmd") ?? false;
86
+ }
87
+ function isDataFile(relativePath) {
88
+ if (!safeWorkspacePath(relativePath)) return false;
89
+ const name = relativePath.split("/").pop() ?? "";
90
+ return isDataFileName(name);
91
+ }
92
+ function isSyncedFile(relativePath) {
93
+ return isUserDiagram(relativePath) || isDataFile(relativePath);
94
+ }
95
+ function isBoilerplate(relativePath) {
96
+ return BOILERPLATE.has(relativePath);
97
+ }
98
+ async function listUserFiles(root) {
99
+ const out = /* @__PURE__ */ new Map();
100
+ await walkUserFiles(root, root, out);
101
+ return out;
102
+ }
103
+ async function walkUserFiles(root, dir, out) {
104
+ let entries;
105
+ try {
106
+ entries = await fs.readdir(dir, { withFileTypes: true });
107
+ } catch (err) {
108
+ const code = err.code;
109
+ if (code === "ENOENT") return;
110
+ throw err;
111
+ }
112
+ for (const entry of entries) {
113
+ if (entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
114
+ const abs = path.join(dir, entry.name);
115
+ if (entry.isDirectory()) {
116
+ await walkUserFiles(root, abs, out);
117
+ continue;
118
+ }
119
+ if (!entry.isFile()) continue;
120
+ const rel = path.relative(root, abs).split(path.sep).join("/");
121
+ if (!isSyncedFile(rel)) continue;
122
+ out.set(rel, await fs.readFile(abs, "utf8"));
123
+ }
124
+ }
125
+ async function writePrivateFile(file, content) {
126
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 448 });
127
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`);
128
+ await fs.writeFile(tmp, content, { encoding: "utf8", mode: 384 });
129
+ await fs.chmod(tmp, 384);
130
+ await fs.rename(tmp, file);
131
+ await fs.chmod(file, 384);
132
+ }
133
+
134
+ // server/src/sync/configStore.ts
135
+ function emptyConfig() {
136
+ return {
137
+ version: 1,
138
+ enabled: false,
139
+ clientId: null,
140
+ login: null,
141
+ owner: null,
142
+ repo: null,
143
+ private: true,
144
+ htmlUrl: null,
145
+ remoteUrl: null,
146
+ branch: BRANCH,
147
+ lastSyncAt: null,
148
+ lastPushedOid: null,
149
+ ahead: 0,
150
+ behind: 0
151
+ };
152
+ }
153
+ async function loadConfig() {
154
+ try {
155
+ const raw = await fs2.readFile(configPath(), "utf8");
156
+ const parsed = JSON.parse(raw);
157
+ const config = emptyConfig();
158
+ config.enabled = parsed.enabled === true;
159
+ config.clientId = typeof parsed.clientId === "string" ? parsed.clientId : null;
160
+ config.login = typeof parsed.login === "string" ? parsed.login : null;
161
+ config.owner = typeof parsed.owner === "string" ? parsed.owner : null;
162
+ config.repo = typeof parsed.repo === "string" ? parsed.repo : null;
163
+ config.private = parsed.private !== false;
164
+ config.htmlUrl = typeof parsed.htmlUrl === "string" ? parsed.htmlUrl : null;
165
+ config.remoteUrl = typeof parsed.remoteUrl === "string" ? parsed.remoteUrl : null;
166
+ config.branch = typeof parsed.branch === "string" && parsed.branch ? parsed.branch : BRANCH;
167
+ config.lastSyncAt = typeof parsed.lastSyncAt === "string" ? parsed.lastSyncAt : null;
168
+ config.lastPushedOid = typeof parsed.lastPushedOid === "string" ? parsed.lastPushedOid : null;
169
+ config.ahead = typeof parsed.ahead === "number" ? parsed.ahead : 0;
170
+ config.behind = typeof parsed.behind === "number" ? parsed.behind : 0;
171
+ if (configContainsSecret(raw)) {
172
+ throw new Error("GitHub sync config is damaged");
173
+ }
174
+ return config;
175
+ } catch (err) {
176
+ const code = err.code;
177
+ if (code === "ENOENT") return emptyConfig();
178
+ if (err instanceof SyntaxError) return emptyConfig();
179
+ throw err;
180
+ }
181
+ }
182
+ async function saveConfig(config) {
183
+ const body = `${JSON.stringify(config, null, 2)}
184
+ `;
185
+ if (configContainsSecret(body)) {
186
+ throw new Error("Refusing to store a token in GitHub sync config");
187
+ }
188
+ await writePrivateFile(configPath(), body);
189
+ }
190
+ function configContainsSecret(body) {
191
+ return /"(token|access_token|refresh_token|accessToken|refreshToken|device_code|client_secret)"\s*:/i.test(body) || /ghp_[A-Za-z0-9]/.test(body) || /gho_[A-Za-z0-9]/.test(body) || /ghu_[A-Za-z0-9]/.test(body) || /ghs_[A-Za-z0-9]/.test(body) || /ghr_[A-Za-z0-9]/.test(body) || /github_pat_[A-Za-z0-9_]/.test(body);
192
+ }
193
+ function clientIdOf(config) {
194
+ const fromEnv = process.env.NERDGRAM_GITHUB_CLIENT_ID?.trim();
195
+ if (fromEnv) return { id: fromEnv, source: "env" };
196
+ if (config.clientId) return { id: config.clientId, source: "config" };
197
+ return { id: null, source: null };
198
+ }
199
+
200
+ // server/src/sync/redact.ts
201
+ var TOKEN_SHAPES = [
202
+ /ghp_[A-Za-z0-9]+/g,
203
+ /github_pat_[A-Za-z0-9_]+/g,
204
+ /gho_[A-Za-z0-9]+/g,
205
+ /ghu_[A-Za-z0-9]+/g,
206
+ /ghs_[A-Za-z0-9]+/g,
207
+ /ghr_[A-Za-z0-9]+/g
208
+ ];
209
+ var extraSecrets = /* @__PURE__ */ new Set();
210
+ function rememberSecret(value) {
211
+ if (!value) return;
212
+ const trimmed = value.trim();
213
+ if (trimmed.length < 8) return;
214
+ extraSecrets.add(trimmed);
215
+ }
216
+ function redactText(input) {
217
+ let out = input;
218
+ const envValues = [process.env.NERDGRAM_GITHUB_TOKEN, process.env.NERDGRAM_GITHUB_CLIENT_SECRET];
219
+ for (const secret of extraSecrets) out = out.split(secret).join("[redacted]");
220
+ for (const secret of envValues) {
221
+ if (secret && secret.trim().length >= 8) out = out.split(secret.trim()).join("[redacted]");
222
+ }
223
+ for (const pattern of TOKEN_SHAPES) out = out.replace(pattern, "[redacted]");
224
+ out = out.replace(/Bearer\s+\S+/gi, "Bearer [redacted]");
225
+ out = out.replace(/Basic\s+[A-Za-z0-9+/=]+/gi, "Basic [redacted]");
226
+ out = out.replace(/x-access-token:[^\s"']+/gi, "x-access-token:[redacted]");
227
+ out = out.replace(/access_token["']?\s*[:=]\s*["']?[^"'\s&]+/gi, "access_token=[redacted]");
228
+ out = out.replace(/refresh_token["']?\s*[:=]\s*["']?[^"'\s&]+/gi, "refresh_token=[redacted]");
229
+ out = out.replace(/device_code["']?\s*[:=]\s*["']?[^"'\s&]+/gi, "device_code=[redacted]");
230
+ out = out.replace(/client_secret["']?\s*[:=]\s*["']?[^"'\s&]+/gi, "client_secret=[redacted]");
231
+ return out;
232
+ }
233
+ function scrubError(err) {
234
+ const code = err && typeof err === "object" && "code" in err && typeof err.code === "string" ? err.code : void 0;
235
+ const name = err instanceof Error ? err.name : "Error";
236
+ const message = redactText(err instanceof Error ? err.message : "Git request failed");
237
+ const next = new Error(message || "Git request failed");
238
+ next.name = name;
239
+ if (code && code !== message) {
240
+ Object.assign(next, { code });
241
+ }
242
+ const status = readErrorStatus(err);
243
+ if (status != null) Object.assign(next, { status, statusCode: status });
244
+ return next;
245
+ }
246
+ function readErrorStatus(err) {
247
+ if (!err || typeof err !== "object") return null;
248
+ const record = err;
249
+ if (typeof record.status === "number" && Number.isFinite(record.status)) return record.status;
250
+ if (typeof record.statusCode === "number" && Number.isFinite(record.statusCode)) return record.statusCode;
251
+ if (record.data && typeof record.data.statusCode === "number" && Number.isFinite(record.data.statusCode)) {
252
+ return record.data.statusCode;
253
+ }
254
+ return null;
255
+ }
256
+
257
+ // server/src/sync/secrets.ts
258
+ import fs3 from "node:fs/promises";
259
+ var EMPTY_AUTH = {
260
+ accessToken: null,
261
+ refreshToken: null,
262
+ expiresAt: null,
263
+ refreshExpiresAt: null,
264
+ deviceFlow: false,
265
+ source: null
266
+ };
267
+ async function readToken() {
268
+ const auth = await readStoredAuth();
269
+ return { token: auth.accessToken, source: auth.source };
270
+ }
271
+ async function readStoredAuth() {
272
+ const fromEnv = process.env.NERDGRAM_GITHUB_TOKEN?.trim();
273
+ if (fromEnv) {
274
+ rememberSecret(fromEnv);
275
+ return {
276
+ accessToken: fromEnv,
277
+ refreshToken: null,
278
+ expiresAt: null,
279
+ refreshExpiresAt: null,
280
+ deviceFlow: false,
281
+ source: "env"
282
+ };
283
+ }
284
+ let text = "";
285
+ try {
286
+ text = (await fs3.readFile(tokenPath(), "utf8")).trim();
287
+ } catch (err) {
288
+ const code = err.code;
289
+ if (code === "ENOENT") return { ...EMPTY_AUTH };
290
+ throw err;
291
+ }
292
+ if (!text) return { ...EMPTY_AUTH };
293
+ if (text.startsWith("{")) return parseTokenRecord(text);
294
+ rememberSecret(text);
295
+ return {
296
+ accessToken: text,
297
+ refreshToken: null,
298
+ expiresAt: null,
299
+ refreshExpiresAt: null,
300
+ deviceFlow: false,
301
+ source: "file"
302
+ };
303
+ }
304
+ async function writeToken(token, extras) {
305
+ const trimmed = token.trim();
306
+ if (!trimmed) throw new Error("Refusing to store an empty token");
307
+ rememberSecret(trimmed);
308
+ if (process.env.NERDGRAM_GITHUB_TOKEN?.trim()) {
309
+ return;
310
+ }
311
+ const refresh = extras?.refreshToken?.trim() || "";
312
+ if (refresh) rememberSecret(refresh);
313
+ const expiresIn = finiteOrNull(extras?.expiresIn);
314
+ const refreshExpiresIn = finiteOrNull(extras?.refreshExpiresIn);
315
+ if (!refresh && expiresIn == null && refreshExpiresIn == null) {
316
+ await writePrivateFile(tokenPath(), `${trimmed}
317
+ `);
318
+ return;
319
+ }
320
+ const now = Date.now();
321
+ const record = {
322
+ accessToken: trimmed,
323
+ refreshToken: refresh || null,
324
+ expiresAt: expiresIn == null ? null : now + expiresIn * 1e3,
325
+ refreshExpiresAt: refreshExpiresIn == null ? null : now + refreshExpiresIn * 1e3,
326
+ deviceFlow: extras?.deviceFlow === true
327
+ };
328
+ await writePrivateFile(tokenPath(), `${JSON.stringify(record)}
329
+ `);
330
+ }
331
+ function parseTokenRecord(text) {
332
+ let parsed;
333
+ try {
334
+ parsed = JSON.parse(text);
335
+ } catch {
336
+ console.error("GitHub sync: token_file The saved GitHub token file could not be read.");
337
+ return { ...EMPTY_AUTH };
338
+ }
339
+ if (!parsed || typeof parsed !== "object") return { ...EMPTY_AUTH };
340
+ const record = parsed;
341
+ const accessToken = stringField(record, "accessToken");
342
+ const refreshToken = stringField(record, "refreshToken");
343
+ if (accessToken) rememberSecret(accessToken);
344
+ if (refreshToken) rememberSecret(refreshToken);
345
+ return {
346
+ accessToken,
347
+ refreshToken,
348
+ expiresAt: epochField(record, "expiresAt"),
349
+ refreshExpiresAt: epochField(record, "refreshExpiresAt"),
350
+ deviceFlow: record.deviceFlow === true,
351
+ source: accessToken ? "file" : null
352
+ };
353
+ }
354
+ function stringField(record, key) {
355
+ const value = record[key];
356
+ return typeof value === "string" && value.trim() ? value.trim() : null;
357
+ }
358
+ function epochField(record, key) {
359
+ const value = record[key];
360
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
361
+ }
362
+ function finiteOrNull(value) {
363
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
364
+ }
365
+
366
+ // server/src/sync/github.ts
367
+ var REFRESH_SKEW_MS = 5 * 60 * 1e3;
368
+ var AUTH_REVOKED_MESSAGE = "GitHub rejected the saved authorization. It may have been revoked. Connect again.";
369
+ var AUTH_FORBIDDEN_MESSAGE = "GitHub refused this request. Check that the authorization still includes repository access.";
370
+ var AUTH_EXPIRED_MESSAGE = "GitHub authorization expired. Connect again.";
371
+ var APP_CODES = /* @__PURE__ */ new Set([
372
+ "auth_revoked",
373
+ "auth_expired",
374
+ "not_connected",
375
+ "offline",
376
+ "rate_limit",
377
+ "not_fast_forward",
378
+ "repo_missing",
379
+ "github",
380
+ "invalid",
381
+ "invalid_client",
382
+ "device_flow_disabled",
383
+ "name_taken",
384
+ "repo_not_empty",
385
+ "conflicts",
386
+ "locked"
387
+ ]);
388
+ var fetchImpl = globalThis.fetch.bind(globalThis);
389
+ function githubWeb() {
390
+ return (process.env.NERDGRAM_GITHUB_WEB || "https://github.com").replace(/\/$/, "");
391
+ }
392
+ function githubApi() {
393
+ return (process.env.NERDGRAM_GITHUB_API || "https://api.github.com").replace(/\/$/, "");
394
+ }
395
+ async function refreshAccessToken(input) {
396
+ rememberSecret(input.refreshToken);
397
+ const secret = input.clientSecret?.trim() || "";
398
+ if (secret) rememberSecret(secret);
399
+ const payload = {
400
+ client_id: input.clientId,
401
+ grant_type: "refresh_token",
402
+ refresh_token: input.refreshToken
403
+ };
404
+ if (secret) payload.client_secret = secret;
405
+ const response = await githubFetch(`${githubWeb()}/login/oauth/access_token`, {
406
+ method: "POST",
407
+ headers: acceptJson({ "Content-Type": "application/json" }),
408
+ body: JSON.stringify(payload)
409
+ });
410
+ const body = await readBody(response);
411
+ if (typeof body.access_token === "string" && body.access_token) return issuedFrom(body);
412
+ throw httpFail(401, AUTH_EXPIRED_MESSAGE, "auth_expired");
413
+ }
414
+ async function getRepo(token, owner, name) {
415
+ const response = await githubFetch(`${githubApi()}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, {
416
+ headers: authHeaders(await liveToken(token))
417
+ });
418
+ if (response.status === 404) {
419
+ await response.arrayBuffer().catch(() => void 0);
420
+ return null;
421
+ }
422
+ const body = await readBody(response);
423
+ if (!response.ok) throw classifyResponse(response.status, body, response.headers);
424
+ return repoFrom(body);
425
+ }
426
+ function repoFrom(body) {
427
+ const name = stringField2(body, "name");
428
+ const htmlUrl = stringField2(body, "html_url");
429
+ const cloneUrl = stringField2(body, "clone_url");
430
+ const ownerObj = body.owner;
431
+ const owner = ownerObj && typeof ownerObj === "object" && typeof ownerObj.login === "string" ? ownerObj.login : "";
432
+ if (!name || !owner || !cloneUrl) {
433
+ throw httpFail(502, "GitHub returned an unexpected repository response.", "github");
434
+ }
435
+ assertCleanRemoteUrl(cloneUrl);
436
+ return {
437
+ owner,
438
+ name,
439
+ private: body.private !== false,
440
+ htmlUrl: htmlUrl || `https://github.com/${owner}/${name}`,
441
+ cloneUrl,
442
+ defaultBranch: stringField2(body, "default_branch")
443
+ };
444
+ }
445
+ function assertCleanRemoteUrl(remoteUrl) {
446
+ if (remoteUrl.includes("\0") || /\s/.test(remoteUrl)) {
447
+ throw httpFail(400, "The Git remote URL is not valid.", "invalid");
448
+ }
449
+ if (/^(ghp_|github_pat_|gho_|ghu_|ghs_|ghr_)/.test(remoteUrl)) {
450
+ throw httpFail(400, "The Git remote URL must not contain a token.", "invalid");
451
+ }
452
+ if (remoteUrl.startsWith("https://") || remoteUrl.startsWith("http://")) {
453
+ let url;
454
+ try {
455
+ url = new URL(remoteUrl);
456
+ } catch {
457
+ throw httpFail(400, "The Git remote URL is not valid.", "invalid");
458
+ }
459
+ if (url.username || url.password || url.hash) {
460
+ throw httpFail(400, "The Git remote URL must not contain a token or password.", "invalid");
461
+ }
462
+ for (const key of ["access_token", "token", "client_secret", "device_code"]) {
463
+ if (url.searchParams.has(key)) {
464
+ throw httpFail(400, "The Git remote URL must not contain a token or password.", "invalid");
465
+ }
466
+ }
467
+ return;
468
+ }
469
+ if (remoteUrl.includes("://")) {
470
+ throw httpFail(400, "The Git remote URL is not valid.", "invalid");
471
+ }
472
+ }
473
+ function classifyResponse(status, body, headers) {
474
+ const remaining = headers.get("x-ratelimit-remaining");
475
+ const message = typeof body.message === "string" ? body.message : "";
476
+ if (status === 429 || remaining === "0" || /rate limit/i.test(message)) {
477
+ return httpFail(
478
+ 429,
479
+ "GitHub rate limit reached. Local commits stay on this computer. Sync again after the limit resets.",
480
+ "rate_limit"
481
+ );
482
+ }
483
+ if (status === 401) return httpFail(401, AUTH_REVOKED_MESSAGE, "auth_revoked");
484
+ if (status === 404) {
485
+ return httpFail(404, "That GitHub repository was not found.", "repo_missing");
486
+ }
487
+ if (status === 403) return httpFail(403, AUTH_FORBIDDEN_MESSAGE, "auth_revoked");
488
+ return httpFail(502, "GitHub sync failed.", "github");
489
+ }
490
+ function classifyNetworkError(err) {
491
+ const name = err instanceof Error ? err.name : "";
492
+ const code = err && typeof err === "object" && "code" in err && typeof err.code === "string" ? err.code : "";
493
+ const message = redactText(err instanceof Error ? err.message : "");
494
+ const status = httpStatusOf(err) ?? statusFromMessage(message);
495
+ if (code && APP_CODES.has(code) && err instanceof Error) {
496
+ if ("status" in err && typeof err.status === "number") return err;
497
+ return httpFail(status ?? statusForAppCode(code), err.message || "GitHub sync failed.", code);
498
+ }
499
+ if (status === 401 || code === "HttpError" && status === 401) {
500
+ return httpFail(401, AUTH_REVOKED_MESSAGE, "auth_revoked");
501
+ }
502
+ if (status === 403) return httpFail(403, AUTH_FORBIDDEN_MESSAGE, "auth_revoked");
503
+ if (err instanceof Error && "status" in err && "code" in err && code !== "HttpError") return err;
504
+ if (name === "AbortError" || code === "ABORT_ERR" || code === "ETIMEDOUT" || code === "ENOTFOUND" || code === "ECONNREFUSED" || code === "EAI_AGAIN" || code === "ENETUNREACH" || code === "ECONNRESET" || /timeout|network|fetch failed|getaddrinfo/i.test(message)) {
505
+ return httpFail(
506
+ 503,
507
+ "The network is unavailable. Local commits stay on this computer and push when the connection returns.",
508
+ "offline"
509
+ );
510
+ }
511
+ if (/non-fast-forward|not fast[- ]forward|rejected non-fast-forward|cannot lock ref/i.test(message)) {
512
+ return httpFail(
513
+ 409,
514
+ "The GitHub repository has commits that are not on this computer. NerdGram did not force-push. Pull when you want to reconcile.",
515
+ "not_fast_forward"
516
+ );
517
+ }
518
+ return httpFail(502, "GitHub sync failed.", "github");
519
+ }
520
+ function acceptJson(extra = {}) {
521
+ return {
522
+ Accept: "application/json",
523
+ "User-Agent": "NerdGram1337",
524
+ ...extra
525
+ };
526
+ }
527
+ function authHeaders(token, extra = {}) {
528
+ rememberSecret(token);
529
+ return {
530
+ Accept: "application/vnd.github+json",
531
+ Authorization: `Bearer ${token}`,
532
+ "User-Agent": "NerdGram1337",
533
+ "X-GitHub-Api-Version": "2022-11-28",
534
+ ...extra
535
+ };
536
+ }
537
+ async function githubFetch(url, init = {}, attempt = 0) {
538
+ assertNoSecretInUrl(url);
539
+ const timeout = AbortSignal.timeout(githubTimeoutMs());
540
+ const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
541
+ let response;
542
+ try {
543
+ response = await fetchImpl(url, { ...init, signal });
544
+ } catch (err) {
545
+ throw classifyNetworkError(err);
546
+ }
547
+ if (attempt === 0 && response.status === 401 && bearerValue(init)) {
548
+ let next;
549
+ try {
550
+ next = await refreshAfterUnauthorized();
551
+ } catch (err) {
552
+ await response.arrayBuffer().catch(() => void 0);
553
+ throw err;
554
+ }
555
+ if (next) {
556
+ await response.arrayBuffer().catch(() => void 0);
557
+ const headers = new Headers(init.headers);
558
+ headers.set("Authorization", `Bearer ${next}`);
559
+ return githubFetch(url, { ...init, headers }, attempt + 1);
560
+ }
561
+ }
562
+ return response;
563
+ }
564
+ function bearerValue(init) {
565
+ const value = new Headers(init.headers).get("authorization") ?? "";
566
+ const match = /^Bearer\s+(\S+)/i.exec(value);
567
+ return match?.[1] ?? null;
568
+ }
569
+ var refreshInflight = null;
570
+ async function ensureAccessToken() {
571
+ const auth = await readStoredAuth();
572
+ if (!auth.accessToken) return null;
573
+ if (auth.source !== "file" || auth.expiresAt == null) return auth.accessToken;
574
+ if (auth.expiresAt - Date.now() > REFRESH_SKEW_MS) return auth.accessToken;
575
+ const next = await refreshCoalesced();
576
+ return next ?? auth.accessToken;
577
+ }
578
+ async function refreshAfterUnauthorized() {
579
+ const auth = await readStoredAuth();
580
+ if (auth.source !== "file" || !auth.refreshToken) return null;
581
+ return refreshCoalesced();
582
+ }
583
+ async function authorizationBlock() {
584
+ const auth = await readStoredAuth();
585
+ if (!auth.accessToken || auth.source !== "file") return null;
586
+ if (auth.expiresAt == null || auth.expiresAt > Date.now()) return null;
587
+ if (await canRefresh(auth)) return null;
588
+ return { code: "auth_expired", message: AUTH_EXPIRED_MESSAGE, status: 401 };
589
+ }
590
+ function refreshCoalesced() {
591
+ if (!refreshInflight) {
592
+ refreshInflight = performRefresh().finally(() => {
593
+ refreshInflight = null;
594
+ });
595
+ }
596
+ return refreshInflight;
597
+ }
598
+ async function performRefresh() {
599
+ const auth = await readStoredAuth();
600
+ if (!auth.accessToken || auth.source !== "file") return null;
601
+ if (!auth.refreshToken) {
602
+ if (auth.expiresAt != null && auth.expiresAt - Date.now() <= REFRESH_SKEW_MS) {
603
+ throw httpFail(401, AUTH_EXPIRED_MESSAGE, "auth_expired");
604
+ }
605
+ return null;
606
+ }
607
+ if (auth.refreshExpiresAt != null && auth.refreshExpiresAt <= Date.now()) {
608
+ throw httpFail(401, AUTH_EXPIRED_MESSAGE, "auth_expired");
609
+ }
610
+ const secret = readClientSecret();
611
+ if (!auth.deviceFlow && !secret) throw httpFail(401, AUTH_EXPIRED_MESSAGE, "auth_expired");
612
+ const clientId = await clientIdForRefresh();
613
+ if (!clientId) throw httpFail(401, AUTH_EXPIRED_MESSAGE, "auth_expired");
614
+ const issued = await refreshAccessToken({
615
+ clientId,
616
+ refreshToken: auth.refreshToken,
617
+ clientSecret: secret
618
+ });
619
+ await writeToken(issued.token, {
620
+ refreshToken: issued.refreshToken ?? auth.refreshToken,
621
+ expiresIn: issued.expiresIn,
622
+ refreshExpiresIn: issued.refreshExpiresIn,
623
+ deviceFlow: auth.deviceFlow
624
+ });
625
+ return issued.token;
626
+ }
627
+ async function canRefresh(auth) {
628
+ if (!auth.refreshToken) return false;
629
+ if (auth.refreshExpiresAt != null && auth.refreshExpiresAt <= Date.now()) return false;
630
+ if (!auth.deviceFlow && !readClientSecret()) return false;
631
+ return Boolean(await clientIdForRefresh());
632
+ }
633
+ async function clientIdForRefresh() {
634
+ const config = await loadConfig();
635
+ return clientIdOf(config).id;
636
+ }
637
+ function readClientSecret() {
638
+ const secret = process.env.NERDGRAM_GITHUB_CLIENT_SECRET?.trim() || "";
639
+ if (!secret) return null;
640
+ rememberSecret(secret);
641
+ return secret;
642
+ }
643
+ function issuedFrom(body) {
644
+ const token = typeof body.access_token === "string" ? body.access_token : "";
645
+ const refreshToken = stringField2(body, "refresh_token");
646
+ rememberSecret(token);
647
+ if (refreshToken) rememberSecret(refreshToken);
648
+ return {
649
+ token,
650
+ refreshToken,
651
+ expiresIn: numberField(body, "expires_in"),
652
+ refreshExpiresIn: numberField(body, "refresh_token_expires_in")
653
+ };
654
+ }
655
+ async function liveToken(fallback) {
656
+ const fresh = await ensureAccessToken();
657
+ return fresh || fallback;
658
+ }
659
+ function httpStatusOf(err) {
660
+ return readErrorStatus(err);
661
+ }
662
+ function statusFromMessage(message) {
663
+ const match = /\bHTTP Error:\s*(401|403)\b/.exec(message);
664
+ return match ? Number(match[1]) : null;
665
+ }
666
+ function statusForAppCode(code) {
667
+ if (code === "auth_revoked" || code === "auth_expired" || code === "not_connected") return 401;
668
+ if (code === "offline") return 503;
669
+ if (code === "rate_limit") return 429;
670
+ if (code === "not_fast_forward" || code === "conflicts" || code === "repo_not_empty") return 409;
671
+ if (code === "repo_missing") return 404;
672
+ if (code === "locked") return 423;
673
+ if (code === "invalid" || code === "invalid_client" || code === "device_flow_disabled" || code === "name_taken") {
674
+ return 400;
675
+ }
676
+ return 502;
677
+ }
678
+ function assertNoSecretInUrl(raw) {
679
+ let url;
680
+ try {
681
+ url = new URL(raw);
682
+ } catch {
683
+ throw httpFail(400, "The GitHub URL is not valid.", "invalid");
684
+ }
685
+ if (url.username || url.password) {
686
+ throw httpFail(400, "Refusing to send a token in a URL.", "invalid");
687
+ }
688
+ for (const key of ["access_token", "token", "client_secret", "device_code"]) {
689
+ if (url.searchParams.has(key)) {
690
+ throw httpFail(400, "Refusing to send a token in a URL.", "invalid");
691
+ }
692
+ }
693
+ }
694
+ async function readBody(response) {
695
+ const text = await response.text();
696
+ if (!text) return {};
697
+ try {
698
+ const parsed = JSON.parse(text);
699
+ if (parsed && typeof parsed === "object") return parsed;
700
+ return {};
701
+ } catch {
702
+ return {};
703
+ }
704
+ }
705
+ function stringField2(body, key) {
706
+ const value = body[key];
707
+ return typeof value === "string" && value.trim() ? value.trim() : null;
708
+ }
709
+ function numberField(body, key) {
710
+ const value = body[key];
711
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
712
+ }
713
+
714
+ // server/src/sync/mirror.ts
715
+ import fs4 from "node:fs";
716
+ import fsp from "node:fs/promises";
717
+ import path2 from "node:path";
718
+ import git from "isomorphic-git";
719
+ import http from "isomorphic-git/http/node";
720
+ var nodeFs = fs4;
721
+ var PERSON = { name: "NerdGram1337", email: "nerdgram@localhost" };
722
+ var gitHttp = {
723
+ async request(request) {
724
+ try {
725
+ return await gitRequest(request, true);
726
+ } catch (err) {
727
+ throw classifyNetworkError(scrubError(err));
728
+ }
729
+ }
730
+ };
731
+ function gitBasicAuthorization(token) {
732
+ rememberSecret(token);
733
+ return `Basic ${Buffer.from(`x-access-token:${token}`, "utf8").toString("base64")}`;
734
+ }
735
+ async function gitRequest(request, allowRefresh) {
736
+ assertCleanRemoteUrl(request.url);
737
+ const token = await ensureAccessToken();
738
+ const headers = { ...request.headers ?? {} };
739
+ if (token) headers.Authorization = gitBasicAuthorization(token);
740
+ const timeout = AbortSignal.timeout(githubTimeoutMs());
741
+ const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout;
742
+ const response = await http.request({ ...request, headers, signal });
743
+ if (response.statusCode === 401 && allowRefresh) {
744
+ await drainBody(response.body);
745
+ const next = await refreshAfterUnauthorized();
746
+ if (next) return gitRequest(request, false);
747
+ }
748
+ if (response.statusCode === 401 || response.statusCode === 403) {
749
+ await drainBody(response.body);
750
+ throw response.statusCode === 401 ? httpFail(401, AUTH_REVOKED_MESSAGE, "auth_revoked") : httpFail(403, AUTH_FORBIDDEN_MESSAGE, "auth_revoked");
751
+ }
752
+ return response;
753
+ }
754
+ async function drainBody(body) {
755
+ if (!body) return;
756
+ try {
757
+ for await (const _chunk of body) {
758
+ }
759
+ } catch {
760
+ }
761
+ }
762
+ var README = `# NerdGram diagrams
763
+
764
+ This repository is a copy of diagrams from NerdGram1337.
765
+
766
+ The files are Mermaid \`.mmd\` diagrams, plus \`.csv\`, \`.json\`, \`.network.json\`, \`.cdp\`, and \`.lldp\` data files stored next to a generated diagram. Favorites, syntax overrides, trash, version history, thumbnails, the search index, and the GitHub token stay on the computer that runs NerdGram. They are not in this repository.
767
+
768
+ Editing a file on GitHub does not change NerdGram until you pull in the app. NerdGram will not force-push over commits made here.
769
+ `;
770
+ var GITIGNORE = `# Tokens, trash, history, and caches are not copied into this repository.
771
+ .meta/
772
+ `;
773
+ var GITATTRIBUTES = `*.mmd text eol=lf
774
+ *.csv text eol=lf
775
+ *.json text eol=lf
776
+ *.cdp text eol=lf
777
+ *.lldp text eol=lf
778
+ `;
779
+ async function ensureBoilerplate(dir) {
780
+ await writeIfChanged(path2.join(dir, "README.md"), README);
781
+ await writeIfChanged(path2.join(dir, ".gitignore"), GITIGNORE);
782
+ await writeIfChanged(path2.join(dir, ".gitattributes"), GITATTRIBUTES);
783
+ }
784
+ async function copyDataToMirror(dataRoot, dir) {
785
+ const desired = await listUserFiles(dataRoot);
786
+ await ensureBoilerplate(dir);
787
+ const changed = [];
788
+ for (const [rel, content] of desired) {
789
+ const abs = mirrorFile(dir, rel);
790
+ const current = await readTextIfFile(abs);
791
+ if (current === content) continue;
792
+ await fsp.mkdir(path2.dirname(abs), { recursive: true });
793
+ await fsp.writeFile(abs, content, "utf8");
794
+ changed.push(rel);
795
+ }
796
+ await deleteExtra(dir, dir, desired);
797
+ return changed;
798
+ }
799
+ async function commitMirror(dir, message, parents) {
800
+ const matrix = await git.statusMatrix({ fs: nodeFs, dir });
801
+ let dirty = false;
802
+ for (const [filepath, head, workdir, stage] of matrix) {
803
+ if (head === 1 && workdir === 1 && stage === 1) continue;
804
+ if (head === 0 && workdir === 0) continue;
805
+ dirty = true;
806
+ if (workdir === 0) await git.remove({ fs: nodeFs, dir, filepath });
807
+ else await git.add({ fs: nodeFs, dir, filepath });
808
+ }
809
+ if (!dirty && !parents) return null;
810
+ const oid = await git.commit({
811
+ fs: nodeFs,
812
+ dir,
813
+ message: message.trim() || "Update diagrams",
814
+ author: PERSON,
815
+ committer: PERSON,
816
+ parent: parents
817
+ });
818
+ return oid;
819
+ }
820
+ async function fetchRemote(dir) {
821
+ try {
822
+ await git.fetch({
823
+ fs: nodeFs,
824
+ http: gitHttp,
825
+ dir,
826
+ remote: "origin",
827
+ ref: BRANCH,
828
+ singleBranch: true,
829
+ tags: false,
830
+ headers: await authHeaders2()
831
+ });
832
+ } catch (err) {
833
+ throw classifyNetworkError(scrubError(err));
834
+ }
835
+ }
836
+ async function pushBranch(dir) {
837
+ let result;
838
+ try {
839
+ result = await git.push({
840
+ fs: nodeFs,
841
+ http: gitHttp,
842
+ dir,
843
+ remote: "origin",
844
+ ref: BRANCH,
845
+ remoteRef: BRANCH,
846
+ // Never force-push. A rejected update stays rejected.
847
+ force: false,
848
+ headers: await authHeaders2()
849
+ });
850
+ } catch (err) {
851
+ throw classifyNetworkError(scrubError(err));
852
+ }
853
+ if (!result.ok) {
854
+ const detail = result.error || Object.values(result.refs ?? {})[0]?.error || "";
855
+ throw classifyNetworkError(new Error(detail || "push rejected"));
856
+ }
857
+ }
858
+ async function headOid(dir) {
859
+ try {
860
+ return await git.resolveRef({ fs: nodeFs, dir, ref: "HEAD" });
861
+ } catch {
862
+ return null;
863
+ }
864
+ }
865
+ async function remoteOid(dir) {
866
+ try {
867
+ return await git.resolveRef({ fs: nodeFs, dir, ref: `refs/remotes/origin/${BRANCH}` });
868
+ } catch {
869
+ return null;
870
+ }
871
+ }
872
+ async function mergeBase(dir, local, remote) {
873
+ try {
874
+ const bases = await git.findMergeBase({ fs: nodeFs, dir, oids: [local, remote] });
875
+ return bases[0] ?? null;
876
+ } catch {
877
+ return null;
878
+ }
879
+ }
880
+ async function readUserFilesAt(dir, ref) {
881
+ const out = /* @__PURE__ */ new Map();
882
+ let oid = ref;
883
+ try {
884
+ oid = await git.resolveRef({ fs: nodeFs, dir, ref });
885
+ } catch {
886
+ return out;
887
+ }
888
+ let files = [];
889
+ try {
890
+ files = await git.listFiles({ fs: nodeFs, dir, ref: oid });
891
+ } catch {
892
+ return out;
893
+ }
894
+ for (const filepath of files) {
895
+ if (!isSyncedFile(filepath)) continue;
896
+ const { blob } = await git.readBlob({ fs: nodeFs, dir, oid, filepath });
897
+ out.set(filepath, Buffer.from(blob).toString("utf8"));
898
+ }
899
+ return out;
900
+ }
901
+ async function authHeaders2() {
902
+ const token = await ensureAccessToken();
903
+ if (!token) return {};
904
+ return { Authorization: gitBasicAuthorization(token) };
905
+ }
906
+ function mirrorFile(dir, relativePath) {
907
+ if (!isSyncedFile(relativePath)) {
908
+ throw httpFail(400, "Invalid path", "invalid");
909
+ }
910
+ return path2.join(dir, ...relativePath.split("/"));
911
+ }
912
+ async function readTextIfFile(file) {
913
+ try {
914
+ return await fsp.readFile(file, "utf8");
915
+ } catch (err) {
916
+ const code = err.code;
917
+ if (code === "ENOENT") return null;
918
+ throw err;
919
+ }
920
+ }
921
+ async function writeIfChanged(file, content) {
922
+ const current = await readTextIfFile(file);
923
+ if (current === content) return;
924
+ await fsp.mkdir(path2.dirname(file), { recursive: true });
925
+ await fsp.writeFile(file, content, "utf8");
926
+ }
927
+ async function deleteExtra(mirror, dir, desired) {
928
+ let entries;
929
+ try {
930
+ entries = await fsp.readdir(dir, { withFileTypes: true });
931
+ } catch (err) {
932
+ const code = err.code;
933
+ if (code === "ENOENT") return;
934
+ throw err;
935
+ }
936
+ for (const entry of entries) {
937
+ if (entry.name === ".git") continue;
938
+ const abs = path2.join(dir, entry.name);
939
+ const rel = path2.relative(mirror, abs).split(path2.sep).join("/");
940
+ if (entry.isDirectory()) {
941
+ if (entry.name.startsWith(".")) {
942
+ await fsp.rm(abs, { recursive: true, force: true });
943
+ continue;
944
+ }
945
+ await deleteExtra(mirror, abs, desired);
946
+ const left = await fsp.readdir(abs).catch(() => ["keep"]);
947
+ if (left.length === 0) await fsp.rmdir(abs).catch(() => void 0);
948
+ continue;
949
+ }
950
+ if (isBoilerplate(rel)) continue;
951
+ if (entry.name.startsWith(".") || !isSyncedFile(rel) || !desired.has(rel)) {
952
+ await fsp.rm(abs, { force: true });
953
+ }
954
+ }
955
+ }
956
+
957
+ // server/src/sync/engine.ts
958
+ var suppress = 0;
959
+ var timer = null;
960
+ var summaries = [];
961
+ var structuralPending = false;
962
+ var chain = Promise.resolve();
963
+ var active = 0;
964
+ var maxActive = 0;
965
+ var testHook = null;
966
+ var device = null;
967
+ var memoryError = null;
968
+ function noteLocalChange(change) {
969
+ if (suppress > 0) return;
970
+ void recordChange(change);
971
+ }
972
+ async function recordChange(change) {
973
+ if (suppress > 0) return;
974
+ const config = await loadConfig();
975
+ if (!config.enabled || suppress > 0) return;
976
+ if (change.summary && !summaries.includes(change.summary)) summaries.push(change.summary);
977
+ if (change.kind === "structural") {
978
+ structuralPending = true;
979
+ schedule(STRUCTURAL_IDLE_MS);
980
+ return;
981
+ }
982
+ if (!structuralPending) schedule(idleMs());
983
+ }
984
+ async function syncNow() {
985
+ return exclusive(async () => {
986
+ const config = await loadConfig();
987
+ if (!config.enabled) throw httpFail(409, "GitHub sync is not on.", "invalid");
988
+ await pushLocal(config, true);
989
+ return publicStatus();
990
+ });
991
+ }
992
+ async function pushLocal(config, push) {
993
+ if (timer) {
994
+ clearTimeout(timer);
995
+ timer = null;
996
+ }
997
+ const mirror = mirrorPath();
998
+ const changed = await copyDataToMirror(ensureDataRoot(), mirror);
999
+ const message = commitMessage(changed);
1000
+ await commitMirror(mirror, message);
1001
+ if (!push) return;
1002
+ try {
1003
+ await probeIfHttp(config);
1004
+ await fetchRemote(mirror);
1005
+ } catch (err) {
1006
+ const failure = asFailure(err);
1007
+ memoryError = failure;
1008
+ const head = await headOid(mirror);
1009
+ config.ahead = head && head !== config.lastPushedOid ? 1 : 0;
1010
+ await saveConfig(config);
1011
+ logSyncFailure(failure);
1012
+ return;
1013
+ }
1014
+ const compared = await compare(mirror);
1015
+ config.ahead = compared.ahead;
1016
+ config.behind = compared.behind;
1017
+ await saveConfig(config);
1018
+ if (compared.behind > 0) {
1019
+ memoryError = asFailure(
1020
+ httpFail(
1021
+ 409,
1022
+ "The GitHub repository has commits that are not on this computer. NerdGram did not force-push. Pull when you want to reconcile.",
1023
+ "not_fast_forward"
1024
+ )
1025
+ );
1026
+ logSyncFailure(memoryError);
1027
+ return;
1028
+ }
1029
+ await pushIfForward(config);
1030
+ }
1031
+ async function pushIfForward(config) {
1032
+ const mirror = mirrorPath();
1033
+ let compared;
1034
+ try {
1035
+ await probeIfHttp(config);
1036
+ await fetchRemote(mirror);
1037
+ compared = await compare(mirror);
1038
+ } catch (err) {
1039
+ memoryError = asFailure(err);
1040
+ logSyncFailure(memoryError);
1041
+ await saveConfig(config);
1042
+ return;
1043
+ }
1044
+ config.ahead = compared.ahead;
1045
+ config.behind = compared.behind;
1046
+ if (compared.behind > 0) {
1047
+ memoryError = asFailure(
1048
+ httpFail(
1049
+ 409,
1050
+ "The GitHub repository has commits that are not on this computer. NerdGram did not force-push. Pull when you want to reconcile.",
1051
+ "not_fast_forward"
1052
+ )
1053
+ );
1054
+ await saveConfig(config);
1055
+ logSyncFailure(memoryError);
1056
+ return;
1057
+ }
1058
+ const head = await headOid(mirror);
1059
+ if (head && compared.remote === head) {
1060
+ config.lastPushedOid = head;
1061
+ config.lastSyncAt = (/* @__PURE__ */ new Date()).toISOString();
1062
+ config.ahead = 0;
1063
+ config.behind = 0;
1064
+ memoryError = null;
1065
+ await saveConfig(config);
1066
+ return;
1067
+ }
1068
+ try {
1069
+ await pushBranch(mirror);
1070
+ } catch (err) {
1071
+ memoryError = asFailure(err);
1072
+ await saveConfig(config);
1073
+ logSyncFailure(memoryError);
1074
+ return;
1075
+ }
1076
+ const pushed = await headOid(mirror);
1077
+ config.lastPushedOid = pushed;
1078
+ config.lastSyncAt = (/* @__PURE__ */ new Date()).toISOString();
1079
+ config.ahead = 0;
1080
+ config.behind = 0;
1081
+ memoryError = null;
1082
+ await saveConfig(config);
1083
+ }
1084
+ async function compare(dir) {
1085
+ const local = await headOid(dir);
1086
+ const remote = await remoteOid(dir);
1087
+ if (!local || !remote) return { local, remote, base: null, ahead: local && local !== remote ? 1 : 0, behind: 0 };
1088
+ if (local === remote) return { local, remote, base: local, ahead: 0, behind: 0 };
1089
+ const base = await mergeBase(dir, local, remote);
1090
+ if (!base) return { local, remote, base: null, ahead: 1, behind: 1 };
1091
+ if (base === remote) return { local, remote, base, ahead: 1, behind: 0 };
1092
+ if (base === local) return { local, remote, base, ahead: 0, behind: 1 };
1093
+ return { local, remote, base, ahead: 1, behind: 1 };
1094
+ }
1095
+ function commitMessage(changed) {
1096
+ const named = summaries.filter((summary) => summary.trim().length > 0);
1097
+ summaries = [];
1098
+ structuralPending = false;
1099
+ if (named.length === 1) return named[0] ?? "Update diagrams";
1100
+ if (named.length > 1 && named.length <= 4) return named.join("; ");
1101
+ if (named.length > 4) return `Update ${named.length} diagrams`;
1102
+ if (changed.length === 1) return `Update ${changed[0]}`;
1103
+ if (changed.length > 1 && changed.length <= 3) return `Update ${changed.join(", ")}`;
1104
+ if (changed.length > 3) {
1105
+ return `Update ${changed.slice(0, 3).join(", ")} and ${changed.length - 3} more`;
1106
+ }
1107
+ return "Update diagrams";
1108
+ }
1109
+ async function publicStatus() {
1110
+ const config = await loadConfig();
1111
+ const client = clientIdOf(config);
1112
+ const auth = await readToken();
1113
+ const conflicts = await loadConflicts();
1114
+ const pending = await hasPending(config);
1115
+ const deviceView = device && device.phase === "pending" ? {
1116
+ userCode: device.userCode,
1117
+ verificationUri: device.verificationUri,
1118
+ expiresAt: new Date(device.expiresAt).toISOString()
1119
+ } : null;
1120
+ const blocked = memoryError || device?.phase === "error" && device.error ? null : await authorizationBlock();
1121
+ const error = device?.phase === "error" && device.error ? {
1122
+ code: device.error.code,
1123
+ message: device.error.message,
1124
+ docsUrl: device.error.code === "invalid_client" || device.error.code === "device_flow_disabled" ? SYNC_DOCS_URL : void 0
1125
+ } : memoryError ? { code: memoryError.code, message: memoryError.message, docsUrl: memoryError.docsUrl } : blocked ? { code: blocked.code, message: blocked.message, docsUrl: SYNC_DOCS_URL } : null;
1126
+ return {
1127
+ enabled: config.enabled,
1128
+ login: config.login,
1129
+ clientId: client.id,
1130
+ clientIdSource: client.source,
1131
+ tokenSource: auth.source,
1132
+ repo: config.owner && config.repo ? {
1133
+ owner: config.owner,
1134
+ name: config.repo,
1135
+ private: config.private,
1136
+ htmlUrl: config.htmlUrl || `https://github.com/${config.owner}/${config.repo}`
1137
+ } : null,
1138
+ lastSyncAt: config.lastSyncAt,
1139
+ pending,
1140
+ ahead: config.ahead,
1141
+ behind: config.behind,
1142
+ idleMs: idleMs(),
1143
+ syncing: active > 0,
1144
+ error,
1145
+ conflicts: (conflicts?.conflicts ?? []).map((conflict) => ({
1146
+ path: conflict.path,
1147
+ reason: conflict.reason,
1148
+ locked: conflict.locked,
1149
+ localPreview: preview(conflict.localContent),
1150
+ remotePreview: preview(conflict.remoteContent)
1151
+ })),
1152
+ device: deviceView,
1153
+ docsUrl: SYNC_DOCS_URL,
1154
+ mirror: process.env.NERDGRAM_SYNC_MIRROR?.trim() ? "custom" : ".nerdgram-git"
1155
+ };
1156
+ }
1157
+ async function hasPending(config) {
1158
+ if (timer) return true;
1159
+ if (!config.enabled) return false;
1160
+ try {
1161
+ const head = await headOid(mirrorPath());
1162
+ if (head && config.lastPushedOid && head !== config.lastPushedOid) return true;
1163
+ const changed = await copyWouldChange();
1164
+ return changed;
1165
+ } catch {
1166
+ return false;
1167
+ }
1168
+ }
1169
+ async function copyWouldChange() {
1170
+ const mirror = mirrorPath();
1171
+ try {
1172
+ await fsp2.access(mirror);
1173
+ } catch {
1174
+ return false;
1175
+ }
1176
+ const desired = await listUserFiles(ensureDataRoot());
1177
+ const committed = await readUserFilesAt(mirror, "HEAD");
1178
+ return !mapsEqual(desired, committed);
1179
+ }
1180
+ function mapsEqual(left, right) {
1181
+ if (left.size !== right.size) return false;
1182
+ for (const [key, value] of left) {
1183
+ if (right.get(key) !== value) return false;
1184
+ }
1185
+ return true;
1186
+ }
1187
+ async function probeIfHttp(config) {
1188
+ const remote = config.remoteUrl;
1189
+ if (!remote || !remote.startsWith("https://") && !remote.startsWith("http://")) return;
1190
+ if (!config.owner || !config.repo) return;
1191
+ const auth = await readToken();
1192
+ if (!auth.token) {
1193
+ throw httpFail(401, "GitHub rejected the saved authorization. It may have been revoked. Connect again.", "auth_revoked");
1194
+ }
1195
+ const repo = await getRepo(auth.token, config.owner, config.repo);
1196
+ if (!repo) throw httpFail(404, "That GitHub repository was not found.", "repo_missing");
1197
+ }
1198
+ function logSyncFailure(failure) {
1199
+ const message = redactText(failure.message).replace(/\s+/g, " ").trim();
1200
+ console.error(`GitHub sync: ${failure.code} ${message}`);
1201
+ }
1202
+ function asFailure(err) {
1203
+ if (err && typeof err === "object" && "status" in err && "code" in err && err instanceof Error) {
1204
+ const code = String(err.code);
1205
+ const docs = code === "invalid_client" || code === "device_flow_disabled" || code === "repo_not_empty" || code === "auth_expired" ? SYNC_DOCS_URL : void 0;
1206
+ return {
1207
+ code,
1208
+ message: err.message,
1209
+ status: err.status,
1210
+ docsUrl: docs
1211
+ };
1212
+ }
1213
+ const wrapped = classifyNetworkError(err);
1214
+ if (wrapped instanceof Error && "code" in wrapped) {
1215
+ return asFailure(wrapped);
1216
+ }
1217
+ return { code: "github", message: "GitHub sync failed.", status: 502 };
1218
+ }
1219
+ function preview(content) {
1220
+ if (content == null) return null;
1221
+ return content.length > 1500 ? `${content.slice(0, 1500)}
1222
+ \u2026` : content;
1223
+ }
1224
+ async function loadConflicts() {
1225
+ try {
1226
+ const parsed = JSON.parse(await fsp2.readFile(conflictsPath(), "utf8"));
1227
+ if (!parsed || !Array.isArray(parsed.conflicts)) return null;
1228
+ return parsed;
1229
+ } catch (err) {
1230
+ const code = err.code;
1231
+ if (code === "ENOENT") return null;
1232
+ return null;
1233
+ }
1234
+ }
1235
+ function schedule(ms) {
1236
+ if (timer) clearTimeout(timer);
1237
+ timer = setTimeout(() => {
1238
+ timer = null;
1239
+ void syncNow().catch((err) => {
1240
+ memoryError = asFailure(err);
1241
+ logSyncFailure(memoryError);
1242
+ });
1243
+ }, ms);
1244
+ timer.unref?.();
1245
+ }
1246
+ async function exclusive(fn) {
1247
+ const run = chain.then(async () => {
1248
+ active += 1;
1249
+ maxActive = Math.max(maxActive, active);
1250
+ try {
1251
+ if (testHook) await testHook();
1252
+ return await fn();
1253
+ } finally {
1254
+ active -= 1;
1255
+ }
1256
+ });
1257
+ chain = run.then(
1258
+ () => void 0,
1259
+ () => void 0
1260
+ );
1261
+ return run;
1262
+ }
1263
+ export {
1264
+ noteLocalChange
1265
+ };