@bluestep-systems/b6p-core 0.9.0 → 1.1.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.
- package/README.md +274 -24
- package/dist/B6PCore.d.ts +13 -0
- package/dist/B6PCore.js +61 -1
- package/dist/B6PCore.js.map +1 -1
- package/dist/B6PUri.d.ts +6 -8
- package/dist/B6PUri.js +6 -8
- package/dist/B6PUri.js.map +1 -1
- package/dist/Err.d.ts +434 -0
- package/dist/Err.js +582 -0
- package/dist/Err.js.map +1 -1
- package/dist/auth/BearerAuthProvider.d.ts +32 -0
- package/dist/auth/BearerAuthProvider.js +49 -0
- package/dist/auth/BearerAuthProvider.js.map +1 -1
- package/dist/cache/OrgCache.js.map +1 -1
- package/dist/cache/ScriptMetaDataStore.js.map +1 -1
- package/dist/constants/ApiEndpoints.d.ts +1 -0
- package/dist/constants/ApiEndpoints.js +1 -0
- package/dist/constants/ApiEndpoints.js.map +1 -1
- package/dist/constants/AuthTypes.js.map +1 -1
- package/dist/constants/BlueHQ.js.map +1 -1
- package/dist/constants/CryptoAlgorithms.js.map +1 -1
- package/dist/constants/ExtensionConfig.js.map +1 -1
- package/dist/constants/FileExtensions.js.map +1 -1
- package/dist/constants/FolderNames.js.map +1 -1
- package/dist/constants/Gateway.d.ts +71 -0
- package/dist/constants/Gateway.js +79 -0
- package/dist/constants/Gateway.js.map +1 -0
- package/dist/constants/GitHubUrls.js.map +1 -1
- package/dist/constants/Http.js.map +1 -1
- package/dist/constants/MimeTypes.js.map +1 -1
- package/dist/constants/Numerical.js.map +1 -1
- package/dist/constants/OutputChannels.js.map +1 -1
- package/dist/constants/SettingsKeys.d.ts +5 -0
- package/dist/constants/SettingsKeys.js +5 -0
- package/dist/constants/SettingsKeys.js.map +1 -1
- package/dist/constants/SpecialFiles.js.map +1 -1
- package/dist/constants/WebDAVElements.js.map +1 -1
- package/dist/constants/index.d.ts +1 -0
- package/dist/constants/index.js +3 -1
- package/dist/constants/index.js.map +1 -1
- package/dist/data/DownstairsPathParser.js.map +1 -1
- package/dist/data/GlobMatcher.js.map +1 -1
- package/dist/data/IdUtility.js.map +1 -1
- package/dist/data/OrgWorker.js.map +1 -1
- package/dist/data/ScriptKey.js.map +1 -1
- package/dist/data/ScriptUrlParser.js.map +1 -1
- package/dist/data/ServerVersion.d.ts +76 -0
- package/dist/data/ServerVersion.js +111 -0
- package/dist/data/ServerVersion.js.map +1 -0
- package/dist/data/index.d.ts +2 -0
- package/dist/data/index.js +7 -1
- package/dist/data/index.js.map +1 -1
- package/dist/gateway/GatewayClient.d.ts +147 -0
- package/dist/gateway/GatewayClient.js +395 -0
- package/dist/gateway/GatewayClient.js.map +1 -0
- package/dist/gateway/GatewayContext.d.ts +43 -0
- package/dist/gateway/GatewayContext.js +3 -0
- package/dist/gateway/GatewayContext.js.map +1 -0
- package/dist/gateway/GatewayGit.d.ts +291 -0
- package/dist/gateway/GatewayGit.js +731 -0
- package/dist/gateway/GatewayGit.js.map +1 -0
- package/dist/gateway/GatewayKb.d.ts +173 -0
- package/dist/gateway/GatewayKb.js +354 -0
- package/dist/gateway/GatewayKb.js.map +1 -0
- package/dist/gateway/GatewayMarketplace.d.ts +116 -0
- package/dist/gateway/GatewayMarketplace.js +278 -0
- package/dist/gateway/GatewayMarketplace.js.map +1 -0
- package/dist/gateway/GatewayService.d.ts +47 -0
- package/dist/gateway/GatewayService.js +54 -0
- package/dist/gateway/GatewayService.js.map +1 -0
- package/dist/gateway/GatewayToken.d.ts +18 -0
- package/dist/gateway/GatewayToken.js +43 -0
- package/dist/gateway/GatewayToken.js.map +1 -0
- package/dist/gateway/GatewayTokenService.d.ts +101 -0
- package/dist/gateway/GatewayTokenService.js +465 -0
- package/dist/gateway/GatewayTokenService.js.map +1 -0
- package/dist/index.d.ts +27 -9
- package/dist/index.js +36 -7
- package/dist/index.js.map +1 -1
- package/dist/network/HttpClient.js.map +1 -1
- package/dist/network/HttpClientProvider.js.map +1 -1
- package/dist/network/StatusCodes.js.map +1 -1
- package/dist/persistence/PersistablePseudoMap.js.map +1 -1
- package/dist/persistence/PersistenceKeys.js.map +1 -1
- package/dist/persistence/PrivatePersistanceMap.js.map +1 -1
- package/dist/persistence/PseudoMap.js.map +1 -1
- package/dist/persistence/PublicPersistanceMap.js.map +1 -1
- package/dist/persistence/Serializable.js.map +1 -1
- package/dist/persistence/SharedFilePersistence.d.ts +22 -0
- package/dist/persistence/SharedFilePersistence.js +65 -14
- package/dist/persistence/SharedFilePersistence.js.map +1 -1
- package/dist/persistence/TypedMap.js.map +1 -1
- package/dist/persistence/TypedPersistable.js.map +1 -1
- package/dist/persistence/TypedPrivatePersistable.js.map +1 -1
- package/dist/persistence/dirLockdown.js.map +1 -1
- package/dist/providers.d.ts +36 -19
- package/dist/schema/SchemaContext.d.ts +10 -0
- package/dist/schema/SchemaContext.js +3 -0
- package/dist/schema/SchemaContext.js.map +1 -0
- package/dist/schema/SchemaService.d.ts +99 -0
- package/dist/schema/SchemaService.js +225 -0
- package/dist/schema/SchemaService.js.map +1 -0
- package/dist/script/GitIdentity.js.map +1 -1
- package/dist/script/GitSync.d.ts +78 -11
- package/dist/script/GitSync.js +84 -17
- package/dist/script/GitSync.js.map +1 -1
- package/dist/script/ScriptContext.d.ts +1 -8
- package/dist/script/ScriptFactory.d.ts +1 -2
- package/dist/script/ScriptFactory.js +1 -2
- package/dist/script/ScriptFactory.js.map +1 -1
- package/dist/script/ScriptFile.js.map +1 -1
- package/dist/script/ScriptFolder.js.map +1 -1
- package/dist/script/ScriptNode.js.map +1 -1
- package/dist/script/ScriptRoot.d.ts +0 -63
- package/dist/script/ScriptRoot.js +0 -178
- package/dist/script/ScriptRoot.js.map +1 -1
- package/dist/script/ScriptService.d.ts +45 -11
- package/dist/script/ScriptService.js +44 -6
- package/dist/script/ScriptService.js.map +1 -1
- package/dist/script/ServerCompile.d.ts +35 -0
- package/dist/script/ServerCompile.js +40 -0
- package/dist/script/ServerCompile.js.map +1 -0
- package/dist/script/TsConfig.d.ts +2 -2
- package/dist/script/TsConfig.js +3 -3
- package/dist/script/TsConfig.js.map +1 -1
- package/dist/script/push.d.ts +117 -77
- package/dist/script/push.js +151 -170
- package/dist/script/push.js.map +1 -1
- package/dist/session/SessionManager.js.map +1 -1
- package/dist/testing/FakeGateway.d.ts +280 -0
- package/dist/testing/FakeGateway.js +627 -0
- package/dist/testing/FakeGateway.js.map +1 -0
- package/dist/testing/MockFileSystem.js.map +1 -1
- package/dist/types.d.ts +534 -0
- package/dist/update/UpdateService.js.map +1 -1
- package/package.json +8 -7
- package/dist/script/ScriptTranspiler.d.ts +0 -183
- package/dist/script/ScriptTranspiler.js +0 -425
- package/dist/script/ScriptTranspiler.js.map +0 -1
- package/dist/script/TsLibResolver.d.ts +0 -60
- package/dist/script/TsLibResolver.js +0 -134
- package/dist/script/TsLibResolver.js.map +0 -1
|
@@ -0,0 +1,731 @@
|
|
|
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
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.GatewayGit = void 0;
|
|
40
|
+
const nodeFs = __importStar(require("node:fs"));
|
|
41
|
+
const path = __importStar(require("node:path"));
|
|
42
|
+
const isomorphic_git_1 = __importDefault(require("isomorphic-git"));
|
|
43
|
+
const Gateway_1 = require("../constants/Gateway");
|
|
44
|
+
const Http_1 = require("../constants/Http");
|
|
45
|
+
const Err_1 = require("../Err");
|
|
46
|
+
const GatewayClient_1 = require("./GatewayClient");
|
|
47
|
+
const GatewayToken_1 = require("./GatewayToken");
|
|
48
|
+
/**
|
|
49
|
+
* The remote name every clone made here uses.
|
|
50
|
+
* @lastreviewed null
|
|
51
|
+
*/
|
|
52
|
+
const REMOTE = "origin";
|
|
53
|
+
/**
|
|
54
|
+
* How many annotated tags deep a tag may point at another tag before peeling stops.
|
|
55
|
+
* @lastreviewed null
|
|
56
|
+
*/
|
|
57
|
+
const MAX_TAG_DEPTH = 10;
|
|
58
|
+
// Normalise a path from isomorphic-git (already `/`-separated) and drop a leading `./`.
|
|
59
|
+
function posix(file) {
|
|
60
|
+
return file.split(path.sep).join("/").replace(/^\.\//, "");
|
|
61
|
+
}
|
|
62
|
+
// isomorphic-git error codes that mean the other end did not speak smart HTTP.
|
|
63
|
+
const PROTOCOL_ERROR_CODES = new Set([
|
|
64
|
+
"HttpError",
|
|
65
|
+
"SmartHttpError",
|
|
66
|
+
"ParseError",
|
|
67
|
+
"EmptyServerResponseError",
|
|
68
|
+
"RemoteCapabilityError",
|
|
69
|
+
"UnknownTransportError",
|
|
70
|
+
"UrlParseError",
|
|
71
|
+
"NotFoundError",
|
|
72
|
+
"InvalidOidError",
|
|
73
|
+
"InternalError",
|
|
74
|
+
]);
|
|
75
|
+
// Whether any component of the resolved path is `.git` or an alias a filesystem resolves to it:
|
|
76
|
+
// the Windows short name (`git~1`), Unicode-ignorable characters inside the name (HFS+ ignores
|
|
77
|
+
// them), and trailing dots or spaces (NTFS drops them). Each component is NFC-normalised, stripped
|
|
78
|
+
// of ignorables and of trailing dots/spaces, then compared case-insensitively. A clone there would
|
|
79
|
+
// put its config inside a git directory, where git runs the commands that config names
|
|
80
|
+
// (core.fsmonitor and the like).
|
|
81
|
+
function hasGitDirComponent(dir) {
|
|
82
|
+
return path
|
|
83
|
+
.resolve(dir)
|
|
84
|
+
.split(/[\\/]+/)
|
|
85
|
+
.some((part) => {
|
|
86
|
+
const name = part
|
|
87
|
+
.normalize("NFC")
|
|
88
|
+
.replace(/[\p{Cf}\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff]/gu, "")
|
|
89
|
+
.replace(/[. ]+$/, "");
|
|
90
|
+
return /^(\.git|git~\d+)$/i.test(name);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
// The outermost folder on the way to `dir` that does not exist yet: what a clone into `dir` creates.
|
|
94
|
+
function topmostMissing(dir) {
|
|
95
|
+
let top = path.resolve(dir);
|
|
96
|
+
for (;;) {
|
|
97
|
+
const parent = path.dirname(top);
|
|
98
|
+
if (parent === top || nodeFs.existsSync(parent)) {
|
|
99
|
+
return top;
|
|
100
|
+
}
|
|
101
|
+
top = parent;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// The error's `code`, as isomorphic-git sets it on every error it throws.
|
|
105
|
+
function codeOf(error) {
|
|
106
|
+
if (typeof error === "object" && error !== null && "code" in error) {
|
|
107
|
+
const code = error.code;
|
|
108
|
+
return typeof code === "string" ? code : undefined;
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
// The `filepaths` of an isomorphic-git `CheckoutConflictError`, or `[]` for any other error.
|
|
113
|
+
function conflictPathsOf(error) {
|
|
114
|
+
if (codeOf(error) === "CheckoutConflictError" && typeof error === "object" && error !== null && "data" in error) {
|
|
115
|
+
const data = error.data;
|
|
116
|
+
if (typeof data === "object" && data !== null && "filepaths" in data) {
|
|
117
|
+
const filepaths = data.filepaths;
|
|
118
|
+
if (Array.isArray(filepaths)) {
|
|
119
|
+
return filepaths.filter((p) => typeof p === "string").map(posix);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Git over the gateway's smart HTTP endpoints, in pure JS (isomorphic-git; no git install needed).
|
|
127
|
+
* It works only with the gateway-supplied `gitUrl` from the listings, never one it builds.
|
|
128
|
+
*
|
|
129
|
+
* Safety rules, all enforced here rather than left to a caller:
|
|
130
|
+
* - every request carries the `b6pt_` token via {@link GatewayClient.authHeadersFor}, which refuses
|
|
131
|
+
* a URL off the gateway's origin before any request is made; redirects are never followed;
|
|
132
|
+
* - {@link push} sends the current branch to its upstream only as a fast-forward: never forced,
|
|
133
|
+
* never a ref deletion, never a tag;
|
|
134
|
+
* - {@link pull} only fast-forwards, and refuses (naming the paths) when it would overwrite local
|
|
135
|
+
* changes;
|
|
136
|
+
* - file contents are never rewritten: no `autocrlf`, no filters, so a Windows checkout keeps the
|
|
137
|
+
* bytes the repository holds.
|
|
138
|
+
*
|
|
139
|
+
* Each operation runs inside the {@link GatewayClient} queue, so git traffic never overlaps a REST
|
|
140
|
+
* call or another git operation. The working copy is on the local disk through Node's `fs`
|
|
141
|
+
* directly: isomorphic-git needs the Node-fs surface (`lstat`, symlinks, file modes, sub-second
|
|
142
|
+
* mtimes) that the core `FileSystem` provider (URI-based, no `lstat`/`symlink`/`chmod`) does not
|
|
143
|
+
* offer, and a clone is always a real folder on the local machine.
|
|
144
|
+
* @lastreviewed null
|
|
145
|
+
*/
|
|
146
|
+
class GatewayGit {
|
|
147
|
+
ctx;
|
|
148
|
+
client;
|
|
149
|
+
firstByteTimeoutMs;
|
|
150
|
+
idleTimeoutMs;
|
|
151
|
+
stall;
|
|
152
|
+
constructor(ctx, client, options = {}) {
|
|
153
|
+
this.ctx = ctx;
|
|
154
|
+
this.client = client;
|
|
155
|
+
this.firstByteTimeoutMs = options.firstByteTimeoutMs ?? Gateway_1.Gateway.GIT_FIRST_BYTE_TIMEOUT_MS;
|
|
156
|
+
this.idleTimeoutMs = options.idleTimeoutMs ?? Gateway_1.Gateway.GIT_IDLE_TIMEOUT_MS;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Clone `gitUrl` into `dir` (created if missing; it must be empty if it exists) and check out
|
|
160
|
+
* `ref`, or the default branch.
|
|
161
|
+
*
|
|
162
|
+
* @param gitUrl the `gitUrl` of a knowledge base or marketplace repo from the gateway's listing
|
|
163
|
+
* @param dir the local folder (an OS path)
|
|
164
|
+
* @throws {Err.GatewayWorkingCopyError} `not-empty` when `dir` has files; `ref-not-found`
|
|
165
|
+
* @throws {Err.GatewayError} a subclass for any gateway failure (see {@link gatewayErrorFor})
|
|
166
|
+
* @lastreviewed null
|
|
167
|
+
*/
|
|
168
|
+
clone(gitUrl, dir, options = {}) {
|
|
169
|
+
return this.sequenced(async () => {
|
|
170
|
+
if (hasGitDirComponent(dir)) {
|
|
171
|
+
throw new Err_1.Err.GatewayWorkingCopyError("The clone target has a .git (or git~N) path component, so nothing was cloned.", "unsafe-target");
|
|
172
|
+
}
|
|
173
|
+
await this.client.authHeadersFor(gitUrl);
|
|
174
|
+
const existed = nodeFs.existsSync(dir);
|
|
175
|
+
const topCreated = existed ? undefined : topmostMissing(dir);
|
|
176
|
+
if (existed && (!nodeFs.statSync(dir).isDirectory() || nodeFs.readdirSync(dir).length > 0)) {
|
|
177
|
+
throw new Err_1.Err.GatewayWorkingCopyError(`${dir} already has files, so nothing was cloned into it.`, "not-empty");
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
await isomorphic_git_1.default.clone({
|
|
181
|
+
fs: nodeFs,
|
|
182
|
+
http: this.http(),
|
|
183
|
+
dir,
|
|
184
|
+
url: gitUrl,
|
|
185
|
+
remote: REMOTE,
|
|
186
|
+
ref: options.ref,
|
|
187
|
+
singleBranch: true,
|
|
188
|
+
});
|
|
189
|
+
this.throwIfStalled();
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
// Whatever is in `dir` now was put there by this attempt (it was absent or empty).
|
|
193
|
+
if (existed) {
|
|
194
|
+
for (const entry of nodeFs.readdirSync(dir)) {
|
|
195
|
+
nodeFs.rmSync(path.join(dir, entry), { recursive: true, force: true });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
nodeFs.rmSync(topCreated ?? dir, { recursive: true, force: true });
|
|
200
|
+
}
|
|
201
|
+
throw this.notFoundRef(error, options.ref) ?? error;
|
|
202
|
+
}
|
|
203
|
+
const head = await isomorphic_git_1.default.resolveRef({ fs: nodeFs, dir, ref: "HEAD" });
|
|
204
|
+
const branch = (await isomorphic_git_1.default.currentBranch({ fs: nodeFs, dir })) ?? null;
|
|
205
|
+
return { branch, head };
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The URL the clone in `dir` fetches from and pushes to (its `origin`), or `null` when it has none.
|
|
210
|
+
* @throws {Err.GatewayWorkingCopyError} `not-a-clone` when `dir` is not a clone
|
|
211
|
+
* @lastreviewed null
|
|
212
|
+
*/
|
|
213
|
+
async originUrl(dir) {
|
|
214
|
+
this.requireClone(dir);
|
|
215
|
+
const url = await isomorphic_git_1.default.getConfig({ fs: nodeFs, dir, path: `remote.${REMOTE}.url` });
|
|
216
|
+
return typeof url === "string" && url.length > 0 ? url : null;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The state of the clone in `dir`.
|
|
220
|
+
* @throws {Err.GatewayWorkingCopyError} `not-a-clone` when `dir` is not a clone (a detached head is not an
|
|
221
|
+
* error: `branch` is then `null`)
|
|
222
|
+
* @lastreviewed null
|
|
223
|
+
*/
|
|
224
|
+
status(dir, options = {}) {
|
|
225
|
+
return this.sequenced(async () => {
|
|
226
|
+
this.requireClone(dir);
|
|
227
|
+
const branch = (await isomorphic_git_1.default.currentBranch({ fs: nodeFs, dir })) ?? null;
|
|
228
|
+
const head = await isomorphic_git_1.default.resolveRef({ fs: nodeFs, dir, ref: "HEAD" });
|
|
229
|
+
const remoteBranch = branch ? await this.upstreamOf(dir, branch) : null;
|
|
230
|
+
if (options.fetch && remoteBranch) {
|
|
231
|
+
await this.fetchBranch(dir, remoteBranch);
|
|
232
|
+
}
|
|
233
|
+
let ahead = 0;
|
|
234
|
+
let behind = 0;
|
|
235
|
+
if (branch && remoteBranch) {
|
|
236
|
+
const counts = await this.aheadBehind(dir, head, remoteBranch);
|
|
237
|
+
ahead = counts.ahead;
|
|
238
|
+
behind = counts.behind;
|
|
239
|
+
}
|
|
240
|
+
const dirtyPaths = await this.dirtyPaths(dir);
|
|
241
|
+
return {
|
|
242
|
+
branch,
|
|
243
|
+
upstream: branch && remoteBranch ? `${REMOTE}/${remoteBranch}` : null,
|
|
244
|
+
head,
|
|
245
|
+
dirty: dirtyPaths.length > 0,
|
|
246
|
+
dirtyPaths,
|
|
247
|
+
ahead,
|
|
248
|
+
behind,
|
|
249
|
+
};
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Fetch the current branch's upstream and fast-forward to it. A clean tree just proceeds. Local
|
|
254
|
+
* changes the incoming commits do not touch are kept. The call never merges, rebases or
|
|
255
|
+
* overwrites.
|
|
256
|
+
*
|
|
257
|
+
* @throws {Err.GatewayDirtyWorkingTreeError} the incoming commits change files that have local
|
|
258
|
+
* changes (`paths`); nothing was changed
|
|
259
|
+
* @throws {Err.GatewayWorkingCopyError} `not-a-clone`, `detached`, `no-upstream`, or `diverged`
|
|
260
|
+
* @throws {Err.GatewayError} a subclass for any gateway failure
|
|
261
|
+
* @lastreviewed null
|
|
262
|
+
*/
|
|
263
|
+
pull(dir) {
|
|
264
|
+
return this.sequenced(async () => {
|
|
265
|
+
const tracking = await this.tracking(dir);
|
|
266
|
+
const { branch, head: from, remoteBranch } = tracking;
|
|
267
|
+
if (remoteBranch === null) {
|
|
268
|
+
throw this.noUpstream(branch);
|
|
269
|
+
}
|
|
270
|
+
await this.fetchBranch(dir, remoteBranch);
|
|
271
|
+
const remoteRef = `refs/remotes/${REMOTE}/${remoteBranch}`;
|
|
272
|
+
const to = await isomorphic_git_1.default.resolveRef({ fs: nodeFs, dir, ref: remoteRef });
|
|
273
|
+
if (to === from) {
|
|
274
|
+
return { outcome: "up-to-date", branch, from, to };
|
|
275
|
+
}
|
|
276
|
+
if (await isomorphic_git_1.default.isDescendent({ fs: nodeFs, dir, oid: from, ancestor: to })) {
|
|
277
|
+
return { outcome: "ahead", branch, from, to: from };
|
|
278
|
+
}
|
|
279
|
+
if (!(await isomorphic_git_1.default.isDescendent({ fs: nodeFs, dir, oid: to, ancestor: from }))) {
|
|
280
|
+
throw new Err_1.Err.GatewayWorkingCopyError(`${branch} and ${REMOTE}/${remoteBranch} have each moved on without the other, so it cannot be fast-forwarded.`, "diverged");
|
|
281
|
+
}
|
|
282
|
+
// An earlier pull killed after its checkout but before its ref write leaves HEAD at `from`
|
|
283
|
+
// over an index and files that are exactly `to`. Only that exact state is finished here.
|
|
284
|
+
if (await this.matchesCommit(dir, to)) {
|
|
285
|
+
await isomorphic_git_1.default.writeRef({ fs: nodeFs, dir, ref: `refs/heads/${branch}`, value: to, force: true });
|
|
286
|
+
return { outcome: "fast-forwarded", branch, from, to };
|
|
287
|
+
}
|
|
288
|
+
// The checkout rebuilds the index from `to`, which would silently drop anything staged, even
|
|
289
|
+
// on a path the incoming commits do not touch. So any staged change refuses the pull.
|
|
290
|
+
const staged = await this.stagedPaths(dir);
|
|
291
|
+
if (staged.length > 0) {
|
|
292
|
+
throw this.dirtyError(branch, staged, "staged");
|
|
293
|
+
}
|
|
294
|
+
const incoming = await this.changedBetween(dir, from, to);
|
|
295
|
+
const dirty = new Set(await this.dirtyPaths(dir));
|
|
296
|
+
const clash = incoming.filter((file) => dirty.has(file) || [...dirty].some((d) => file.startsWith(`${d}/`)));
|
|
297
|
+
if (clash.length > 0) {
|
|
298
|
+
throw this.dirtyError(branch, clash);
|
|
299
|
+
}
|
|
300
|
+
// Check the files out to the new commit FIRST and move the branch only once that has
|
|
301
|
+
// succeeded, so a crash mid-checkout leaves the branch at the old commit over (at worst)
|
|
302
|
+
// a part-updated tree, never HEAD at the new commit over the old files.
|
|
303
|
+
try {
|
|
304
|
+
await isomorphic_git_1.default.checkout({ fs: nodeFs, dir, ref: to, force: false, noUpdateHead: true });
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
const paths = conflictPathsOf(error);
|
|
308
|
+
if (paths.length > 0) {
|
|
309
|
+
throw this.dirtyError(branch, paths);
|
|
310
|
+
}
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
await isomorphic_git_1.default.writeRef({ fs: nodeFs, dir, ref: `refs/heads/${branch}`, value: to, force: true });
|
|
314
|
+
return { outcome: "fast-forwarded", branch, from, to };
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Push the current branch to its upstream, only as a fast-forward. Never forced, never a
|
|
319
|
+
* deletion, never tags. Nothing is sent when the branch has no commits upstream lacks.
|
|
320
|
+
*
|
|
321
|
+
* @throws {Err.GatewayConflictError} the upstream has moved on (not a fast-forward), whether the
|
|
322
|
+
* client or the gateway noticed
|
|
323
|
+
* @throws {Err.GatewayWorkingCopyError} `not-a-clone`, `detached` or `no-upstream`
|
|
324
|
+
* @throws {Err.GatewayError} a subclass for any other gateway failure (auth, scope, not permitted, ...)
|
|
325
|
+
* @lastreviewed null
|
|
326
|
+
*/
|
|
327
|
+
push(dir) {
|
|
328
|
+
return this.sequenced(async () => {
|
|
329
|
+
const tracking = await this.tracking(dir);
|
|
330
|
+
const { branch, head, remoteBranch } = tracking;
|
|
331
|
+
if (remoteBranch === null) {
|
|
332
|
+
throw this.noUpstream(branch);
|
|
333
|
+
}
|
|
334
|
+
// Refresh the view of the upstream first, so a branch behind it is refused here with the
|
|
335
|
+
// right reason and never reaches the wire.
|
|
336
|
+
await this.fetchBranch(dir, remoteBranch);
|
|
337
|
+
const counts = await this.aheadBehind(dir, head, remoteBranch);
|
|
338
|
+
if (counts.behind > 0) {
|
|
339
|
+
throw new Err_1.Err.GatewayConflictError(`${branch} does not build on ${REMOTE}/${remoteBranch}: the upstream has ${counts.behind} commit(s) it lacks, so the push was not sent.`, "non-fast-forward");
|
|
340
|
+
}
|
|
341
|
+
if (counts.ahead === 0) {
|
|
342
|
+
return { pushed: false, branch, remoteBranch, head };
|
|
343
|
+
}
|
|
344
|
+
let result;
|
|
345
|
+
try {
|
|
346
|
+
result = await isomorphic_git_1.default.push({
|
|
347
|
+
fs: nodeFs,
|
|
348
|
+
http: this.http(),
|
|
349
|
+
dir,
|
|
350
|
+
remote: REMOTE,
|
|
351
|
+
ref: branch,
|
|
352
|
+
remoteRef: `refs/heads/${remoteBranch}`,
|
|
353
|
+
force: false,
|
|
354
|
+
});
|
|
355
|
+
this.throwIfStalled();
|
|
356
|
+
}
|
|
357
|
+
catch (error) {
|
|
358
|
+
if (codeOf(error) === "PushRejectedError") {
|
|
359
|
+
throw new Err_1.Err.GatewayConflictError(`${branch} does not build on ${REMOTE}/${remoteBranch}: the push was rejected as not a fast-forward.`, "non-fast-forward");
|
|
360
|
+
}
|
|
361
|
+
throw error;
|
|
362
|
+
}
|
|
363
|
+
if (!result.ok) {
|
|
364
|
+
const said = Object.values(result.refs)
|
|
365
|
+
.map((r) => r.error)
|
|
366
|
+
.filter((e) => typeof e === "string");
|
|
367
|
+
const text = (0, GatewayToken_1.redactToken)([result.error, ...said].filter(Boolean).join("; "), await this.tokenText());
|
|
368
|
+
if (/non-fast-forward|fetch first|stale info/i.test(text)) {
|
|
369
|
+
throw new Err_1.Err.GatewayConflictError(`${branch} does not build on ${REMOTE}/${remoteBranch}: the gateway rejected the push as not a fast-forward.`, "non-fast-forward");
|
|
370
|
+
}
|
|
371
|
+
throw new Err_1.Err.GatewayUnexpectedResponseError(`The gateway did not accept the push of ${branch}${text ? `: ${text}` : ""}.`, null, null);
|
|
372
|
+
}
|
|
373
|
+
return { pushed: true, branch, remoteBranch, head };
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* What a clone's own config and refs say, for a caller deciding whether it is the clone it wants:
|
|
378
|
+
* the `origin` URL, the current branch (`null` when detached), the head commit, the remote branch
|
|
379
|
+
* the current branch tracks, and, when `tag` is given, the commit that local tag names (peeled
|
|
380
|
+
* through any chain of annotated tags, to a depth of 10), or `null` when there is no such tag.
|
|
381
|
+
* @throws {Err.GatewayWorkingCopyError} `not-a-clone` when `dir` has no usable git repository
|
|
382
|
+
* (no `.git`, a gitdir file, or a damaged one)
|
|
383
|
+
* @lastreviewed null
|
|
384
|
+
*/
|
|
385
|
+
inspect(dir, tag) {
|
|
386
|
+
return this.sequenced(async () => {
|
|
387
|
+
this.requireClone(dir);
|
|
388
|
+
try {
|
|
389
|
+
const origin = await isomorphic_git_1.default.getConfig({ fs: nodeFs, dir, path: `remote.${REMOTE}.url` });
|
|
390
|
+
const branch = (await isomorphic_git_1.default.currentBranch({ fs: nodeFs, dir })) ?? null;
|
|
391
|
+
const head = await isomorphic_git_1.default.resolveRef({ fs: nodeFs, dir, ref: "HEAD" });
|
|
392
|
+
const upstream = branch === null ? null : await this.upstreamOf(dir, branch);
|
|
393
|
+
const tagCommit = tag === undefined ? null : await this.localTagCommit(dir, tag);
|
|
394
|
+
return {
|
|
395
|
+
origin: typeof origin === "string" && origin.length > 0 ? origin : null,
|
|
396
|
+
branch,
|
|
397
|
+
head,
|
|
398
|
+
upstream,
|
|
399
|
+
tagCommit,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
throw new Err_1.Err.GatewayWorkingCopyError(`${dir} does not hold a usable git repository.`, "not-a-clone");
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* The commit a tag points at on the gateway right now (an annotated tag is peeled to its commit),
|
|
409
|
+
* or `null` when the repo has no such tag. Nothing is written locally.
|
|
410
|
+
* @param gitUrl the `gitUrl` of a listing
|
|
411
|
+
* @throws {Err.GatewayError} a subclass for any gateway failure
|
|
412
|
+
* @lastreviewed null
|
|
413
|
+
*/
|
|
414
|
+
remoteTagCommit(gitUrl, tag) {
|
|
415
|
+
return this.sequenced(async () => {
|
|
416
|
+
await this.client.authHeadersFor(gitUrl);
|
|
417
|
+
const refs = await isomorphic_git_1.default.listServerRefs({
|
|
418
|
+
http: this.http(),
|
|
419
|
+
url: gitUrl,
|
|
420
|
+
prefix: "refs/tags/",
|
|
421
|
+
peelTags: true,
|
|
422
|
+
});
|
|
423
|
+
const exact = refs.filter((r) => r.ref === `refs/tags/${tag}`);
|
|
424
|
+
const found = exact[0];
|
|
425
|
+
return found ? (found.peeled ?? found.oid) : null;
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
// ── internals ──────────────────────────────────────────────────────
|
|
429
|
+
// The commit a local tag names, peeling annotated tags (a tag may point at another tag) up to a cap.
|
|
430
|
+
async localTagCommit(dir, tag) {
|
|
431
|
+
let oid;
|
|
432
|
+
try {
|
|
433
|
+
oid = await isomorphic_git_1.default.resolveRef({ fs: nodeFs, dir, ref: `refs/tags/${tag}` });
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
return null;
|
|
437
|
+
}
|
|
438
|
+
for (let depth = 0; depth < MAX_TAG_DEPTH; depth++) {
|
|
439
|
+
try {
|
|
440
|
+
oid = (await isomorphic_git_1.default.readTag({ fs: nodeFs, dir, oid })).tag.object;
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
return oid;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return oid;
|
|
447
|
+
}
|
|
448
|
+
// Run one operation in the client's queue. isomorphic-git can swallow an error thrown from a
|
|
449
|
+
// response body (it treats it as the end of the stream), so a stall is remembered here and
|
|
450
|
+
// rethrown in place of whatever protocol error the half-read answer produced.
|
|
451
|
+
sequenced(task) {
|
|
452
|
+
return this.client.sequence(async () => {
|
|
453
|
+
this.stall = undefined;
|
|
454
|
+
let result;
|
|
455
|
+
try {
|
|
456
|
+
result = await task();
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
throw this.stall ?? this.typed(error);
|
|
460
|
+
}
|
|
461
|
+
this.throwIfStalled();
|
|
462
|
+
return result;
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
// isomorphic-git's own protocol errors (some quote a preview of the response body) become typed
|
|
466
|
+
// gateway errors that quote nothing; every other error passes through as it is.
|
|
467
|
+
typed(error) {
|
|
468
|
+
const code = codeOf(error);
|
|
469
|
+
if (error instanceof Err_1.Err.GatewayError || code === undefined || !PROTOCOL_ERROR_CODES.has(code)) {
|
|
470
|
+
return error;
|
|
471
|
+
}
|
|
472
|
+
return new Err_1.Err.GatewayUnexpectedResponseError(`The gateway's answer was not valid git smart HTTP (${code}).`, null, "invalid-git-response");
|
|
473
|
+
}
|
|
474
|
+
// The token as it was sent, for redacting server-supplied text. Asked of the same source each time.
|
|
475
|
+
async tokenText() {
|
|
476
|
+
const header = (await this.client.authHeadersFor(await this.client.origin()))[Http_1.Http.Headers.AUTHORIZATION];
|
|
477
|
+
return header?.replace(/^Bearer /, "");
|
|
478
|
+
}
|
|
479
|
+
throwIfStalled() {
|
|
480
|
+
if (this.stall) {
|
|
481
|
+
throw this.stall;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
requireClone(dir) {
|
|
485
|
+
if (!nodeFs.existsSync(path.join(dir, ".git"))) {
|
|
486
|
+
throw new Err_1.Err.GatewayWorkingCopyError(`${dir} is not a git clone.`, "not-a-clone");
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
async tracking(dir) {
|
|
490
|
+
this.requireClone(dir);
|
|
491
|
+
const branch = await isomorphic_git_1.default.currentBranch({ fs: nodeFs, dir });
|
|
492
|
+
if (!branch) {
|
|
493
|
+
throw new Err_1.Err.GatewayWorkingCopyError(`${dir} is on a detached head, not on a branch.`, "detached");
|
|
494
|
+
}
|
|
495
|
+
const head = await isomorphic_git_1.default.resolveRef({ fs: nodeFs, dir, ref: "HEAD" });
|
|
496
|
+
return { branch, head, remoteBranch: await this.upstreamOf(dir, branch) };
|
|
497
|
+
}
|
|
498
|
+
// The branch name `branch` tracks on the gateway remote, from the clone's own config.
|
|
499
|
+
async upstreamOf(dir, branch) {
|
|
500
|
+
const remote = await isomorphic_git_1.default.getConfig({ fs: nodeFs, dir, path: `branch.${branch}.remote` });
|
|
501
|
+
const merge = await isomorphic_git_1.default.getConfig({ fs: nodeFs, dir, path: `branch.${branch}.merge` });
|
|
502
|
+
if (remote !== REMOTE || typeof merge !== "string" || !merge.startsWith("refs/heads/")) {
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
return merge.slice("refs/heads/".length);
|
|
506
|
+
}
|
|
507
|
+
noUpstream(branch) {
|
|
508
|
+
return new Err_1.Err.GatewayWorkingCopyError(`${branch} tracks no branch on the gateway.`, "no-upstream");
|
|
509
|
+
}
|
|
510
|
+
dirtyError(branch, paths, kind) {
|
|
511
|
+
const sorted = [...new Set(paths)].sort();
|
|
512
|
+
const what = kind === "staged" ? "staged changes to" : "local changes to";
|
|
513
|
+
return new Err_1.Err.GatewayDirtyWorkingTreeError(`Updating ${branch} would overwrite ${what} ${sorted.length} file(s); nothing was changed.`, sorted);
|
|
514
|
+
}
|
|
515
|
+
// Paths whose index entry differs from HEAD (staged edits, additions and deletions).
|
|
516
|
+
async stagedPaths(dir) {
|
|
517
|
+
const rows = await isomorphic_git_1.default.statusMatrix({ fs: nodeFs, dir });
|
|
518
|
+
return rows
|
|
519
|
+
.filter(([, head, , stage]) => (head === 1 && stage !== 1) || (head === 0 && stage !== 0))
|
|
520
|
+
.map(([file]) => posix(file))
|
|
521
|
+
.sort();
|
|
522
|
+
}
|
|
523
|
+
// Whether the index and every file are exactly commit `oid`'s tree (nothing untracked either).
|
|
524
|
+
async matchesCommit(dir, oid) {
|
|
525
|
+
const rows = await isomorphic_git_1.default.statusMatrix({ fs: nodeFs, dir, ref: oid });
|
|
526
|
+
return rows.every(([, head, work, stage]) => head === 1 && work === 1 && stage === 1);
|
|
527
|
+
}
|
|
528
|
+
// Map isomorphic-git's "no such remote ref" failure to a GatewayWorkingCopyError (ref-not-found).
|
|
529
|
+
notFoundRef(error, ref) {
|
|
530
|
+
if (ref !== undefined && ["NotFoundError", "ResolveRefError"].includes(codeOf(error) ?? "")) {
|
|
531
|
+
return new Err_1.Err.GatewayWorkingCopyError(`The gateway's repository has no branch or tag named ${ref}.`, "ref-not-found");
|
|
532
|
+
}
|
|
533
|
+
return undefined;
|
|
534
|
+
}
|
|
535
|
+
async fetchBranch(dir, remoteBranch) {
|
|
536
|
+
await isomorphic_git_1.default.fetch({
|
|
537
|
+
fs: nodeFs,
|
|
538
|
+
http: this.http(),
|
|
539
|
+
dir,
|
|
540
|
+
remote: REMOTE,
|
|
541
|
+
remoteRef: `refs/heads/${remoteBranch}`,
|
|
542
|
+
singleBranch: true,
|
|
543
|
+
tags: false,
|
|
544
|
+
});
|
|
545
|
+
this.throwIfStalled();
|
|
546
|
+
}
|
|
547
|
+
async aheadBehind(dir, head, remoteBranch) {
|
|
548
|
+
const remoteRef = `refs/remotes/${REMOTE}/${remoteBranch}`;
|
|
549
|
+
let remoteHead;
|
|
550
|
+
try {
|
|
551
|
+
remoteHead = await isomorphic_git_1.default.resolveRef({ fs: nodeFs, dir, ref: remoteRef });
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
return { ahead: 0, behind: 0 };
|
|
555
|
+
}
|
|
556
|
+
const mine = new Set((await isomorphic_git_1.default.log({ fs: nodeFs, dir, ref: head })).map((c) => c.oid));
|
|
557
|
+
const theirs = new Set((await isomorphic_git_1.default.log({ fs: nodeFs, dir, ref: remoteHead })).map((c) => c.oid));
|
|
558
|
+
return {
|
|
559
|
+
ahead: [...mine].filter((oid) => !theirs.has(oid)).length,
|
|
560
|
+
behind: [...theirs].filter((oid) => !mine.has(oid)).length,
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
// Paths whose working copy or index differs from HEAD, plus untracked files (ignored ones excluded).
|
|
564
|
+
async dirtyPaths(dir) {
|
|
565
|
+
const rows = await isomorphic_git_1.default.statusMatrix({ fs: nodeFs, dir });
|
|
566
|
+
return rows
|
|
567
|
+
.filter(([, head, work, stage]) => !(head === 1 && work === 1 && stage === 1))
|
|
568
|
+
.map(([file]) => posix(file))
|
|
569
|
+
.sort();
|
|
570
|
+
}
|
|
571
|
+
// Files (not folders) whose content differs between two commits, including added and removed ones.
|
|
572
|
+
async changedBetween(dir, from, to) {
|
|
573
|
+
const changed = [];
|
|
574
|
+
await isomorphic_git_1.default.walk({
|
|
575
|
+
fs: nodeFs,
|
|
576
|
+
dir,
|
|
577
|
+
trees: [isomorphic_git_1.default.TREE({ ref: from }), isomorphic_git_1.default.TREE({ ref: to })],
|
|
578
|
+
map: async (file, entries) => {
|
|
579
|
+
if (file === ".") {
|
|
580
|
+
return undefined;
|
|
581
|
+
}
|
|
582
|
+
const [before, after] = entries;
|
|
583
|
+
const kinds = await Promise.all([before?.type(), after?.type()]);
|
|
584
|
+
if (kinds.includes("tree") && kinds.every((k) => k === undefined || k === "tree")) {
|
|
585
|
+
return undefined;
|
|
586
|
+
}
|
|
587
|
+
const [a, b] = await Promise.all([before?.oid(), after?.oid()]);
|
|
588
|
+
if (a !== b) {
|
|
589
|
+
changed.push(posix(file));
|
|
590
|
+
}
|
|
591
|
+
return undefined;
|
|
592
|
+
},
|
|
593
|
+
});
|
|
594
|
+
return changed;
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* The HTTP client isomorphic-git talks through: the injected `fetchFn` (so a consumer's proxy
|
|
598
|
+
* and TLS settings apply), the bearer header from {@link GatewayClient.authHeadersFor} on every
|
|
599
|
+
* request (so a URL off the gateway's origin throws before any bytes are sent), and redirects
|
|
600
|
+
* refused. A non-2xx answer becomes the typed gateway error right here.
|
|
601
|
+
* @lastreviewed null
|
|
602
|
+
*/
|
|
603
|
+
http() {
|
|
604
|
+
return {
|
|
605
|
+
request: async (req) => {
|
|
606
|
+
const auth = await this.client.authHeadersFor(req.url);
|
|
607
|
+
const secret = (auth[Http_1.Http.Headers.AUTHORIZATION] ?? "").replace(/^Bearer /, "");
|
|
608
|
+
const method = req.method ?? "GET";
|
|
609
|
+
const headers = { ...(req.headers ?? {}), ...auth };
|
|
610
|
+
const controller = new AbortController();
|
|
611
|
+
const abort = () => controller.abort();
|
|
612
|
+
if (req.signal) {
|
|
613
|
+
if (req.signal.aborted) {
|
|
614
|
+
abort();
|
|
615
|
+
}
|
|
616
|
+
else {
|
|
617
|
+
req.signal.addEventListener("abort", abort, { once: true });
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const init = { method, headers, redirect: "manual", signal: controller.signal };
|
|
621
|
+
if (req.body) {
|
|
622
|
+
const chunks = [];
|
|
623
|
+
for await (const chunk of req.body) {
|
|
624
|
+
chunks.push(Buffer.from(chunk));
|
|
625
|
+
}
|
|
626
|
+
init.body = Buffer.concat(chunks);
|
|
627
|
+
}
|
|
628
|
+
const url = new URL(req.url);
|
|
629
|
+
const what = `${method} ${url.pathname}${url.search}`;
|
|
630
|
+
const unavailable = (why) => new Err_1.Err.GatewayUnavailableError(`${what}: the gateway could not be reached: ${why}.`, null, null);
|
|
631
|
+
let response;
|
|
632
|
+
let timer;
|
|
633
|
+
try {
|
|
634
|
+
// Raced, not just aborted: the timeout must hold even for a fetch that ignores its signal.
|
|
635
|
+
const timedOut = new Promise((_resolve, reject) => {
|
|
636
|
+
timer = setTimeout(() => {
|
|
637
|
+
abort();
|
|
638
|
+
reject(unavailable(`no answer within ${this.firstByteTimeoutMs} ms`));
|
|
639
|
+
}, this.firstByteTimeoutMs);
|
|
640
|
+
timer.unref?.();
|
|
641
|
+
});
|
|
642
|
+
response = await Promise.race([this.ctx.fetchFn(url, init), timedOut]);
|
|
643
|
+
}
|
|
644
|
+
catch (error) {
|
|
645
|
+
if (error instanceof Err_1.Err.GatewayError) {
|
|
646
|
+
throw error;
|
|
647
|
+
}
|
|
648
|
+
throw unavailable(`the request failed (${(0, GatewayToken_1.redactToken)(error instanceof Error ? error.message : String(error), secret)})`);
|
|
649
|
+
}
|
|
650
|
+
finally {
|
|
651
|
+
clearTimeout(timer);
|
|
652
|
+
}
|
|
653
|
+
this.ctx.logger.debug(`gateway git ${what} -> ${response.status}`);
|
|
654
|
+
// Redirects are never followed ("manual" above); one is named, not mistaken for a network
|
|
655
|
+
// failure. Location is not quoted: it is server-supplied and names a place no token went.
|
|
656
|
+
if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
|
|
657
|
+
throw new Err_1.Err.GatewayUnexpectedResponseError(`${what}: the gateway answered with a redirect (${response.status}), which was not followed.`, response.status, "redirect-refused");
|
|
658
|
+
}
|
|
659
|
+
// Belt and braces after any URL resolution inside the fetch: the answer must come from the
|
|
660
|
+
// gateway's own origin.
|
|
661
|
+
if (response.url && new URL(response.url).origin !== (await this.client.origin())) {
|
|
662
|
+
throw new Err_1.Err.GatewayConfigError("A git response came from outside the gateway's origin; it was discarded.");
|
|
663
|
+
}
|
|
664
|
+
if (!response.ok) {
|
|
665
|
+
let text = "";
|
|
666
|
+
try {
|
|
667
|
+
text = await response.text();
|
|
668
|
+
}
|
|
669
|
+
catch {
|
|
670
|
+
// best-effort body only
|
|
671
|
+
}
|
|
672
|
+
throw (0, GatewayClient_1.gatewayErrorFor)(response.status, text, what, secret);
|
|
673
|
+
}
|
|
674
|
+
const responseHeaders = {};
|
|
675
|
+
response.headers.forEach((value, key) => {
|
|
676
|
+
responseHeaders[key] = value;
|
|
677
|
+
});
|
|
678
|
+
return {
|
|
679
|
+
url: req.url,
|
|
680
|
+
method,
|
|
681
|
+
headers: responseHeaders,
|
|
682
|
+
body: response.body
|
|
683
|
+
? streamOf(response.body, this.idleTimeoutMs, abort, (why) => {
|
|
684
|
+
this.stall = unavailable(why);
|
|
685
|
+
return this.stall;
|
|
686
|
+
})
|
|
687
|
+
: singleChunk(new Uint8Array()),
|
|
688
|
+
statusCode: response.status,
|
|
689
|
+
statusMessage: response.statusText,
|
|
690
|
+
};
|
|
691
|
+
},
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
exports.GatewayGit = GatewayGit;
|
|
696
|
+
// Adapt a web `ReadableStream` to the async iterator isomorphic-git reads. A read that yields
|
|
697
|
+
// nothing for `idleMs` aborts the request and throws what `stalled` builds.
|
|
698
|
+
async function* streamOf(stream, idleMs, abort, stalled) {
|
|
699
|
+
const reader = stream.getReader();
|
|
700
|
+
try {
|
|
701
|
+
for (;;) {
|
|
702
|
+
let timer;
|
|
703
|
+
const idle = new Promise((_resolve, reject) => {
|
|
704
|
+
timer = setTimeout(() => {
|
|
705
|
+
abort();
|
|
706
|
+
reject(stalled(`the response stalled for ${idleMs} ms`));
|
|
707
|
+
}, idleMs);
|
|
708
|
+
timer.unref?.();
|
|
709
|
+
});
|
|
710
|
+
let next;
|
|
711
|
+
try {
|
|
712
|
+
next = await Promise.race([reader.read(), idle]);
|
|
713
|
+
}
|
|
714
|
+
finally {
|
|
715
|
+
clearTimeout(timer);
|
|
716
|
+
}
|
|
717
|
+
if (next.done) {
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
yield next.value;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
finally {
|
|
724
|
+
reader.cancel().catch(() => undefined);
|
|
725
|
+
reader.releaseLock();
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
async function* singleChunk(chunk) {
|
|
729
|
+
yield chunk;
|
|
730
|
+
}
|
|
731
|
+
//# sourceMappingURL=GatewayGit.js.map
|