@bluestep-systems/b6p-core 0.8.1 → 1.0.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.
Files changed (149) hide show
  1. package/README.md +310 -32
  2. package/dist/B6PCore.d.ts +7 -0
  3. package/dist/B6PCore.js +96 -1
  4. package/dist/B6PCore.js.map +1 -1
  5. package/dist/B6PUri.d.ts +6 -8
  6. package/dist/B6PUri.js +6 -8
  7. package/dist/B6PUri.js.map +1 -1
  8. package/dist/Err.d.ts +421 -0
  9. package/dist/Err.js +558 -0
  10. package/dist/Err.js.map +1 -1
  11. package/dist/auth/BearerAuthProvider.d.ts +32 -0
  12. package/dist/auth/BearerAuthProvider.js +49 -0
  13. package/dist/auth/BearerAuthProvider.js.map +1 -1
  14. package/dist/cache/OrgCache.js.map +1 -1
  15. package/dist/cache/ScriptMetaDataStore.js.map +1 -1
  16. package/dist/constants/ApiEndpoints.d.ts +1 -0
  17. package/dist/constants/ApiEndpoints.js +1 -0
  18. package/dist/constants/ApiEndpoints.js.map +1 -1
  19. package/dist/constants/AuthTypes.js.map +1 -1
  20. package/dist/constants/BlueHQ.js.map +1 -1
  21. package/dist/constants/CryptoAlgorithms.js.map +1 -1
  22. package/dist/constants/ExtensionConfig.js.map +1 -1
  23. package/dist/constants/FileExtensions.js.map +1 -1
  24. package/dist/constants/FolderNames.js.map +1 -1
  25. package/dist/constants/Gateway.d.ts +71 -0
  26. package/dist/constants/Gateway.js +79 -0
  27. package/dist/constants/Gateway.js.map +1 -0
  28. package/dist/constants/GitHubUrls.js.map +1 -1
  29. package/dist/constants/Http.js.map +1 -1
  30. package/dist/constants/MimeTypes.js.map +1 -1
  31. package/dist/constants/Numerical.js.map +1 -1
  32. package/dist/constants/OutputChannels.js.map +1 -1
  33. package/dist/constants/SettingsKeys.d.ts +5 -0
  34. package/dist/constants/SettingsKeys.js +5 -0
  35. package/dist/constants/SettingsKeys.js.map +1 -1
  36. package/dist/constants/SpecialFiles.js.map +1 -1
  37. package/dist/constants/WebDAVElements.js.map +1 -1
  38. package/dist/constants/index.d.ts +1 -0
  39. package/dist/constants/index.js +3 -1
  40. package/dist/constants/index.js.map +1 -1
  41. package/dist/data/DownstairsPathParser.js.map +1 -1
  42. package/dist/data/GlobMatcher.js.map +1 -1
  43. package/dist/data/IdUtility.js.map +1 -1
  44. package/dist/data/OrgWorker.js.map +1 -1
  45. package/dist/data/ScriptKey.d.ts +3 -27
  46. package/dist/data/ScriptKey.js +12 -24
  47. package/dist/data/ScriptKey.js.map +1 -1
  48. package/dist/data/ScriptUrlParser.js +3 -1
  49. package/dist/data/ScriptUrlParser.js.map +1 -1
  50. package/dist/data/ServerVersion.d.ts +76 -0
  51. package/dist/data/ServerVersion.js +111 -0
  52. package/dist/data/ServerVersion.js.map +1 -0
  53. package/dist/data/index.d.ts +2 -0
  54. package/dist/data/index.js +7 -1
  55. package/dist/data/index.js.map +1 -1
  56. package/dist/gateway/GatewayClient.d.ts +147 -0
  57. package/dist/gateway/GatewayClient.js +395 -0
  58. package/dist/gateway/GatewayClient.js.map +1 -0
  59. package/dist/gateway/GatewayContext.d.ts +43 -0
  60. package/dist/gateway/GatewayContext.js +3 -0
  61. package/dist/gateway/GatewayContext.js.map +1 -0
  62. package/dist/gateway/GatewayGit.d.ts +291 -0
  63. package/dist/gateway/GatewayGit.js +731 -0
  64. package/dist/gateway/GatewayGit.js.map +1 -0
  65. package/dist/gateway/GatewayKb.d.ts +173 -0
  66. package/dist/gateway/GatewayKb.js +354 -0
  67. package/dist/gateway/GatewayKb.js.map +1 -0
  68. package/dist/gateway/GatewayMarketplace.d.ts +116 -0
  69. package/dist/gateway/GatewayMarketplace.js +278 -0
  70. package/dist/gateway/GatewayMarketplace.js.map +1 -0
  71. package/dist/gateway/GatewayService.d.ts +47 -0
  72. package/dist/gateway/GatewayService.js +54 -0
  73. package/dist/gateway/GatewayService.js.map +1 -0
  74. package/dist/gateway/GatewayToken.d.ts +18 -0
  75. package/dist/gateway/GatewayToken.js +43 -0
  76. package/dist/gateway/GatewayToken.js.map +1 -0
  77. package/dist/gateway/GatewayTokenService.d.ts +101 -0
  78. package/dist/gateway/GatewayTokenService.js +465 -0
  79. package/dist/gateway/GatewayTokenService.js.map +1 -0
  80. package/dist/index.d.ts +29 -8
  81. package/dist/index.js +81 -9
  82. package/dist/index.js.map +1 -1
  83. package/dist/network/HttpClient.js.map +1 -1
  84. package/dist/network/HttpClientProvider.js.map +1 -1
  85. package/dist/network/StatusCodes.js.map +1 -1
  86. package/dist/persistence/PersistablePseudoMap.js.map +1 -1
  87. package/dist/persistence/PersistenceKeys.js.map +1 -1
  88. package/dist/persistence/PrivatePersistanceMap.js.map +1 -1
  89. package/dist/persistence/PseudoMap.js.map +1 -1
  90. package/dist/persistence/PublicPersistanceMap.js.map +1 -1
  91. package/dist/persistence/Serializable.js.map +1 -1
  92. package/dist/persistence/SharedFilePersistence.d.ts +22 -0
  93. package/dist/persistence/SharedFilePersistence.js +65 -14
  94. package/dist/persistence/SharedFilePersistence.js.map +1 -1
  95. package/dist/persistence/TypedMap.js.map +1 -1
  96. package/dist/persistence/TypedPersistable.js.map +1 -1
  97. package/dist/persistence/TypedPrivatePersistable.js.map +1 -1
  98. package/dist/persistence/dirLockdown.js.map +1 -1
  99. package/dist/providers.d.ts +46 -16
  100. package/dist/script/GitIdentity.d.ts +48 -0
  101. package/dist/script/GitIdentity.js +52 -0
  102. package/dist/script/GitIdentity.js.map +1 -0
  103. package/dist/script/GitSync.d.ts +388 -0
  104. package/dist/script/GitSync.js +1068 -0
  105. package/dist/script/GitSync.js.map +1 -0
  106. package/dist/script/ScriptContext.d.ts +20 -5
  107. package/dist/script/ScriptFactory.d.ts +1 -2
  108. package/dist/script/ScriptFactory.js +1 -2
  109. package/dist/script/ScriptFactory.js.map +1 -1
  110. package/dist/script/ScriptFile.d.ts +0 -94
  111. package/dist/script/ScriptFile.js +0 -245
  112. package/dist/script/ScriptFile.js.map +1 -1
  113. package/dist/script/ScriptFolder.d.ts +0 -9
  114. package/dist/script/ScriptFolder.js +4 -7
  115. package/dist/script/ScriptFolder.js.map +1 -1
  116. package/dist/script/ScriptNode.d.ts +0 -9
  117. package/dist/script/ScriptNode.js.map +1 -1
  118. package/dist/script/ScriptRoot.d.ts +0 -65
  119. package/dist/script/ScriptRoot.js +0 -199
  120. package/dist/script/ScriptRoot.js.map +1 -1
  121. package/dist/script/ScriptService.d.ts +113 -9
  122. package/dist/script/ScriptService.js +164 -52
  123. package/dist/script/ScriptService.js.map +1 -1
  124. package/dist/script/ServerCompile.d.ts +35 -0
  125. package/dist/script/ServerCompile.js +40 -0
  126. package/dist/script/ServerCompile.js.map +1 -0
  127. package/dist/script/TsConfig.d.ts +2 -2
  128. package/dist/script/TsConfig.js +3 -3
  129. package/dist/script/TsConfig.js.map +1 -1
  130. package/dist/script/push.d.ts +162 -188
  131. package/dist/script/push.js +216 -474
  132. package/dist/script/push.js.map +1 -1
  133. package/dist/session/SessionManager.js.map +1 -1
  134. package/dist/testing/FakeGateway.d.ts +280 -0
  135. package/dist/testing/FakeGateway.js +627 -0
  136. package/dist/testing/FakeGateway.js.map +1 -0
  137. package/dist/testing/MockFileSystem.js.map +1 -1
  138. package/dist/types.d.ts +332 -0
  139. package/dist/update/UpdateService.js.map +1 -1
  140. package/package.json +17 -12
  141. package/dist/script/ScriptTranspiler.d.ts +0 -121
  142. package/dist/script/ScriptTranspiler.js +0 -333
  143. package/dist/script/ScriptTranspiler.js.map +0 -1
  144. package/dist/script/SnapshotHistoryRecorder.d.ts +0 -47
  145. package/dist/script/SnapshotHistoryRecorder.js +0 -231
  146. package/dist/script/SnapshotHistoryRecorder.js.map +0 -1
  147. package/dist/script/TsLibResolver.d.ts +0 -60
  148. package/dist/script/TsLibResolver.js +0 -134
  149. package/dist/script/TsLibResolver.js.map +0 -1
@@ -0,0 +1,1068 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.GitSymlinkError = exports.GitStagedChangesError = exports.GitWrongBranchError = exports.GitSwitchDeclinedError = void 0;
37
+ exports.openRepo = openRepo;
38
+ exports.isGitWorkingTree = isGitWorkingTree;
39
+ exports.legacyIgnoreRulesForDraft = legacyIgnoreRulesForDraft;
40
+ exports.pullDraft = pullDraft;
41
+ exports.auditDraft = auditDraft;
42
+ exports.confirmOverwrittenFiles = confirmOverwrittenFiles;
43
+ exports.pushDraft = pushDraft;
44
+ exports.draftFolderOf = draftFolderOf;
45
+ const path = __importStar(require("path"));
46
+ const node_crypto_1 = require("node:crypto");
47
+ const os = __importStar(require("node:os"));
48
+ const b6p_core_bsjs_git_1 = require("@bluestep-systems/b6p-core-bsjs-git");
49
+ const constants_1 = require("../constants");
50
+ const Err_1 = require("../Err");
51
+ /**
52
+ * The `origin` branch of the platform's draft, as `ScriptRepo` resolves it.
53
+ * @lastreviewed null
54
+ */
55
+ const REMOTE_DRAFT = `refs/remotes/origin/${b6p_core_bsjs_git_1.DRAFT_BRANCH}`;
56
+ const REMOTE_MASTER = "refs/remotes/origin/master";
57
+ const GIT_DIR = ".git";
58
+ const EXCLUDE_BEGIN = "# >>> b6p: rules this tool maintains (the script's own .gitignore is not touched)";
59
+ const EXCLUDE_END = "# <<< b6p";
60
+ /**
61
+ * Files git must never pick up from a script's working tree: macOS folder metadata and this package's own atomic-write
62
+ * temp files.
63
+ * @lastreviewed null
64
+ */
65
+ const LOCAL_EXCLUDES = [".DS_Store", "*.b6p-tmp"];
66
+ /**
67
+ * Tells a consumer that the one-way switch to git had already happened when this error was thrown, by setting
68
+ * `switchedToGit` on it (a field of `OverwriteDeclinedError`, an added property on any other error). The error is
69
+ * returned for rethrowing.
70
+ * @lastreviewed null
71
+ */
72
+ function markSwitched(error, tracker) {
73
+ if (tracker.switched && typeof error === "object" && error !== null) {
74
+ Object.defineProperty(error, "switchedToGit", {
75
+ value: true,
76
+ writable: true,
77
+ configurable: true,
78
+ enumerable: true,
79
+ });
80
+ }
81
+ return error;
82
+ }
83
+ /**
84
+ * Thrown when the script still publishes over WebDAV and switching it to git (which cannot be undone) was not confirmed.
85
+ * Nothing was switched and nothing local was changed.
86
+ * @lastreviewed null
87
+ */
88
+ class GitSwitchDeclinedError extends Error {
89
+ constructor() {
90
+ super("The script still publishes over WebDAV and switching it to git was not confirmed");
91
+ this.name = "GitSwitchDeclinedError";
92
+ }
93
+ }
94
+ exports.GitSwitchDeclinedError = GitSwitchDeclinedError;
95
+ /**
96
+ * Thrown by a push when the draft folder's repo has another branch checked out: a commit would advance that branch while
97
+ * the push sends the draft branch, so nothing is committed.
98
+ * @lastreviewed null
99
+ */
100
+ class GitWrongBranchError extends Error {
101
+ branch;
102
+ constructor(branch) {
103
+ super(`The draft folder has ${branch === undefined ? "a detached HEAD" : `the branch "${branch}"`} checked out, ` +
104
+ `not "${b6p_core_bsjs_git_1.DRAFT_BRANCH}": nothing was committed or pushed, because the platform's script is its "${b6p_core_bsjs_git_1.DRAFT_BRANCH}" branch`);
105
+ this.branch = branch;
106
+ this.name = "GitWrongBranchError";
107
+ }
108
+ }
109
+ exports.GitWrongBranchError = GitWrongBranchError;
110
+ /**
111
+ * Thrown by a pull when files hold changes that exist only in the git index (staged, then edited again): updating the
112
+ * working tree would discard them. Nothing was changed.
113
+ * @lastreviewed null
114
+ */
115
+ class GitStagedChangesError extends Error {
116
+ paths;
117
+ constructor(paths) {
118
+ super(`${paths.length} file(s) have staged changes that differ from the file on disk, and a pull would discard them ` +
119
+ `(nothing was changed):\n\n${paths.join("\n")}`);
120
+ this.paths = paths;
121
+ this.name = "GitStagedChangesError";
122
+ }
123
+ }
124
+ exports.GitStagedChangesError = GitStagedChangesError;
125
+ /**
126
+ * Thrown by a pull when an incoming file would be written through a symbolic link out of the draft folder. Nothing was
127
+ * changed.
128
+ * @lastreviewed null
129
+ */
130
+ class GitSymlinkError extends Error {
131
+ paths;
132
+ constructor(paths) {
133
+ super(` incoming file(s) would be written through a symbolic link out of the draft folder (nothing was ` +
134
+ `changed):\n\n${paths.join("\n")}`);
135
+ this.paths = paths;
136
+ this.name = "GitSymlinkError";
137
+ }
138
+ }
139
+ exports.GitSymlinkError = GitSymlinkError;
140
+ function isMissing(error) {
141
+ const code = error.code;
142
+ return code === "ENOENT" || code === "ENOTDIR";
143
+ }
144
+ /**
145
+ * File operations on a script's git working tree, over the context's {@link ScriptContext.gitFs}.
146
+ *
147
+ * A symbolic link is never followed out of a root: reads of one answer "absent", writes through one are refused, and
148
+ * the paths are collected so the caller can warn once ({@link reportSkipped}).
149
+ * @lastreviewed null
150
+ */
151
+ class WorkTreeFiles {
152
+ #fs;
153
+ #ctx;
154
+ #skipped = new Set();
155
+ constructor(ctx) {
156
+ if (!("promises" in ctx.gitFs)) {
157
+ throw new Err_1.Err.InvalidStateError("The git file system has no `promises` interface");
158
+ }
159
+ this.#ctx = ctx;
160
+ this.#fs = ctx.gitFs.promises;
161
+ }
162
+ /**
163
+
164
+ * Warns once about the symbolic links and out-of-root paths that were left alone, then forgets them.
165
+
166
+ * @lastreviewed null
167
+
168
+ */
169
+ reportSkipped() {
170
+ if (this.#skipped.size > 0) {
171
+ this.#ctx.prompt.warn(`Skipped ${this.#skipped.size} path(s) that are, or sit behind, a symbolic link: a script's files are never ` +
172
+ `read or written through a link out of its draft folder:\n\n${[...this.#skipped].join("\n")}`);
173
+ this.#skipped.clear();
174
+ }
175
+ }
176
+ async exists(p) {
177
+ try {
178
+ await this.#fs.stat(p);
179
+ return true;
180
+ }
181
+ catch {
182
+ return false;
183
+ }
184
+ }
185
+ /**
186
+ * Whether `p` is under `root` with no symbolic link between them (nor `p` itself being one). A missing component
187
+ * ends the walk: nothing there can be a link yet.
188
+ * @lastreviewed null
189
+ */
190
+ async #contained(root, p) {
191
+ const relative = path.relative(root, p);
192
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) {
193
+ return relative === "";
194
+ }
195
+ let current = root;
196
+ for (const part of relative.split(path.sep)) {
197
+ current = path.join(current, part);
198
+ try {
199
+ if ((await this.#fs.lstat(current)).isSymbolicLink()) {
200
+ this.#skipped.add(p);
201
+ return false;
202
+ }
203
+ }
204
+ catch (error) {
205
+ if (isMissing(error)) {
206
+ return true;
207
+ }
208
+ throw error;
209
+ }
210
+ }
211
+ return true;
212
+ }
213
+ /**
214
+
215
+ * Whether `p` is, or sits behind, a symbolic link (or is outside `root`).
216
+
217
+ * @lastreviewed null
218
+
219
+ */
220
+ async escapes(root, p) {
221
+ return !(await this.#contained(root, p));
222
+ }
223
+ async readOptional(root, p) {
224
+ if (!(await this.#contained(root, p))) {
225
+ return undefined;
226
+ }
227
+ try {
228
+ return await this.#fs.readFile(p);
229
+ }
230
+ catch (error) {
231
+ if (isMissing(error) || error.code === "EISDIR") {
232
+ return undefined;
233
+ }
234
+ throw error;
235
+ }
236
+ }
237
+ /**
238
+
239
+ * @returns false when the write was refused because the path is, or sits behind, a symbolic link.
240
+
241
+ * @lastreviewed null
242
+
243
+ */
244
+ async write(root, p, data) {
245
+ if (!(await this.#contained(root, p))) {
246
+ this.#skipped.add(p);
247
+ return false;
248
+ }
249
+ await this.#fs.mkdir(path.dirname(p), { recursive: true });
250
+ await this.#fs.writeFile(p, data);
251
+ return true;
252
+ }
253
+ async mkdirp(p) {
254
+ await this.#fs.mkdir(p, { recursive: true });
255
+ }
256
+ async mkdtemp(prefix) {
257
+ return this.#fs.mkdtemp(prefix);
258
+ }
259
+ async remove(p) {
260
+ await this.#fs.rm(p, { recursive: true, force: true });
261
+ }
262
+ async rename(from, to) {
263
+ await this.#fs.rename(from, to);
264
+ }
265
+ /**
266
+ * Whether the folder exists and holds anything at all.
267
+ * @lastreviewed null
268
+ */
269
+ async hasEntries(dir) {
270
+ try {
271
+ return (await this.#fs.readdir(dir)).length > 0;
272
+ }
273
+ catch {
274
+ return false;
275
+ }
276
+ }
277
+ /**
278
+ * Every regular file under `root` as a `/`-separated path relative to it, skipping the repo's own `.git` and every
279
+ * symbolic link.
280
+ * @lastreviewed null
281
+ */
282
+ async listFiles(root) {
283
+ const found = [];
284
+ const walk = async (relativeDir) => {
285
+ const names = await this.#fs.readdir(relativeDir === "" ? root : path.join(root, ...relativeDir.split("/")));
286
+ for (const name of names) {
287
+ if (name === GIT_DIR) {
288
+ continue;
289
+ }
290
+ const relative = relativeDir === "" ? name : `${relativeDir}/${name}`;
291
+ const place = path.join(root, ...relative.split("/"));
292
+ const stat = await this.#fs.lstat(place);
293
+ if (stat.isSymbolicLink()) {
294
+ this.#skipped.add(place);
295
+ }
296
+ else if (stat.isDirectory()) {
297
+ await walk(relative);
298
+ }
299
+ else {
300
+ found.push(relative);
301
+ }
302
+ }
303
+ };
304
+ await walk("");
305
+ return found.sort();
306
+ }
307
+ /**
308
+ * Deletes everything directly under `root` except the repo's `.git`.
309
+ * @lastreviewed null
310
+ */
311
+ async clearExceptGit(root) {
312
+ for (const name of await this.#fs.readdir(root)) {
313
+ if (name !== GIT_DIR) {
314
+ await this.remove(path.join(root, name));
315
+ }
316
+ }
317
+ }
318
+ }
319
+ function absolute(root, relative) {
320
+ return path.join(root, ...relative.split("/"));
321
+ }
322
+ function sameBytes(a, b) {
323
+ return Buffer.compare(a, b) === 0;
324
+ }
325
+ function sha512Hex(bytes) {
326
+ return (0, node_crypto_1.createHash)("sha512").update(bytes).digest("hex");
327
+ }
328
+ function normalizeRepoUrl(url) {
329
+ return url
330
+ .trim()
331
+ .replace(/\/+$/, "")
332
+ .replace(/\.git$/, "")
333
+ .toLowerCase();
334
+ }
335
+ /**
336
+ * Opens the script's repo on `dir` (the draft folder, or a scratch folder).
337
+ * @lastreviewed null
338
+ */
339
+ async function openRepo(target, dir, author) {
340
+ return new b6p_core_bsjs_git_1.ScriptRepo({
341
+ fs: target.ctx.gitFs,
342
+ dir,
343
+ script: target.script,
344
+ baseUrl: target.baseUrl,
345
+ auth: { kind: "token", token: await target.ctx.gitToken() },
346
+ ...(author ? { author } : {}),
347
+ ...(target.ctx.gitFetch ? { fetch: target.ctx.gitFetch } : {}),
348
+ });
349
+ }
350
+ /**
351
+ * Whether the draft folder is already a git working tree.
352
+ * @lastreviewed null
353
+ */
354
+ async function isGitWorkingTree(ctx, draftPath) {
355
+ return new WorkTreeFiles(ctx).exists(path.join(draftPath, GIT_DIR));
356
+ }
357
+ async function readOriginUrl(files, draftPath) {
358
+ const raw = await files.readOptional(draftPath, path.join(draftPath, GIT_DIR, "config"));
359
+ if (!raw) {
360
+ return undefined;
361
+ }
362
+ const match = /\[remote "origin"\][^[]*?\burl\s*=\s*(\S+)/.exec(Buffer.from(raw).toString("utf8"));
363
+ return match?.[1];
364
+ }
365
+ /**
366
+ * The rules of a script root's old `.gitignore` (which governed what a WebDAV push uploaded) as git rules for the repo
367
+ * rooted at `draft/`. That file's patterns matched paths relative to the script root, so only the ones that reached
368
+ * into `draft/` applied to the draft's files: `draft/<rest>` becomes `/<rest>` (anchored at the draft root) and
369
+ * `**` + `/<rest>` stays as it is. Everything else never matched a draft file and is dropped.
370
+ * @lastreviewed null
371
+ */
372
+ function legacyIgnoreRulesForDraft(rootGitignore) {
373
+ const rules = [];
374
+ for (const raw of rootGitignore.split(/\r?\n/)) {
375
+ const line = raw.trim();
376
+ if (line === "" || line.startsWith("#")) {
377
+ continue;
378
+ }
379
+ const negated = line.startsWith("!");
380
+ const pattern = (negated ? line.slice(1) : line).replace(/^\//, "");
381
+ const prefix = negated ? "!" : "";
382
+ if (pattern.startsWith(`${constants_1.FolderNames.DRAFT}/`)) {
383
+ rules.push(`${prefix}/${pattern.slice(constants_1.FolderNames.DRAFT.length + 1)}`);
384
+ }
385
+ else if (pattern.startsWith("**/")) {
386
+ rules.push(`${prefix}${pattern}`);
387
+ }
388
+ }
389
+ return rules;
390
+ }
391
+ /**
392
+ * Writes the repo's `info/exclude` (never committed): the temp and metadata files git must not pick up, and the old
393
+ * script-root `.gitignore` rules ({@link legacyIgnoreRulesForDraft}), so a file the old tool never uploaded is never
394
+ * committed now. The block is rewritten on every call, so an edited root `.gitignore` takes effect; other lines of the
395
+ * file are left alone.
396
+ * @param scriptRoot The script root whose `.gitignore` the rules come from
397
+ * @lastreviewed null
398
+ */
399
+ async function ensureLocalExcludes(files, repoDir, scriptRoot) {
400
+ const exclude = path.join(repoDir, GIT_DIR, "info", "exclude");
401
+ const existing = await files.readOptional(repoDir, exclude);
402
+ const text = existing ? Buffer.from(existing).toString("utf8") : "";
403
+ const begin = text.indexOf(EXCLUDE_BEGIN);
404
+ const end = text.indexOf(EXCLUDE_END);
405
+ const kept = begin >= 0 && end > begin ? text.slice(0, begin) + text.slice(end + EXCLUDE_END.length) : text;
406
+ const rootRules = await files.readOptional(scriptRoot, path.join(scriptRoot, constants_1.SpecialFiles.GITIGNORE));
407
+ const rules = [
408
+ ...LOCAL_EXCLUDES,
409
+ ...(rootRules ? legacyIgnoreRulesForDraft(Buffer.from(rootRules).toString("utf8")) : []),
410
+ ];
411
+ const block = [EXCLUDE_BEGIN, ...rules, EXCLUDE_END].join("\n");
412
+ const base = kept.trimEnd();
413
+ await files.write(repoDir, exclude, Buffer.from(`${base}${base ? "\n" : ""}${block}\n`));
414
+ }
415
+ async function remoteDraftOf(repo) {
416
+ try {
417
+ return await repo.sha(REMOTE_DRAFT);
418
+ }
419
+ catch (error) {
420
+ if (error instanceof b6p_core_bsjs_git_1.BsjsGitError && error.code === "REPO_NOT_FOUND") {
421
+ return undefined;
422
+ }
423
+ throw error;
424
+ }
425
+ }
426
+ /**
427
+ * The consent to switch a WebDAV script to git, which cannot be undone, asked before anything is switched or changed
428
+ * locally. The safe answer is first, so an empty answer and auto-confirm decline.
429
+ * @param enableGit The caller already confirmed, so do not ask.
430
+ * @throws {GitSwitchDeclinedError} when it is not given.
431
+ * @lastreviewed null
432
+ */
433
+ async function requireSwitchConsent(ctx, enableGit) {
434
+ if (enableGit) {
435
+ return;
436
+ }
437
+ const CANCEL = "Cancel";
438
+ const SWITCH = "Switch to git";
439
+ const answer = await ctx.prompt.confirm("This script has no git repository: it still publishes over WebDAV. Working with it through git switches it to " +
440
+ "git publishing, which cannot be undone, and its draft and snapshot then no longer accept WebDAV writes. " +
441
+ "Switch it to git?", [CANCEL, SWITCH], { destructive: true, safeOption: CANCEL });
442
+ if (answer !== SWITCH) {
443
+ throw new GitSwitchDeclinedError();
444
+ }
445
+ }
446
+ /**
447
+ * Clones the script into an empty scratch folder next to the draft (`<root>/.b6p-adopt`). Nothing of the draft folder
448
+ * is touched until {@link installGit} moves the clone's `.git` in.
449
+ * @lastreviewed null
450
+ */
451
+ async function cloneToScratch(target, files, author) {
452
+ const scratch = path.join(path.dirname(target.draftPath), ".b6p-adopt");
453
+ await files.remove(scratch);
454
+ await files.mkdirp(scratch);
455
+ try {
456
+ const repo = await openRepo(target, scratch, author);
457
+ await repo.clone();
458
+ return { repo, scratch };
459
+ }
460
+ catch (error) {
461
+ await files.remove(scratch);
462
+ throw error;
463
+ }
464
+ }
465
+ /**
466
+ * Makes the scratch clone's `.git` the draft folder's, so the folder's files become the working tree of the script's
467
+ * repo as they stand: what differs from the platform then shows as local changes. Replaces a `.git` that is there.
468
+ * @lastreviewed null
469
+ */
470
+ async function installGit(files, scratch, draftPath) {
471
+ await files.mkdirp(draftPath);
472
+ await files.remove(path.join(draftPath, GIT_DIR));
473
+ await files.rename(path.join(scratch, GIT_DIR), path.join(draftPath, GIT_DIR));
474
+ }
475
+ /**
476
+ * Brings the platform's draft into the local draft folder:
477
+ * - no repo: the script's mode is read first. A WebDAV script needs the one-way switch, confirmed before anything is
478
+ * switched or touched. An empty folder then gets a clone; a folder with files is bound to the repo as it stands (a
479
+ * file the platform has that differs from the local one is kept when its last sync record says it was edited here,
480
+ * and replaced otherwise);
481
+ * - a repo: fetches and fast-forwards. A local edit to a file the platform also changed, and a local ignored or
482
+ * untracked file at a path the platform now tracks, are kept and reported. Files the platform has that are missing
483
+ * locally are restored.
484
+ *
485
+ * Nothing is ever written through a symbolic link.
486
+ *
487
+ * @throws {GitSwitchDeclinedError} when a WebDAV script needs the switch and it was declined.
488
+ * @throws {GitNotFastForwardError} when the local draft has commits of its own and the platform moved too.
489
+ * @throws {GitStagedChangesError} when index-only changes would be discarded.
490
+ * @lastreviewed null
491
+ */
492
+ async function pullDraft(target, options = {}) {
493
+ const files = new WorkTreeFiles(target.ctx);
494
+ const tracker = { switched: false };
495
+ try {
496
+ return await pullDraftInner(target, options, files, tracker);
497
+ }
498
+ catch (error) {
499
+ throw markSwitched(error, tracker);
500
+ }
501
+ finally {
502
+ files.reportSkipped();
503
+ }
504
+ }
505
+ async function pullDraftInner(target, options, files, tracker) {
506
+ const { ctx, draftPath } = target;
507
+ const scriptRoot = path.dirname(draftPath);
508
+ const overwrite = new Set(options.overwrite ?? []);
509
+ const keptLocalPaths = [];
510
+ let switchedToGit = false;
511
+ const repo = await openRepo(target, draftPath);
512
+ if (!(await files.exists(path.join(draftPath, GIT_DIR)))) {
513
+ if (!(await repo.gitMode()).gitPublishing) {
514
+ await requireSwitchConsent(ctx, options.enableGit);
515
+ switchedToGit = (await repo.ensureGitModeResult()).switched;
516
+ tracker.switched = switchedToGit;
517
+ }
518
+ if (!(await files.hasEntries(draftPath))) {
519
+ await files.mkdirp(draftPath);
520
+ try {
521
+ await repo.clone();
522
+ }
523
+ catch (error) {
524
+ await files.remove(path.join(draftPath, GIT_DIR));
525
+ throw error;
526
+ }
527
+ await ensureLocalExcludes(files, draftPath, scriptRoot);
528
+ return { keptLocalPaths, switchedToGit };
529
+ }
530
+ const { scratch } = await cloneToScratch(target, files);
531
+ try {
532
+ await installGit(files, scratch, draftPath);
533
+ }
534
+ finally {
535
+ await files.remove(scratch);
536
+ }
537
+ await ensureLocalExcludes(files, draftPath, scriptRoot);
538
+ for (const { path: relative } of await repo.listTree(b6p_core_bsjs_git_1.DRAFT_BRANCH)) {
539
+ const remote = await repo.readFile(b6p_core_bsjs_git_1.DRAFT_BRANCH, relative);
540
+ const place = absolute(draftPath, relative);
541
+ const local = await files.readOptional(draftPath, place);
542
+ if (local && sameBytes(local, remote)) {
543
+ continue;
544
+ }
545
+ if (local && !overwrite.has(relative)) {
546
+ const recorded = options.lastSynced ? await options.lastSynced(relative) : null;
547
+ if (recorded !== null && recorded !== sha512Hex(local)) {
548
+ keptLocalPaths.push(place);
549
+ continue;
550
+ }
551
+ }
552
+ await files.write(draftPath, place, remote);
553
+ }
554
+ return { keptLocalPaths, switchedToGit };
555
+ }
556
+ await ensureLocalExcludes(files, draftPath, scriptRoot);
557
+ await repo.fetch();
558
+ const remote = await remoteDraftOf(repo);
559
+ const local = await repo.sha(b6p_core_bsjs_git_1.DRAFT_BRANCH);
560
+ if (remote && remote !== local) {
561
+ if (await repo.isAncestor(local, remote)) {
562
+ const incoming = await repo.diff(local, remote);
563
+ const changed = new Set(incoming.filter((c) => c.newOid !== undefined).map((c) => c.path));
564
+ const added = incoming.filter((c) => c.status === "added").map((c) => c.path);
565
+ const escaping = [];
566
+ for (const relative of changed) {
567
+ if (await files.escapes(draftPath, absolute(draftPath, relative))) {
568
+ escaping.push(relative);
569
+ }
570
+ }
571
+ if (escaping.length > 0) {
572
+ throw new GitSymlinkError(escaping);
573
+ }
574
+ const staged = await repo.stagedOnlyChanges();
575
+ if (staged.length > 0) {
576
+ throw new GitStagedChangesError(staged);
577
+ }
578
+ const dirty = new Set((await repo.status()).filter((s) => s.status !== "deleted").map((s) => s.path));
579
+ // Everything the checkout would clobber and that is ours: edited or untracked files, and files at paths the
580
+ // platform has just started tracking (an ignored local file is invisible to the status).
581
+ const saved = new Map();
582
+ for (const relative of new Set([...dirty, ...added])) {
583
+ const bytes = await files.readOptional(draftPath, absolute(draftPath, relative));
584
+ if (bytes) {
585
+ saved.set(relative, bytes);
586
+ }
587
+ }
588
+ await repo.resetDraft(remote);
589
+ for (const [relative, bytes] of saved) {
590
+ if (overwrite.has(relative)) {
591
+ continue;
592
+ }
593
+ const place = absolute(draftPath, relative);
594
+ const platform = await files.readOptional(draftPath, place);
595
+ if (await files.write(draftPath, place, bytes)) {
596
+ if (changed.has(relative) && !(platform && sameBytes(platform, bytes))) {
597
+ keptLocalPaths.push(place);
598
+ }
599
+ }
600
+ }
601
+ }
602
+ else if (!(await repo.isAncestor(remote, local))) {
603
+ throw new b6p_core_bsjs_git_1.GitNotFastForwardError(b6p_core_bsjs_git_1.DRAFT_BRANCH);
604
+ }
605
+ }
606
+ // A platform copy the caller confirmed replaces a local one, and it is the fetched platform draft that is read: the
607
+ // local branch may be ahead of it.
608
+ const platformRev = remote ?? b6p_core_bsjs_git_1.DRAFT_BRANCH;
609
+ for (const relative of overwrite) {
610
+ let bytes;
611
+ try {
612
+ bytes = await repo.readFile(platformRev, relative);
613
+ }
614
+ catch (error) {
615
+ if (error instanceof b6p_core_bsjs_git_1.BsjsGitError || error.code === "NotFoundError") {
616
+ continue;
617
+ }
618
+ throw error;
619
+ }
620
+ await files.write(draftPath, absolute(draftPath, relative), bytes);
621
+ }
622
+ // Files the local draft has that this folder lacks come back.
623
+ for (const { path: relative } of await repo.listTree(b6p_core_bsjs_git_1.DRAFT_BRANCH)) {
624
+ const place = absolute(draftPath, relative);
625
+ if (!(await files.exists(place))) {
626
+ await files.write(draftPath, place, await repo.readFile(b6p_core_bsjs_git_1.DRAFT_BRANCH, relative));
627
+ }
628
+ }
629
+ return { keptLocalPaths, switchedToGit };
630
+ }
631
+ /**
632
+ * Compares the local draft folder with the platform's draft. Fetches first; reads nothing else from the platform.
633
+ * @returns the differences, or `undefined` when the folder is not a git working tree yet (there is nothing to compare
634
+ * against without pulling it).
635
+ * @lastreviewed null
636
+ */
637
+ async function auditDraft(target) {
638
+ const { ctx, draftPath } = target;
639
+ const files = new WorkTreeFiles(ctx);
640
+ if (!(await files.exists(path.join(draftPath, GIT_DIR)))) {
641
+ return undefined;
642
+ }
643
+ try {
644
+ const repo = await openRepo(target, draftPath);
645
+ await repo.fetch();
646
+ const remote = await remoteDraftOf(repo);
647
+ const audit = { missingLocally: [], changed: [] };
648
+ if (!remote) {
649
+ return audit;
650
+ }
651
+ for (const { path: relative } of await repo.listTree(remote)) {
652
+ const local = await files.readOptional(draftPath, absolute(draftPath, relative));
653
+ if (!local) {
654
+ audit.missingLocally.push(relative);
655
+ }
656
+ else if (!sameBytes(local, await repo.readFile(remote, relative))) {
657
+ audit.changed.push(relative);
658
+ }
659
+ }
660
+ return audit;
661
+ }
662
+ finally {
663
+ files.reportSkipped();
664
+ }
665
+ }
666
+ /**
667
+ * The draft files whose push would overwrite or drop a platform version nobody here has seen: files the platform has
668
+ * that differ from the local one, narrowed to the ones the platform changed (`moved`), and the platform's files with
669
+ * no local copy at all.
670
+ * @lastreviewed null
671
+ */
672
+ async function findOverwriteRisks(opts) {
673
+ const risks = { changed: [], platformOnly: [] };
674
+ for (const relative of opts.paths) {
675
+ const platform = await opts.repo.readFile(opts.remote, relative);
676
+ const local = await opts.files.readOptional(opts.workRoot, absolute(opts.workRoot, relative));
677
+ if (local && sameBytes(local, platform)) {
678
+ continue;
679
+ }
680
+ if (!(await opts.moved(relative, platform))) {
681
+ continue;
682
+ }
683
+ (local ? risks.changed : risks.platformOnly).push(relative);
684
+ }
685
+ return risks;
686
+ }
687
+ /**
688
+ * The push's one overwrite confirmation, asked before anything leaves this machine. The safe answer is first so an
689
+ * empty answer and auto-confirm both decline.
690
+ * @param opts.paths Files that differ from a platform version nobody here has seen
691
+ * @param opts.deleted Files the platform deleted since the last sync that this push would bring back
692
+ * @throws an {@link Err.OverwriteDeclinedError} naming the files when the answer is not "Overwrite all".
693
+ * @lastreviewed null
694
+ */
695
+ async function confirmOverwrittenFiles(opts) {
696
+ const preConfirmed = new Set((opts.preConfirmed ?? []).map((p) => p.replace(/\\/g, "/").replace(/^\.\//, "")));
697
+ const changed = opts.paths.filter((p) => !preConfirmed.has(p));
698
+ const deleted = (opts.deleted ?? []).filter((p) => !preConfirmed.has(p));
699
+ const toAsk = [...changed, ...deleted];
700
+ if (toAsk.length === 0) {
701
+ return;
702
+ }
703
+ const list = [
704
+ ...changed.map((p) => `${p} (changed on the platform since this folder was last synced)`),
705
+ ...deleted.map((p) => `${p} (deleted on the platform since this folder was last synced; pushing would bring it back)`),
706
+ ].join("\n");
707
+ const CANCEL = "Cancel";
708
+ const OVERWRITE_ALL = "Overwrite all";
709
+ const answer = await opts.ctx.prompt.confirm(`${toAsk.length} file(s) would overwrite a platform version nobody here has seen:\n\n${list}\n\n` +
710
+ `Nothing has been pushed yet. Overwrite all of them with your local files?`, [CANCEL, OVERWRITE_ALL], { destructive: true, safeOption: CANCEL });
711
+ if (answer !== OVERWRITE_ALL) {
712
+ const kind = opts.isSnapshot ? "Snapshot push" : "Push";
713
+ await opts.ctx.prompt.popup(`${kind} cancelled: nothing was pushed.`);
714
+ throw new Err_1.Err.OverwriteDeclinedError(`${kind} stopped before pushing anything: ${toAsk.length} file(s) were not overwritten, because ` +
715
+ `each would overwrite a platform version nobody here has seen:\n\n${list}\n\n` +
716
+ `Pull or audit them to see the platform versions before overwriting them.`, [...toAsk]);
717
+ }
718
+ }
719
+ /**
720
+ * Commits the draft folder's changes to the script's draft branch and pushes it; with `build`, asks the platform to
721
+ * build the pushed commit and fast-forwards the folder to the build commit (the platform compiles; nothing compiles
722
+ * here); for a snapshot, then publishes the build commit.
723
+ *
724
+ * Where the repo lives depends on the folder, and the script's publish mode (read first, never assumed from a repo
725
+ * being there) decides whether a switch is needed:
726
+ * - a folder bound to this script's repo whose script is in git mode is pushed in place (and must have the draft
727
+ * branch checked out);
728
+ * - a folder with no repo (a push), or one bound to a read-only mirror of a script that still publishes over WebDAV, is
729
+ * bound to the repo, but only after every consent has been given: the scratch clone is read, the overwrite
730
+ * confirmation asked, and only then is the folder's `.git` installed;
731
+ * - a deploy, or a folder bound to some other script, copies its files through a scratch clone.
732
+ * A script still publishing over WebDAV is switched to git first, which is one-way and confirmed first (`enableGit`
733
+ * pre-confirms). Its platform draft cannot be compared before it is switched, so the overwrite confirmation for it
734
+ * follows the switch, and nothing is installed locally until it is given.
735
+ *
736
+ * Before anything is pushed, one confirmation covers every platform file the push would overwrite or bring back, and
737
+ * another every platform file with no local copy; the safe answers keep the platform's version. The files committed
738
+ * follow git's ignore rules, including the old script-root `.gitignore` rules ({@link legacyIgnoreRulesForDraft}).
739
+ * Nothing is read through a symbolic link.
740
+ *
741
+ * Once the push has succeeded, nothing that follows throws: a failed build comes back as `build.error` and a failed
742
+ * publish as `publish.error`.
743
+ *
744
+ * @throws an {@link Err.OverwriteDeclinedError} when an overwrite is not confirmed.
745
+ * @throws {GitSwitchDeclinedError} when the switch is needed and declined.
746
+ * @throws {GitWrongBranchError} when the folder's repo has another branch checked out.
747
+ * @throws {BsjsGitError} (a typed subclass) when git or the platform refuses the push.
748
+ * @lastreviewed null
749
+ */
750
+ async function pushDraft(target, options) {
751
+ const files = new WorkTreeFiles(target.ctx);
752
+ const tracker = { switched: false };
753
+ try {
754
+ return await pushDraftInner(target, options, files, tracker);
755
+ }
756
+ catch (error) {
757
+ throw markSwitched(error, tracker);
758
+ }
759
+ finally {
760
+ files.reportSkipped();
761
+ }
762
+ }
763
+ async function pushDraftInner(target, options, files, tracker) {
764
+ const { ctx, draftPath } = target;
765
+ const scriptRoot = path.dirname(draftPath);
766
+ const probe = await openRepo(target, draftPath, options.author);
767
+ const hasGit = await files.exists(path.join(draftPath, GIT_DIR));
768
+ const origin = hasGit ? await readOriginUrl(files, draftPath) : undefined;
769
+ const boundHere = origin !== undefined && normalizeRepoUrl(origin) === normalizeRepoUrl(probe.url);
770
+ const inGitMode = (await probe.gitMode()).gitPublishing;
771
+ let mode;
772
+ if (boundHere && inGitMode) {
773
+ mode = "inPlace";
774
+ }
775
+ else if (boundHere || (!hasGit && options.adoptUnbound)) {
776
+ mode = "adopt";
777
+ }
778
+ else {
779
+ mode = "transplant";
780
+ }
781
+ if (mode === "inPlace") {
782
+ const branch = await probe.currentBranch();
783
+ if (branch !== b6p_core_bsjs_git_1.DRAFT_BRANCH) {
784
+ throw new GitWrongBranchError(branch);
785
+ }
786
+ }
787
+ let switchedToGit = false;
788
+ if (!inGitMode) {
789
+ await requireSwitchConsent(ctx, options.enableGit);
790
+ switchedToGit = (await probe.ensureGitModeResult()).switched;
791
+ tracker.switched = switchedToGit;
792
+ }
793
+ let repo = probe;
794
+ let scratch;
795
+ let tempDir;
796
+ try {
797
+ if (mode === "adopt") {
798
+ const cloned = await cloneToScratch(target, files, options.author);
799
+ repo = cloned.repo;
800
+ scratch = cloned.scratch;
801
+ }
802
+ else if (mode === "transplant") {
803
+ tempDir = await files.mkdtemp(path.join(os.tmpdir(), "b6p-push-"));
804
+ repo = await openRepo(target, tempDir, options.author);
805
+ await repo.clone();
806
+ await ensureLocalExcludes(files, tempDir, scriptRoot);
807
+ }
808
+ else {
809
+ await ensureLocalExcludes(files, draftPath, scriptRoot);
810
+ await repo.fetch();
811
+ await takeInPendingBuild(repo, ctx.logger);
812
+ }
813
+ const local = await repo.sha(b6p_core_bsjs_git_1.DRAFT_BRANCH);
814
+ const remote = await remoteDraftOf(repo);
815
+ const platformMoved = mode === "inPlace" && !!remote && remote !== local && !(await repo.isAncestor(remote, local));
816
+ let risks = { changed: [], platformOnly: [], deleted: [] };
817
+ if (remote) {
818
+ if (mode === "inPlace") {
819
+ if (platformMoved) {
820
+ const diff = await repo.diff(local, remote);
821
+ const found = await findOverwriteRisks({
822
+ repo,
823
+ files,
824
+ workRoot: draftPath,
825
+ remote,
826
+ paths: diff.filter((c) => c.newOid !== undefined).map((c) => c.path),
827
+ moved: async () => true,
828
+ });
829
+ const deleted = [];
830
+ for (const change of diff.filter((c) => c.newOid === undefined)) {
831
+ if (await files.readOptional(draftPath, absolute(draftPath, change.path))) {
832
+ deleted.push(change.path);
833
+ }
834
+ }
835
+ risks = { ...found, deleted };
836
+ }
837
+ }
838
+ else {
839
+ const lastSynced = mode === "adopt" ? options.lastSynced : undefined;
840
+ // A read-only mirror this folder was bound to knows what the platform had when it was pulled.
841
+ const mirrorHead = hasGit && mode === "adopt" ? probe : undefined;
842
+ const found = await findOverwriteRisks({
843
+ repo,
844
+ files,
845
+ workRoot: draftPath,
846
+ remote,
847
+ paths: (await repo.listTree(remote)).map((f) => f.path),
848
+ moved: async (relative, platform) => {
849
+ if (mirrorHead) {
850
+ const before = await mirrorHead.readFile(b6p_core_bsjs_git_1.DRAFT_BRANCH, relative).catch(() => undefined);
851
+ return before === undefined || !sameBytes(before, platform);
852
+ }
853
+ const recorded = lastSynced ? await lastSynced(relative) : null;
854
+ return recorded === null || recorded !== sha512Hex(platform);
855
+ },
856
+ });
857
+ risks = { ...found, deleted: [] };
858
+ }
859
+ }
860
+ await confirmOverwrittenFiles({
861
+ ctx,
862
+ paths: risks.changed,
863
+ deleted: risks.deleted,
864
+ isSnapshot: options.snapshot,
865
+ preConfirmed: options.preConfirmed,
866
+ });
867
+ const keptPlatformOnly = [];
868
+ if (risks.platformOnly.length > 0) {
869
+ // "No" is FIRST: an empty answer and auto-confirm both take options[0], and a yes drops platform files that may
870
+ // exist nowhere else.
871
+ const NO = "No";
872
+ const YES = "Yes";
873
+ let answer;
874
+ try {
875
+ answer = await ctx.prompt.confirm(`The following ${risks.platformOnly.length} platform file(s) have no local counterpart:\n\n` +
876
+ `${risks.platformOnly.join("\n")}\n\nDelete them from the platform?`, [NO, YES], { destructive: true, safeOption: NO });
877
+ }
878
+ catch (error) {
879
+ // No answer at all (end of input, a dismissed dialog) is not a yes.
880
+ ctx.logger.warn(`Delete prompt got no answer: ${error instanceof Error ? error.message : error}`);
881
+ }
882
+ if (answer !== YES) {
883
+ keptPlatformOnly.push(...risks.platformOnly);
884
+ ctx.prompt.warn(`Kept ${keptPlatformOnly.length} platform-only file(s): they are on the platform but not in your local ` +
885
+ `draft folder, and deleting them was not confirmed.\n\n${keptPlatformOnly.join("\n")}\n\n` +
886
+ `Their platform copies are included in this push.`);
887
+ }
888
+ }
889
+ // Every consent is in: only now does the draft folder change.
890
+ if (mode === "adopt" && scratch) {
891
+ await installGit(files, scratch, draftPath);
892
+ repo = await openRepo(target, draftPath, options.author);
893
+ await ensureLocalExcludes(files, draftPath, scriptRoot);
894
+ }
895
+ const repoDir = mode === "transplant" ? tempDir : draftPath;
896
+ if (mode === "transplant") {
897
+ await files.clearExceptGit(repoDir);
898
+ // Every file is copied and git's ignore rules (the source's `.gitignore` and the rules carried over) decide at
899
+ // commit time what is committed.
900
+ for (const relative of await files.listFiles(draftPath)) {
901
+ const bytes = await files.readOptional(draftPath, absolute(draftPath, relative));
902
+ if (bytes) {
903
+ await files.write(repoDir, absolute(repoDir, relative), bytes);
904
+ }
905
+ }
906
+ }
907
+ for (const relative of keptPlatformOnly) {
908
+ await files.write(repoDir, absolute(repoDir, relative), await repo.readFile(remote, relative));
909
+ }
910
+ const commitSha = platformMoved
911
+ ? await repo.commit(options.message, options.author, { parents: [local, remote] })
912
+ : await repo.commit(options.message, options.author);
913
+ const head = commitSha ?? local;
914
+ if (head !== remote) {
915
+ const pushed = await repo.push();
916
+ if (pushed.sha !== head) {
917
+ throw new GitWrongBranchError(await repo.currentBranch());
918
+ }
919
+ }
920
+ const outcome = { commitSha: head, switchedToGit, keptPlatformOnly };
921
+ if (!options.build) {
922
+ return options.snapshot ? { ...outcome, publish: await publishAndVerify(repo, head) } : outcome;
923
+ }
924
+ const build = await buildPushed(repo, options.sleep);
925
+ const moved = build.fastForward?.state;
926
+ if (!options.snapshot ||
927
+ build.error !== null ||
928
+ !build.compile ||
929
+ !(0, b6p_core_bsjs_git_1.compileAllowsPublish)(build.compile.status) ||
930
+ (moved !== "fast-forwarded" && moved !== "unchanged")) {
931
+ return { ...outcome, build };
932
+ }
933
+ // Pinned to what was built and checked: a later save cannot be published under this build's result.
934
+ return { ...outcome, build, publish: await publishAndVerify(repo, build.buildCommitSha ?? head) };
935
+ }
936
+ finally {
937
+ if (scratch) {
938
+ await files.remove(scratch);
939
+ }
940
+ if (tempDir) {
941
+ await files.remove(tempDir);
942
+ }
943
+ }
944
+ }
945
+ /**
946
+ * Takes in the platform's build of the local draft when the platform's draft is exactly that (a build whose answer
947
+ * this folder never got: a lost response, or a failure after the build committed), so it is not mistaken for a platform
948
+ * edit. Anything else on the platform is left to the overwrite checks, and so is a move that fails.
949
+ * @throws {GitBuildFastForwardBlockedError} when local files the build changes are in the way; nothing was changed
950
+ * @lastreviewed null
951
+ */
952
+ async function takeInPendingBuild(repo, logger) {
953
+ const remote = await remoteDraftOf(repo);
954
+ const local = await repo.sha(b6p_core_bsjs_git_1.DRAFT_BRANCH);
955
+ if (!remote || remote === local || !(await repo.isBuildCommitOf(remote, local))) {
956
+ return;
957
+ }
958
+ const moved = await repo.fastForwardToBuild(remote);
959
+ if (moved.state === "blocked") {
960
+ throw new b6p_core_bsjs_git_1.GitBuildFastForwardBlockedError(remote, moved.blockedPaths);
961
+ }
962
+ if (moved.state === "failed") {
963
+ // The draft branch did not move; the overwrite checks below see the platform's draft as it is.
964
+ logger.warn(`Could not take in the platform's build ${remote} of this folder's draft: ${moved.error}`);
965
+ }
966
+ }
967
+ /**
968
+ * The structured refusal in an error, when it is a `PUBLISH_REFUSED`.
969
+ * @lastreviewed null
970
+ */
971
+ function refusalOf(error) {
972
+ if (!(error instanceof b6p_core_bsjs_git_1.PublishRefusedError)) {
973
+ return null;
974
+ }
975
+ const withheld = error.details?.withheld;
976
+ return {
977
+ reason: error.reason ?? "",
978
+ withheld: Array.isArray(withheld) ? withheld.filter((p) => typeof p === "string") : [],
979
+ };
980
+ }
981
+ /**
982
+ * Asks the platform to build the draft just pushed and fast-forwards to its build commit. Never throws: the push already
983
+ * succeeded, and a failed build request comes back as `error`.
984
+ * @lastreviewed null
985
+ */
986
+ async function buildPushed(repo, sleep) {
987
+ try {
988
+ const result = await repo.compileDraft(sleep ? { sleep } : {});
989
+ return {
990
+ compile: result.compile,
991
+ buildCommitSha: result.buildCommitSha,
992
+ fastForward: result.fastForward,
993
+ outcomeUnknown: result.outcomeUnknown,
994
+ vouched: result.vouched,
995
+ error: null,
996
+ errorKind: null,
997
+ errorReason: null,
998
+ };
999
+ }
1000
+ catch (error) {
1001
+ return {
1002
+ compile: null,
1003
+ buildCommitSha: null,
1004
+ fastForward: null,
1005
+ outcomeUnknown: null,
1006
+ vouched: false,
1007
+ error: error instanceof Error ? error.message : String(error),
1008
+ errorKind: error instanceof b6p_core_bsjs_git_1.GitUnpushedChangesError
1009
+ ? "not-requested"
1010
+ : error instanceof b6p_core_bsjs_git_1.DraftBuildFailedError && error.reason !== null
1011
+ ? "refused"
1012
+ : "request-failed",
1013
+ errorReason: error instanceof b6p_core_bsjs_git_1.DraftBuildFailedError ? error.reason : null,
1014
+ };
1015
+ }
1016
+ }
1017
+ /**
1018
+ * Publishes the pushed draft and reads back that the platform's published branch is at the commit the platform says it
1019
+ * published. Anything that goes wrong comes back as `error`, never a throw: the push itself already succeeded, and the
1020
+ * caller must still learn its commit.
1021
+ * @lastreviewed null
1022
+ */
1023
+ async function publishAndVerify(repo, at) {
1024
+ let publishedSha;
1025
+ let refreshed;
1026
+ try {
1027
+ const result = await repo.publish({ at });
1028
+ publishedSha = result.publishedSha;
1029
+ refreshed = result.refreshed;
1030
+ }
1031
+ catch (error) {
1032
+ return {
1033
+ publishedSha: null,
1034
+ error: error instanceof Error ? error.message : String(error),
1035
+ refusal: refusalOf(error),
1036
+ liveVerified: null,
1037
+ liveMismatches: [],
1038
+ };
1039
+ }
1040
+ try {
1041
+ if (!refreshed) {
1042
+ await repo.fetch();
1043
+ }
1044
+ const master = await repo.sha(REMOTE_MASTER);
1045
+ if (master === publishedSha) {
1046
+ return { publishedSha, error: null, refusal: null, liveVerified: true, liveMismatches: [] };
1047
+ }
1048
+ let liveMismatches = [];
1049
+ try {
1050
+ liveMismatches = (await repo.diff(publishedSha, master)).map((c) => c.path);
1051
+ }
1052
+ catch {
1053
+ // The published branch's objects may not be local; the sha mismatch is the finding.
1054
+ }
1055
+ return { publishedSha, error: null, refusal: null, liveVerified: false, liveMismatches };
1056
+ }
1057
+ catch {
1058
+ return { publishedSha, error: null, refusal: null, liveVerified: null, liveMismatches: [] };
1059
+ }
1060
+ }
1061
+ /**
1062
+ * The draft folder of a script root, `<root>/draft`.
1063
+ * @lastreviewed null
1064
+ */
1065
+ function draftFolderOf(rootPath) {
1066
+ return path.join(rootPath, constants_1.FolderNames.DRAFT);
1067
+ }
1068
+ //# sourceMappingURL=GitSync.js.map