@starko-one/sdk 0.0.0-stage → 0.1.0-beta.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/CHANGELOG.md +124 -0
- package/LICENSE +17 -0
- package/NOTICE +58 -0
- package/README.md +81 -2
- package/dist/api-B5IHeINe.d.ts +558 -0
- package/dist/api-DR4HazCu.d.cts +558 -0
- package/dist/browser/index.cjs +168 -0
- package/dist/browser/index.d.cts +131 -0
- package/dist/browser/index.d.ts +131 -0
- package/dist/browser/index.js +7 -0
- package/dist/build/rollup.cjs +22 -0
- package/dist/build/rollup.d.cts +34 -0
- package/dist/build/rollup.d.ts +34 -0
- package/dist/build/rollup.js +3 -0
- package/dist/build/vite.cjs +51 -0
- package/dist/build/vite.d.cts +23 -0
- package/dist/build/vite.d.ts +23 -0
- package/dist/build/vite.js +46 -0
- package/dist/build/webpack.cjs +18 -0
- package/dist/build/webpack.d.cts +39 -0
- package/dist/build/webpack.d.ts +39 -0
- package/dist/build/webpack.js +3 -0
- package/dist/chunk-7HYGODU6.cjs +583 -0
- package/dist/chunk-A5M4NOVT.js +413 -0
- package/dist/chunk-A7MYYWMP.cjs +15 -0
- package/dist/chunk-BAQA47FM.js +1113 -0
- package/dist/chunk-CM7HM6CC.js +563 -0
- package/dist/chunk-DFYNIWUN.js +608 -0
- package/dist/chunk-DMVVCGKO.cjs +96 -0
- package/dist/chunk-FARGXYJ4.cjs +56 -0
- package/dist/chunk-G3MYIAX2.js +1226 -0
- package/dist/chunk-G4NAVZQ4.js +249 -0
- package/dist/chunk-GH7RYPKS.js +96 -0
- package/dist/chunk-HADYYQNL.cjs +134 -0
- package/dist/chunk-HOQPAB4X.js +178 -0
- package/dist/chunk-J5RU73SW.js +214 -0
- package/dist/chunk-JNAJ3YZB.cjs +223 -0
- package/dist/chunk-KN7H22EQ.cjs +659 -0
- package/dist/chunk-LDQ4I7FZ.cjs +1151 -0
- package/dist/chunk-NPGESRVQ.js +1212 -0
- package/dist/chunk-OPWM5V7A.cjs +258 -0
- package/dist/chunk-PYYWPIFL.cjs +1230 -0
- package/dist/chunk-R7JLZ4WO.cjs +115 -0
- package/dist/chunk-SC6VQSES.js +213 -0
- package/dist/chunk-TPSJGLR3.cjs +220 -0
- package/dist/chunk-UKBY6HPC.js +131 -0
- package/dist/chunk-VRSEHRBX.cjs +185 -0
- package/dist/chunk-X74AONZA.js +90 -0
- package/dist/chunk-XW3I5CJN.js +12 -0
- package/dist/chunk-XW56FKKJ.js +53 -0
- package/dist/chunk-Z3G5SW7R.cjs +1251 -0
- package/dist/chunk-ZVMAN7OO.cjs +431 -0
- package/dist/cli/index.cjs +1487 -0
- package/dist/common-ARWXbeS3.d.ts +36 -0
- package/dist/common-CwIFh2hK.d.cts +36 -0
- package/dist/dedupe-eHBIfUUD.d.cts +13 -0
- package/dist/dedupe-fw8aNtt4.d.ts +13 -0
- package/dist/handler-DTZ4Rzcf.d.ts +82 -0
- package/dist/handler-_00lctTI.d.cts +82 -0
- package/dist/index.cjs +277 -0
- package/dist/index.d.cts +187 -0
- package/dist/index.d.ts +187 -0
- package/dist/index.js +4 -0
- package/dist/next/client.cjs +113 -0
- package/dist/next/client.d.cts +26 -0
- package/dist/next/client.d.ts +26 -0
- package/dist/next/client.js +41 -0
- package/dist/next/config.cjs +275 -0
- package/dist/next/config.d.cts +193 -0
- package/dist/next/config.d.ts +193 -0
- package/dist/next/config.js +261 -0
- package/dist/next/index.cjs +148 -0
- package/dist/next/index.d.cts +32 -0
- package/dist/next/index.d.ts +32 -0
- package/dist/next/index.js +59 -0
- package/dist/node/index.cjs +257 -0
- package/dist/node/index.d.cts +145 -0
- package/dist/node/index.d.ts +145 -0
- package/dist/node/index.js +83 -0
- package/dist/options-0BhybO54.d.cts +47 -0
- package/dist/options-0BhybO54.d.ts +47 -0
- package/dist/react/index.cjs +107 -0
- package/dist/react/index.d.cts +84 -0
- package/dist/react/index.d.ts +84 -0
- package/dist/react/index.js +103 -0
- package/dist/scope-Bvh45bOf.d.cts +404 -0
- package/dist/scope-Bvh45bOf.d.ts +404 -0
- package/dist/server-edge-BPOGA3GH.cjs +51 -0
- package/dist/server-edge-GYKAJREU.js +48 -0
- package/dist/server-node-HYK2OB2J.js +24 -0
- package/dist/server-node-J2DBAHDV.cjs +27 -0
- package/dist/session-C_WzbEN2.d.cts +4 -0
- package/dist/session-C_WzbEN2.d.ts +4 -0
- package/dist/session-propagation-B7REA7uy.d.cts +30 -0
- package/dist/session-propagation-BnJjKJbR.d.ts +30 -0
- package/dist/starko.min.js +6 -0
- package/docs/browser.md +381 -0
- package/docs/configuration.md +269 -0
- package/docs/nextjs.md +312 -0
- package/docs/node.md +376 -0
- package/docs/other-backends.md +232 -0
- package/docs/privacy.md +112 -0
- package/docs/react.md +187 -0
- package/docs/source-maps.md +332 -0
- package/docs/troubleshooting.md +171 -0
- package/docs/widget.md +84 -0
- package/docs/wire-format.md +367 -0
- package/package.json +98 -4
|
@@ -0,0 +1,1226 @@
|
|
|
1
|
+
import { DEBUG_ID_GLOBAL, DEFAULT_HOST, DEBUG_ID_NAMESPACE, DEBUG_ID_COMMENT, RELEASE_GLOBAL, LIMITS, SOURCEMAP_MAX_BYTES, PATHS, SOURCEMAP_PART_BYTES, SOURCEMAP_MAX_CHUNKS_PER_CHECK, version, SOURCEMAP_MAX_PARTS } from './chunk-GH7RYPKS.js';
|
|
2
|
+
import { createHash, randomBytes } from 'crypto';
|
|
3
|
+
import { execFileSync } from 'child_process';
|
|
4
|
+
import { constants, promises } from 'fs';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import { promisify } from 'util';
|
|
7
|
+
import { gzip as gzip$1 } from 'zlib';
|
|
8
|
+
|
|
9
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
10
|
+
function isDebugId(value) {
|
|
11
|
+
return typeof value === "string" && UUID_RE.test(value);
|
|
12
|
+
}
|
|
13
|
+
function createDebugId(code) {
|
|
14
|
+
const namespace = Buffer.from(DEBUG_ID_NAMESPACE.replace(/-/g, ""), "hex");
|
|
15
|
+
const digest = createHash("sha1").update(namespace).update(code, "utf8").digest();
|
|
16
|
+
digest[6] = digest[6] & 15 | 80;
|
|
17
|
+
digest[8] = digest[8] & 63 | 128;
|
|
18
|
+
const hex = digest.subarray(0, 16).toString("hex");
|
|
19
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
20
|
+
}
|
|
21
|
+
function debugIdComment(debugId) {
|
|
22
|
+
return `${DEBUG_ID_COMMENT}${debugId}`;
|
|
23
|
+
}
|
|
24
|
+
var COMMENT_LINE_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t\r]*$/;
|
|
25
|
+
var MAX_TRAILING_LINES = 16;
|
|
26
|
+
function findDebugId(code) {
|
|
27
|
+
let end = code.length;
|
|
28
|
+
for (let i = 0; i < MAX_TRAILING_LINES && end > 0; i++) {
|
|
29
|
+
const start = code.lastIndexOf("\n", end - 1) + 1;
|
|
30
|
+
const line = code.slice(start, end).trim();
|
|
31
|
+
end = start - 1;
|
|
32
|
+
if (line === "") continue;
|
|
33
|
+
if (!line.startsWith("//")) return void 0;
|
|
34
|
+
const match = COMMENT_LINE_RE.exec(line);
|
|
35
|
+
if (match && isDebugId(match[1])) return match[1].toLowerCase();
|
|
36
|
+
}
|
|
37
|
+
return void 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/build/shared/prologue.ts
|
|
41
|
+
function findInsertionOffset(code) {
|
|
42
|
+
let pos = 0;
|
|
43
|
+
if (code.charCodeAt(0) === 65279) pos = 1;
|
|
44
|
+
if (code.startsWith("#!", pos)) {
|
|
45
|
+
const nl = code.indexOf("\n", pos);
|
|
46
|
+
if (nl === -1) return code.length;
|
|
47
|
+
pos = nl + 1;
|
|
48
|
+
}
|
|
49
|
+
let safe = pos;
|
|
50
|
+
for (; ; ) {
|
|
51
|
+
const trivia = skipTrivia(code, pos);
|
|
52
|
+
if (trivia === void 0) return safe;
|
|
53
|
+
pos = trivia.end;
|
|
54
|
+
const ch = code[pos];
|
|
55
|
+
if (ch !== '"' && ch !== "'") return pos;
|
|
56
|
+
const end = scanString(code, pos);
|
|
57
|
+
if (end === void 0) return safe;
|
|
58
|
+
const after = skipTrivia(code, end);
|
|
59
|
+
if (after === void 0) return safe;
|
|
60
|
+
if (code[after.end] === ";") {
|
|
61
|
+
pos = after.end + 1;
|
|
62
|
+
safe = pos;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (after.end >= code.length) {
|
|
66
|
+
return code.length;
|
|
67
|
+
}
|
|
68
|
+
if (after.newline && !continuesExpression(code, after.end)) {
|
|
69
|
+
pos = after.end;
|
|
70
|
+
safe = pos;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
return pos;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
var LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
|
|
77
|
+
function skipTrivia(code, from) {
|
|
78
|
+
let pos = from;
|
|
79
|
+
let newline = false;
|
|
80
|
+
while (pos < code.length) {
|
|
81
|
+
const ch = code[pos];
|
|
82
|
+
if (LINE_TERMINATOR.test(ch)) {
|
|
83
|
+
newline = true;
|
|
84
|
+
pos++;
|
|
85
|
+
} else if (/\s/.test(ch)) {
|
|
86
|
+
pos++;
|
|
87
|
+
} else if (ch === "/" && code[pos + 1] === "/") {
|
|
88
|
+
const nl = code.slice(pos).search(LINE_TERMINATOR);
|
|
89
|
+
if (nl === -1) return { end: code.length, newline };
|
|
90
|
+
pos += nl;
|
|
91
|
+
} else if (ch === "/" && code[pos + 1] === "*") {
|
|
92
|
+
const close = code.indexOf("*/", pos + 2);
|
|
93
|
+
if (close === -1) return void 0;
|
|
94
|
+
if (LINE_TERMINATOR.test(code.slice(pos + 2, close))) newline = true;
|
|
95
|
+
pos = close + 2;
|
|
96
|
+
} else {
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { end: pos, newline };
|
|
101
|
+
}
|
|
102
|
+
function scanString(code, start) {
|
|
103
|
+
const quote = code[start];
|
|
104
|
+
let pos = start + 1;
|
|
105
|
+
while (pos < code.length) {
|
|
106
|
+
const ch = code[pos];
|
|
107
|
+
if (ch === quote) return pos + 1;
|
|
108
|
+
if (ch === "\\") {
|
|
109
|
+
pos += code[pos + 1] === "\r" && code[pos + 2] === "\n" ? 3 : 2;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (ch === "\n" || ch === "\r") return void 0;
|
|
113
|
+
pos++;
|
|
114
|
+
}
|
|
115
|
+
return void 0;
|
|
116
|
+
}
|
|
117
|
+
function continuesExpression(code, pos) {
|
|
118
|
+
const rest = code.slice(pos, pos + 12);
|
|
119
|
+
if (/^(?:\+\+|--)/.test(rest)) return false;
|
|
120
|
+
return /^(?:[.,([?:<>=&|^%*/`+\-~]|!=|in(?![\w$])|instanceof(?![\w$]))/.test(rest);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/build/shared/snippet.ts
|
|
124
|
+
function jsStringLiteral(value) {
|
|
125
|
+
return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/</g, "\\u003c");
|
|
126
|
+
}
|
|
127
|
+
function createSnippet(debugId, release) {
|
|
128
|
+
const id = jsStringLiteral(debugId);
|
|
129
|
+
const setRelease = release === void 0 ? "" : `g.${RELEASE_GLOBAL}||(g.${RELEASE_GLOBAL}=${jsStringLiteral(release)});`;
|
|
130
|
+
return ';!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{};' + setRelease + `var s=(new Error).stack;s&&((g.${DEBUG_ID_GLOBAL}=g.${DEBUG_ID_GLOBAL}||{})[s]=${id})}catch(e){}}();`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// src/build/shared/vlq.ts
|
|
134
|
+
var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
135
|
+
var INDEX = new Int8Array(128).fill(-1);
|
|
136
|
+
for (let i = 0; i < CHARS.length; i++) INDEX[CHARS.charCodeAt(i)] = i;
|
|
137
|
+
function decodeMappings(mappings) {
|
|
138
|
+
const lines = [];
|
|
139
|
+
let line = [];
|
|
140
|
+
const state = [0, 0, 0, 0, 0];
|
|
141
|
+
const values = [];
|
|
142
|
+
let value = 0;
|
|
143
|
+
let shift = 0;
|
|
144
|
+
const endSegment = () => {
|
|
145
|
+
if (values.length === 0) return;
|
|
146
|
+
if (values.length !== 1 && values.length !== 4 && values.length !== 5) {
|
|
147
|
+
throw new Error(`Invalid source map segment with ${values.length} fields`);
|
|
148
|
+
}
|
|
149
|
+
state[0] += values[0];
|
|
150
|
+
if (values.length === 1) {
|
|
151
|
+
line.push([state[0]]);
|
|
152
|
+
} else {
|
|
153
|
+
state[1] += values[1];
|
|
154
|
+
state[2] += values[2];
|
|
155
|
+
state[3] += values[3];
|
|
156
|
+
if (values.length === 5) {
|
|
157
|
+
state[4] += values[4];
|
|
158
|
+
line.push([state[0], state[1], state[2], state[3], state[4]]);
|
|
159
|
+
} else {
|
|
160
|
+
line.push([state[0], state[1], state[2], state[3]]);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
values.length = 0;
|
|
164
|
+
};
|
|
165
|
+
for (let i = 0; i < mappings.length; i++) {
|
|
166
|
+
const code = mappings.charCodeAt(i);
|
|
167
|
+
if (code === 44) {
|
|
168
|
+
endSegment();
|
|
169
|
+
} else if (code === 59) {
|
|
170
|
+
endSegment();
|
|
171
|
+
lines.push(line);
|
|
172
|
+
line = [];
|
|
173
|
+
state[0] = 0;
|
|
174
|
+
} else {
|
|
175
|
+
const digit = code < 128 ? INDEX[code] : -1;
|
|
176
|
+
if (digit === -1) throw new Error(`Invalid base64 VLQ character ${JSON.stringify(mappings[i])}`);
|
|
177
|
+
value += (digit & 31) * 2 ** shift;
|
|
178
|
+
if (digit & 32) {
|
|
179
|
+
shift += 5;
|
|
180
|
+
} else {
|
|
181
|
+
const negative = value % 2 === 1;
|
|
182
|
+
const magnitude = Math.floor(value / 2);
|
|
183
|
+
values.push(negative ? -magnitude || 0 : magnitude);
|
|
184
|
+
value = 0;
|
|
185
|
+
shift = 0;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
endSegment();
|
|
190
|
+
lines.push(line);
|
|
191
|
+
return lines;
|
|
192
|
+
}
|
|
193
|
+
function encodeValue(n) {
|
|
194
|
+
let vlq = n < 0 ? -n * 2 + 1 : n * 2;
|
|
195
|
+
let out = "";
|
|
196
|
+
do {
|
|
197
|
+
let digit = vlq % 32;
|
|
198
|
+
vlq = Math.floor(vlq / 32);
|
|
199
|
+
if (vlq > 0) digit |= 32;
|
|
200
|
+
out += CHARS[digit];
|
|
201
|
+
} while (vlq > 0);
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
function encodeMappings(lines) {
|
|
205
|
+
const state = [0, 0, 0, 0, 0];
|
|
206
|
+
let out = "";
|
|
207
|
+
for (let l = 0; l < lines.length; l++) {
|
|
208
|
+
if (l > 0) out += ";";
|
|
209
|
+
state[0] = 0;
|
|
210
|
+
const segments = lines[l];
|
|
211
|
+
for (let s = 0; s < segments.length; s++) {
|
|
212
|
+
const seg = segments[s];
|
|
213
|
+
if (s > 0) out += ",";
|
|
214
|
+
out += encodeValue(seg[0] - state[0]);
|
|
215
|
+
state[0] = seg[0];
|
|
216
|
+
if (seg.length === 1) continue;
|
|
217
|
+
for (let f = 1; f < seg.length; f++) {
|
|
218
|
+
out += encodeValue(seg[f] - state[f]);
|
|
219
|
+
state[f] = seg[f];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return out;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// src/build/shared/inject.ts
|
|
227
|
+
var SOURCE_MAPPING_URL_LINE = /^[ \t]*\/\/[#@][ \t]+sourceMappingURL=/;
|
|
228
|
+
function findSourceMappingUrlLine(code) {
|
|
229
|
+
let end = code.length;
|
|
230
|
+
while (end > 0) {
|
|
231
|
+
const start = code.lastIndexOf("\n", end - 1) + 1;
|
|
232
|
+
const line = code.slice(start, end);
|
|
233
|
+
if (line.trim() === "") {
|
|
234
|
+
end = start - 1;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
return SOURCE_MAPPING_URL_LINE.test(line) ? start : void 0;
|
|
238
|
+
}
|
|
239
|
+
return void 0;
|
|
240
|
+
}
|
|
241
|
+
function planInjection(code, options = {}) {
|
|
242
|
+
const debugId = options.debugId ?? createDebugId(code);
|
|
243
|
+
const urlLine = findSourceMappingUrlLine(code);
|
|
244
|
+
const comment = urlLine !== void 0 ? { offset: urlLine, text: `${debugIdComment(debugId)}
|
|
245
|
+
` } : {
|
|
246
|
+
offset: code.length,
|
|
247
|
+
text: `${code.length === 0 || code.endsWith("\n") ? "" : "\n"}${debugIdComment(debugId)}
|
|
248
|
+
`
|
|
249
|
+
};
|
|
250
|
+
const offset = Math.min(findInsertionOffset(code), comment.offset);
|
|
251
|
+
const atLineStart = offset === 0 || code[offset - 1] === "\n";
|
|
252
|
+
const snippetText = createSnippet(debugId, options.release);
|
|
253
|
+
const snippet = { offset, text: atLineStart ? `${snippetText}
|
|
254
|
+
` : snippetText };
|
|
255
|
+
return { debugId, snippet, comment };
|
|
256
|
+
}
|
|
257
|
+
function applyToCode(code, insertions) {
|
|
258
|
+
const sorted = insertions.map((ins, index) => ({ ins, index })).sort((a, b) => a.ins.offset - b.ins.offset || a.index - b.index);
|
|
259
|
+
let out = "";
|
|
260
|
+
let at = 0;
|
|
261
|
+
for (const { ins } of sorted) {
|
|
262
|
+
out += code.slice(at, ins.offset) + ins.text;
|
|
263
|
+
at = ins.offset;
|
|
264
|
+
}
|
|
265
|
+
return out + code.slice(at);
|
|
266
|
+
}
|
|
267
|
+
function lineAndColumn(code, offset) {
|
|
268
|
+
let line = 0;
|
|
269
|
+
let lineStart = 0;
|
|
270
|
+
for (let i = code.indexOf("\n"); i !== -1 && i < offset; i = code.indexOf("\n", i + 1)) {
|
|
271
|
+
line++;
|
|
272
|
+
lineStart = i + 1;
|
|
273
|
+
}
|
|
274
|
+
return { line, column: offset - lineStart };
|
|
275
|
+
}
|
|
276
|
+
function shiftSegments(lines, line, column, text) {
|
|
277
|
+
while (lines.length <= line) lines.push([]);
|
|
278
|
+
const segments = lines[line];
|
|
279
|
+
const newlines = text.split("\n").length - 1;
|
|
280
|
+
if (newlines === 0) {
|
|
281
|
+
for (const seg of segments) if (seg[0] >= column) seg[0] += text.length;
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const lastLineLength = text.length - text.lastIndexOf("\n") - 1;
|
|
285
|
+
const before2 = [];
|
|
286
|
+
const after = [];
|
|
287
|
+
for (const seg of segments) {
|
|
288
|
+
if (seg[0] >= column) {
|
|
289
|
+
seg[0] = seg[0] - column + lastLineLength;
|
|
290
|
+
after.push(seg);
|
|
291
|
+
} else {
|
|
292
|
+
before2.push(seg);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const inserted = Array.from({ length: newlines - 1 }, () => []);
|
|
296
|
+
lines.splice(line, 1, before2, ...inserted, after);
|
|
297
|
+
}
|
|
298
|
+
var before = (a, line, column) => a.line < line || a.line === line && a.column < column;
|
|
299
|
+
function movedPosition(p, at) {
|
|
300
|
+
const newlines = at.text.split("\n").length - 1;
|
|
301
|
+
if (newlines === 0) return p.line === at.line ? { line: p.line, column: p.column + at.text.length } : p;
|
|
302
|
+
const lastLineLength = at.text.length - at.text.lastIndexOf("\n") - 1;
|
|
303
|
+
return { line: p.line + newlines, column: p.line === at.line ? p.column - at.column + lastLineLength : p.column };
|
|
304
|
+
}
|
|
305
|
+
function shiftAt(map, ordered) {
|
|
306
|
+
if (Array.isArray(map.sections)) {
|
|
307
|
+
const sections = map.sections.map((sec) => ({ ...sec, offset: { line: Number(sec.offset?.line) || 0, column: Number(sec.offset?.column) || 0 } }));
|
|
308
|
+
for (const at of ordered) {
|
|
309
|
+
let inside = -1;
|
|
310
|
+
for (let i = 0; i < sections.length; i++) if (before(sections[i].offset, at.line, at.column)) inside = i;
|
|
311
|
+
for (let i = 0; i < sections.length; i++) {
|
|
312
|
+
const sec = sections[i];
|
|
313
|
+
if (!before(sec.offset, at.line, at.column)) sec.offset = movedPosition(sec.offset, at);
|
|
314
|
+
}
|
|
315
|
+
if (inside >= 0) {
|
|
316
|
+
const sec = sections[inside];
|
|
317
|
+
if (!sec.map || typeof sec.map !== "object") throw new Error("Index source map sections with a `url` instead of a `map` are not supported");
|
|
318
|
+
const rel = { line: at.line - sec.offset.line, column: at.line === sec.offset.line ? at.column - sec.offset.column : at.column, text: at.text };
|
|
319
|
+
sec.map = shiftAt(sec.map, [rel]);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return { ...map, sections };
|
|
323
|
+
}
|
|
324
|
+
const lines = decodeMappings(map.mappings ?? "");
|
|
325
|
+
for (const at of ordered) shiftSegments(lines, at.line, at.column, at.text);
|
|
326
|
+
return { ...map, mappings: encodeMappings(lines) };
|
|
327
|
+
}
|
|
328
|
+
function shiftSourceMap(map, code, insertions) {
|
|
329
|
+
const ordered = insertions.map((ins, index) => ({ ins, index })).sort((a, b) => b.ins.offset - a.ins.offset || b.index - a.index).map(({ ins }) => ({ ...lineAndColumn(code, ins.offset), text: ins.text }));
|
|
330
|
+
return shiftAt(map, ordered);
|
|
331
|
+
}
|
|
332
|
+
function hasStarkoRegistration(code, debugId) {
|
|
333
|
+
const id = debugId.toLowerCase();
|
|
334
|
+
return code.includes(`(g.${DEBUG_ID_GLOBAL}=g.${DEBUG_ID_GLOBAL}||{})[s]=${jsStringLiteral(id)}`);
|
|
335
|
+
}
|
|
336
|
+
function hasNativeRegistration(code, debugId) {
|
|
337
|
+
const head = code.slice(0, 4096);
|
|
338
|
+
const id = debugId.toLowerCase();
|
|
339
|
+
if (!head.toLowerCase().includes(id)) return false;
|
|
340
|
+
if (!/_(?:sentryD|d)ebugIds\b/.test(head)) return false;
|
|
341
|
+
return new RegExp(`\\]\\s*=\\s*["']${id}["']`, "i").test(head);
|
|
342
|
+
}
|
|
343
|
+
function injectDebugId(code, map, options = {}) {
|
|
344
|
+
const existing = findDebugId(code);
|
|
345
|
+
if (existing) {
|
|
346
|
+
const withId = (m) => m.debugId === existing ? m : { ...m, debugId: existing };
|
|
347
|
+
if (hasStarkoRegistration(code, existing) || options.keepNativelyRegistered && hasNativeRegistration(code, existing)) {
|
|
348
|
+
return { code, map: map && withId(map), debugId: existing, injected: false, kind: "none" };
|
|
349
|
+
}
|
|
350
|
+
const plan2 = planInjection(code, { ...options, debugId: existing });
|
|
351
|
+
const newMap2 = map ? withId(shiftSourceMap(map, code, [plan2.snippet])) : void 0;
|
|
352
|
+
return { code: applyToCode(code, [plan2.snippet]), map: newMap2, debugId: existing, injected: true, kind: "snippet" };
|
|
353
|
+
}
|
|
354
|
+
const plan = planInjection(code, options);
|
|
355
|
+
const insertions = [plan.snippet, plan.comment];
|
|
356
|
+
const newMap = map ? { ...shiftSourceMap(map, code, insertions), debugId: plan.debugId } : void 0;
|
|
357
|
+
return { code: applyToCode(code, insertions), map: newMap, debugId: plan.debugId, injected: true, kind: "full" };
|
|
358
|
+
}
|
|
359
|
+
var COMMIT_ENV_VARS = [
|
|
360
|
+
"VERCEL_GIT_COMMIT_SHA",
|
|
361
|
+
"GITHUB_SHA",
|
|
362
|
+
"CI_COMMIT_SHA",
|
|
363
|
+
// GitLab
|
|
364
|
+
"BITBUCKET_COMMIT",
|
|
365
|
+
"CIRCLE_SHA1",
|
|
366
|
+
"CF_PAGES_COMMIT_SHA",
|
|
367
|
+
"RENDER_GIT_COMMIT",
|
|
368
|
+
"RAILWAY_GIT_COMMIT_SHA",
|
|
369
|
+
"COMMIT_REF",
|
|
370
|
+
// Netlify
|
|
371
|
+
"BUILDKITE_COMMIT",
|
|
372
|
+
"DRONE_COMMIT_SHA",
|
|
373
|
+
"TRAVIS_COMMIT",
|
|
374
|
+
"BUILD_SOURCEVERSION",
|
|
375
|
+
// Azure Pipelines
|
|
376
|
+
"CODEBUILD_RESOLVED_SOURCE_VERSION",
|
|
377
|
+
"HEROKU_SLUG_COMMIT",
|
|
378
|
+
"SOURCE_VERSION",
|
|
379
|
+
// Heroku
|
|
380
|
+
"GIT_COMMIT"
|
|
381
|
+
// Jenkins
|
|
382
|
+
];
|
|
383
|
+
var BRANCH_ENV_VARS = [
|
|
384
|
+
"VERCEL_GIT_COMMIT_REF",
|
|
385
|
+
"GITHUB_HEAD_REF",
|
|
386
|
+
"GITHUB_REF_NAME",
|
|
387
|
+
"CI_COMMIT_REF_NAME",
|
|
388
|
+
"BITBUCKET_BRANCH",
|
|
389
|
+
"CIRCLE_BRANCH",
|
|
390
|
+
"CF_PAGES_BRANCH",
|
|
391
|
+
"RENDER_GIT_BRANCH",
|
|
392
|
+
"RAILWAY_GIT_BRANCH",
|
|
393
|
+
"BRANCH",
|
|
394
|
+
// Netlify
|
|
395
|
+
"BUILDKITE_BRANCH",
|
|
396
|
+
"DRONE_BRANCH",
|
|
397
|
+
"TRAVIS_BRANCH",
|
|
398
|
+
"BUILD_SOURCEBRANCHNAME",
|
|
399
|
+
"GIT_BRANCH"
|
|
400
|
+
];
|
|
401
|
+
function clean(value) {
|
|
402
|
+
const trimmed = value?.trim();
|
|
403
|
+
return trimmed ? trimmed : void 0;
|
|
404
|
+
}
|
|
405
|
+
function firstEnv(env, names) {
|
|
406
|
+
for (const name of names) {
|
|
407
|
+
const value = clean(env[name]);
|
|
408
|
+
if (value) return value;
|
|
409
|
+
}
|
|
410
|
+
return void 0;
|
|
411
|
+
}
|
|
412
|
+
function git(args, cwd) {
|
|
413
|
+
try {
|
|
414
|
+
return clean(
|
|
415
|
+
execFileSync("git", args, {
|
|
416
|
+
cwd,
|
|
417
|
+
encoding: "utf8",
|
|
418
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
419
|
+
timeout: 5e3,
|
|
420
|
+
windowsHide: true
|
|
421
|
+
})
|
|
422
|
+
);
|
|
423
|
+
} catch {
|
|
424
|
+
return void 0;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
function resolveCommit(options = {}) {
|
|
428
|
+
const env = options.env ?? process.env;
|
|
429
|
+
return firstEnv(env, COMMIT_ENV_VARS) ?? (options.useGit === false ? void 0 : git(["rev-parse", "HEAD"], options.cwd));
|
|
430
|
+
}
|
|
431
|
+
function resolveRelease(explicit, options = {}) {
|
|
432
|
+
const env = options.env ?? process.env;
|
|
433
|
+
const release = clean(explicit) ?? clean(env.STARKO_RELEASE) ?? resolveCommit(options);
|
|
434
|
+
return release === void 0 ? void 0 : release.slice(0, LIMITS.MAX_RELEASE);
|
|
435
|
+
}
|
|
436
|
+
function resolveReleaseInfo(explicit, options = {}) {
|
|
437
|
+
const version2 = resolveRelease(explicit, options);
|
|
438
|
+
if (version2 === void 0) return void 0;
|
|
439
|
+
const env = options.env ?? process.env;
|
|
440
|
+
const commit = resolveCommit(options);
|
|
441
|
+
let branch = firstEnv(env, BRANCH_ENV_VARS);
|
|
442
|
+
if (!branch && options.useGit !== false) {
|
|
443
|
+
const head = git(["rev-parse", "--abbrev-ref", "HEAD"], options.cwd);
|
|
444
|
+
if (head && head !== "HEAD") branch = head;
|
|
445
|
+
}
|
|
446
|
+
const info = { version: version2 };
|
|
447
|
+
if (commit) info.commit = commit;
|
|
448
|
+
if (branch) info.branch = branch;
|
|
449
|
+
return info;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// src/build/shared/options.ts
|
|
453
|
+
var DEFAULT_UPLOAD_TIMEOUT_MS = 18e4;
|
|
454
|
+
function shouldDeleteSourcemaps(owner, options) {
|
|
455
|
+
if (owner === "starko") return true;
|
|
456
|
+
return options.deleteSourcemapsAfterUpload === true && !options.dryRun;
|
|
457
|
+
}
|
|
458
|
+
var NO_API_KEY_MESSAGE = "no API key (set apiKey or STARKO_API_KEY): source maps are not switched on, injected or uploaded, and the build output is left as it is";
|
|
459
|
+
function errorMessage(error) {
|
|
460
|
+
if (error instanceof Error) return error.message;
|
|
461
|
+
try {
|
|
462
|
+
return String(error);
|
|
463
|
+
} catch {
|
|
464
|
+
return "unknown error";
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function redact(message, secrets) {
|
|
468
|
+
let out = message;
|
|
469
|
+
for (const secret of secrets) {
|
|
470
|
+
if (secret && secret.length >= 4) out = out.split(secret).join("[redacted]");
|
|
471
|
+
}
|
|
472
|
+
return out;
|
|
473
|
+
}
|
|
474
|
+
function createLogger(options = {}) {
|
|
475
|
+
const prefix = options.prefix ?? "[starko]";
|
|
476
|
+
const secrets = options.secrets ?? [];
|
|
477
|
+
const sink = options.sink ?? ((level, line) => level === "info" ? console.log(line) : level === "warn" ? console.warn(line) : console.error(line));
|
|
478
|
+
const write = (level) => (message) => {
|
|
479
|
+
if (!options.silent) sink(level, prefix ? `${prefix} ${redact(message, secrets)}` : redact(message, secrets));
|
|
480
|
+
};
|
|
481
|
+
return { info: write("info"), warn: write("warn"), error: write("error") };
|
|
482
|
+
}
|
|
483
|
+
function resolveConnection(options, env = process.env) {
|
|
484
|
+
const apiKey = options.apiKey?.trim() || env.STARKO_API_KEY?.trim() || void 0;
|
|
485
|
+
const host = (options.host?.trim() || env.STARKO_HOST?.trim() || DEFAULT_HOST).replace(/\/+$/, "");
|
|
486
|
+
return { apiKey, host };
|
|
487
|
+
}
|
|
488
|
+
function escapeRegExp(text) {
|
|
489
|
+
return text.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
490
|
+
}
|
|
491
|
+
function globToRegExp(glob) {
|
|
492
|
+
const pattern = glob.includes("/") ? glob.replace(/^\.\//, "") : `**/${glob}`;
|
|
493
|
+
let re = "";
|
|
494
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
495
|
+
const ch = pattern[i];
|
|
496
|
+
if (ch === "*") {
|
|
497
|
+
if (pattern[i + 1] === "*") {
|
|
498
|
+
const slash = pattern[i + 2] === "/";
|
|
499
|
+
re += slash ? "(?:.*/)?" : ".*";
|
|
500
|
+
i += slash ? 2 : 1;
|
|
501
|
+
} else {
|
|
502
|
+
re += "[^/]*";
|
|
503
|
+
}
|
|
504
|
+
} else if (ch === "?") {
|
|
505
|
+
re += "[^/]";
|
|
506
|
+
} else {
|
|
507
|
+
re += escapeRegExp(ch);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return new RegExp(`^${re}$`);
|
|
511
|
+
}
|
|
512
|
+
var JS_FILE = /\.(?:m|c)?js$/;
|
|
513
|
+
var DEFAULT_EXCLUDE = ["**/node_modules/**"];
|
|
514
|
+
function toArray(value) {
|
|
515
|
+
if (value === void 0) return void 0;
|
|
516
|
+
return Array.isArray(value) ? value : [value];
|
|
517
|
+
}
|
|
518
|
+
function test(pattern, path2) {
|
|
519
|
+
if (typeof pattern === "string") return globToRegExp(pattern).test(path2);
|
|
520
|
+
pattern.lastIndex = 0;
|
|
521
|
+
return pattern.test(path2);
|
|
522
|
+
}
|
|
523
|
+
function createFileFilter(options) {
|
|
524
|
+
const include = toArray(options.include);
|
|
525
|
+
const exclude = toArray(options.exclude) ?? DEFAULT_EXCLUDE;
|
|
526
|
+
return (relativePath) => {
|
|
527
|
+
const path2 = relativePath.replace(/\\/g, "/");
|
|
528
|
+
if (!JS_FILE.test(path2)) return false;
|
|
529
|
+
if (include && !include.some((p) => test(p, path2))) return false;
|
|
530
|
+
return !exclude.some((p) => test(p, path2));
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
var TEMP_SUFFIX = ".starko-tmp";
|
|
534
|
+
var SHIFTED_FOR_FIELD = "x_starko_shifted_for";
|
|
535
|
+
var SOURCE_MAPPING_URL = /^[ \t]*\/\/[#@][ \t]+sourceMappingURL=[ \t]*(\S*)[ \t]*$/;
|
|
536
|
+
var CSS_SOURCE_MAPPING_URL = /\n?\/\*[#@] sourceMappingURL=([^*\s]+)\s*\*\/\s*$/;
|
|
537
|
+
var REMOTE_URL = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i;
|
|
538
|
+
function findSourceMappingUrl(code) {
|
|
539
|
+
let end = code.length;
|
|
540
|
+
for (let i = 0; i < 16 && end > 0; i++) {
|
|
541
|
+
const start = code.lastIndexOf("\n", end - 1) + 1;
|
|
542
|
+
const line = code.slice(start, end).replace(/\r$/, "");
|
|
543
|
+
const lineEnd = end;
|
|
544
|
+
end = start - 1;
|
|
545
|
+
if (line.trim() === "") continue;
|
|
546
|
+
if (!line.trimStart().startsWith("//")) return void 0;
|
|
547
|
+
const match = SOURCE_MAPPING_URL.exec(line);
|
|
548
|
+
if (match) return { url: match[1], start, end: lineEnd };
|
|
549
|
+
}
|
|
550
|
+
return void 0;
|
|
551
|
+
}
|
|
552
|
+
function localMapReference(url) {
|
|
553
|
+
if (!url || url.startsWith("data:")) return void 0;
|
|
554
|
+
const clean2 = url.replace(/[?#].*$/, "");
|
|
555
|
+
let decoded = clean2;
|
|
556
|
+
try {
|
|
557
|
+
decoded = decodeURI(clean2);
|
|
558
|
+
} catch {
|
|
559
|
+
}
|
|
560
|
+
if (!decoded || REMOTE_URL.test(decoded) || /^[a-z][a-z0-9+.-]*:/i.test(decoded)) return void 0;
|
|
561
|
+
if (path.isAbsolute(decoded) || path.posix.isAbsolute(decoded) || path.win32.isAbsolute(decoded)) return void 0;
|
|
562
|
+
return decoded;
|
|
563
|
+
}
|
|
564
|
+
function isInside(root, target) {
|
|
565
|
+
const rel = path.relative(root, target);
|
|
566
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
|
|
567
|
+
}
|
|
568
|
+
async function containedFile(realRoot2, candidate) {
|
|
569
|
+
try {
|
|
570
|
+
const real = await promises.realpath(candidate);
|
|
571
|
+
if (!isInside(realRoot2, real)) return void 0;
|
|
572
|
+
return (await promises.stat(real)).isFile() ? real : void 0;
|
|
573
|
+
} catch {
|
|
574
|
+
return void 0;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
async function realRoot(dir) {
|
|
578
|
+
return promises.realpath(path.resolve(dir));
|
|
579
|
+
}
|
|
580
|
+
async function resolveMapPath(jsPath, code, root) {
|
|
581
|
+
const rootReal = await realRoot(root);
|
|
582
|
+
const jsReal = await containedFile(rootReal, jsPath);
|
|
583
|
+
if (!jsReal) return void 0;
|
|
584
|
+
const candidates = [];
|
|
585
|
+
const ref = findSourceMappingUrl(code)?.url;
|
|
586
|
+
const local = ref === void 0 ? void 0 : localMapReference(ref);
|
|
587
|
+
if (local !== void 0) candidates.push(path.resolve(path.dirname(jsReal), local));
|
|
588
|
+
candidates.push(`${jsReal}.map`);
|
|
589
|
+
for (const candidate of candidates) {
|
|
590
|
+
const contained = await containedFile(rootReal, candidate);
|
|
591
|
+
if (contained) return contained;
|
|
592
|
+
}
|
|
593
|
+
return void 0;
|
|
594
|
+
}
|
|
595
|
+
async function listFiles(dir, onError) {
|
|
596
|
+
const out = [];
|
|
597
|
+
const walk = async (current, isRoot) => {
|
|
598
|
+
let entries;
|
|
599
|
+
try {
|
|
600
|
+
entries = await promises.readdir(current, { withFileTypes: true });
|
|
601
|
+
} catch (error) {
|
|
602
|
+
if (isRoot || !onError) throw error;
|
|
603
|
+
onError(current, error);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
for (const entry of entries) {
|
|
607
|
+
const full = path.join(current, entry.name);
|
|
608
|
+
if (entry.isDirectory()) await walk(full, false);
|
|
609
|
+
else if (entry.isFile()) out.push(full);
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
await walk(dir, true);
|
|
613
|
+
return out.sort();
|
|
614
|
+
}
|
|
615
|
+
async function findBundles(dir, filter) {
|
|
616
|
+
const root = await realRoot(dir);
|
|
617
|
+
const bundles = [];
|
|
618
|
+
const withoutMap = [];
|
|
619
|
+
const unreadable = [];
|
|
620
|
+
const files = await listFiles(root, (d, error) => unreadable.push({ file: toRelative(root, d), reason: errorMessage(error) }));
|
|
621
|
+
for (const file of files) {
|
|
622
|
+
const relativePath = toRelative(root, file);
|
|
623
|
+
if (!filter(relativePath)) continue;
|
|
624
|
+
try {
|
|
625
|
+
const code = await promises.readFile(file, "utf8");
|
|
626
|
+
const mapPath = await resolveMapPath(file, code, root);
|
|
627
|
+
if (mapPath) bundles.push({ jsPath: file, relativePath, mapPath });
|
|
628
|
+
else withoutMap.push(relativePath);
|
|
629
|
+
} catch (error) {
|
|
630
|
+
unreadable.push({ file: relativePath, reason: errorMessage(error) });
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return { bundles, withoutMap, unreadable };
|
|
634
|
+
}
|
|
635
|
+
function toRelative(root, file) {
|
|
636
|
+
return path.relative(root, file).split(path.sep).join("/");
|
|
637
|
+
}
|
|
638
|
+
async function readMap(mapPath) {
|
|
639
|
+
const map = JSON.parse(await promises.readFile(mapPath, "utf8"));
|
|
640
|
+
if (!map || typeof map !== "object" || typeof map.version !== "number") throw new Error("not a source map");
|
|
641
|
+
return map;
|
|
642
|
+
}
|
|
643
|
+
var NOFOLLOW = constants.O_NOFOLLOW ?? 0;
|
|
644
|
+
async function writeTemp(file, content) {
|
|
645
|
+
const temp = `${file}.${randomBytes(8).toString("hex")}${TEMP_SUFFIX}`;
|
|
646
|
+
const handle = await promises.open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 420);
|
|
647
|
+
try {
|
|
648
|
+
await handle.writeFile(content);
|
|
649
|
+
} finally {
|
|
650
|
+
await handle.close();
|
|
651
|
+
}
|
|
652
|
+
return temp;
|
|
653
|
+
}
|
|
654
|
+
async function checkReplaced(file, root) {
|
|
655
|
+
const st = await promises.lstat(file);
|
|
656
|
+
if (!st.isFile()) throw new Error(`${file} is not a regular file after it was replaced`);
|
|
657
|
+
if (root && !isInside(await promises.realpath(root), await promises.realpath(file))) throw new Error(`${file} is not inside ${root} after it was replaced`);
|
|
658
|
+
}
|
|
659
|
+
async function replaceFile(file, content, root) {
|
|
660
|
+
let temp;
|
|
661
|
+
try {
|
|
662
|
+
temp = await writeTemp(file, content);
|
|
663
|
+
await promises.rename(temp, file);
|
|
664
|
+
temp = void 0;
|
|
665
|
+
await checkReplaced(file, root);
|
|
666
|
+
} catch (error) {
|
|
667
|
+
if (temp) await promises.unlink(temp).catch(() => void 0);
|
|
668
|
+
throw error;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
async function replacePair(mapPath, mapText, jsPath, jsText, root) {
|
|
672
|
+
let mapTemp;
|
|
673
|
+
let jsTemp;
|
|
674
|
+
try {
|
|
675
|
+
mapTemp = await writeTemp(mapPath, mapText);
|
|
676
|
+
jsTemp = await writeTemp(jsPath, jsText);
|
|
677
|
+
await promises.rename(mapTemp, mapPath);
|
|
678
|
+
mapTemp = void 0;
|
|
679
|
+
await promises.rename(jsTemp, jsPath);
|
|
680
|
+
jsTemp = void 0;
|
|
681
|
+
await checkReplaced(mapPath, root);
|
|
682
|
+
await checkReplaced(jsPath, root);
|
|
683
|
+
} catch (error) {
|
|
684
|
+
if (mapTemp) await promises.unlink(mapTemp).catch(() => void 0);
|
|
685
|
+
if (jsTemp) await promises.unlink(jsTemp).catch(() => void 0);
|
|
686
|
+
throw error;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
async function removeStaleTemps(root) {
|
|
690
|
+
const walk = async (dir) => {
|
|
691
|
+
let entries;
|
|
692
|
+
try {
|
|
693
|
+
entries = await promises.readdir(dir, { withFileTypes: true });
|
|
694
|
+
} catch {
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
for (const entry of entries) {
|
|
698
|
+
const full = path.join(dir, entry.name);
|
|
699
|
+
if (entry.name.endsWith(TEMP_SUFFIX) && (entry.isFile() || entry.isSymbolicLink())) await promises.unlink(full).catch(() => void 0);
|
|
700
|
+
else if (entry.isDirectory()) await walk(full);
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
await walk(root);
|
|
704
|
+
}
|
|
705
|
+
async function injectDirectory(dir, options) {
|
|
706
|
+
const root = await realRoot(dir);
|
|
707
|
+
if (!options.dryRun) await removeStaleTemps(root);
|
|
708
|
+
const { bundles, unreadable } = await findBundles(root, options.filter);
|
|
709
|
+
const result = { injected: [], alreadyInjected: [], skipped: [...unreadable] };
|
|
710
|
+
const byMap = /* @__PURE__ */ new Map();
|
|
711
|
+
for (const b of bundles) byMap.set(b.mapPath, [...byMap.get(b.mapPath) ?? [], b]);
|
|
712
|
+
for (const bundle of bundles) {
|
|
713
|
+
const file = bundle.relativePath;
|
|
714
|
+
try {
|
|
715
|
+
const code = await promises.readFile(bundle.jsPath, "utf8");
|
|
716
|
+
const shared = byMap.get(bundle.mapPath).length > 1;
|
|
717
|
+
const map = await readMap(bundle.mapPath);
|
|
718
|
+
const fingerprint = createDebugId(code);
|
|
719
|
+
const alreadyShifted = map[SHIFTED_FOR_FIELD] === fingerprint;
|
|
720
|
+
const out = injectDebugId(code, alreadyShifted ? void 0 : map, { release: options.release, keepNativelyRegistered: options.keepNativelyRegistered });
|
|
721
|
+
if (out.kind === "none") {
|
|
722
|
+
if (map.debugId !== out.debugId && !options.dryRun && !shared) {
|
|
723
|
+
await replaceFile(bundle.mapPath, JSON.stringify({ ...map, debugId: out.debugId }), root);
|
|
724
|
+
}
|
|
725
|
+
result.alreadyInjected.push({ file, debugId: out.debugId });
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
if (shared) {
|
|
729
|
+
result.skipped.push({ file, reason: `its source map ${path.basename(bundle.mapPath)} is shared with another bundle` });
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
if (!options.dryRun) {
|
|
733
|
+
const newMap = alreadyShifted ? { ...map, debugId: out.debugId } : { ...out.map, [SHIFTED_FOR_FIELD]: fingerprint };
|
|
734
|
+
await replacePair(bundle.mapPath, JSON.stringify(newMap), bundle.jsPath, out.code, root);
|
|
735
|
+
}
|
|
736
|
+
result.injected.push({ file, debugId: out.debugId, existingId: out.kind === "snippet" });
|
|
737
|
+
} catch (error) {
|
|
738
|
+
result.skipped.push({ file, reason: errorMessage(error) });
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
return result;
|
|
742
|
+
}
|
|
743
|
+
async function collectUploads(dir, filter) {
|
|
744
|
+
const { bundles, unreadable } = await findBundles(dir, filter);
|
|
745
|
+
const collected = await collectUploadsFor(bundles);
|
|
746
|
+
return { ...collected, unreadable: [...unreadable, ...collected.unreadable] };
|
|
747
|
+
}
|
|
748
|
+
async function loadMapFor(mapPath, chunkId) {
|
|
749
|
+
const raw = await promises.readFile(mapPath);
|
|
750
|
+
if (raw.includes(`"debugId":"${chunkId}"`)) return raw;
|
|
751
|
+
const map = JSON.parse(raw.toString("utf8"));
|
|
752
|
+
return Buffer.from(JSON.stringify({ ...map, debugId: chunkId }), "utf8");
|
|
753
|
+
}
|
|
754
|
+
async function collectUploadsFor(bundles) {
|
|
755
|
+
const result = { entries: [], missingDebugId: [], unreadable: [] };
|
|
756
|
+
for (const bundle of bundles) {
|
|
757
|
+
try {
|
|
758
|
+
const code = await promises.readFile(bundle.jsPath, "utf8");
|
|
759
|
+
let chunkId = findDebugId(code);
|
|
760
|
+
if (!chunkId) {
|
|
761
|
+
const map = await readMap(bundle.mapPath);
|
|
762
|
+
chunkId = isDebugId(map.debugId) ? map.debugId.toLowerCase() : void 0;
|
|
763
|
+
}
|
|
764
|
+
if (!chunkId) {
|
|
765
|
+
result.missingDebugId.push(bundle.relativePath);
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
const id = chunkId;
|
|
769
|
+
const mapPath = bundle.mapPath;
|
|
770
|
+
result.entries.push({ chunkId: id, load: () => loadMapFor(mapPath, id), fileName: bundle.relativePath, jsPath: bundle.jsPath, mapPath });
|
|
771
|
+
} catch (error) {
|
|
772
|
+
result.unreadable.push({ file: bundle.relativePath, reason: errorMessage(error) });
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return result;
|
|
776
|
+
}
|
|
777
|
+
function stripSourceMappingUrl(code, ref) {
|
|
778
|
+
let cut = ref.end;
|
|
779
|
+
if (code[cut] === "\n") cut++;
|
|
780
|
+
return code.slice(0, ref.start) + code.slice(cut);
|
|
781
|
+
}
|
|
782
|
+
var MAP_FILE = /\.map$/;
|
|
783
|
+
var CODE_FILE = /\.(?:m|c)?js$/;
|
|
784
|
+
var CSS_FILE = /\.css$/;
|
|
785
|
+
async function exists(file) {
|
|
786
|
+
try {
|
|
787
|
+
await promises.lstat(file);
|
|
788
|
+
return true;
|
|
789
|
+
} catch {
|
|
790
|
+
return false;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
async function deleteAllSourcemaps(root, logger, options = {}) {
|
|
794
|
+
let files;
|
|
795
|
+
let rootReal = root;
|
|
796
|
+
try {
|
|
797
|
+
rootReal = await realRoot(root);
|
|
798
|
+
files = await listFiles(rootReal, (d, error) => logger?.warn(`could not read ${d}: ${errorMessage(error)}`));
|
|
799
|
+
} catch (error) {
|
|
800
|
+
if (error?.code !== "ENOENT") logger?.warn(`could not delete the source maps under ${root}: ${errorMessage(error)}`);
|
|
801
|
+
return 0;
|
|
802
|
+
}
|
|
803
|
+
let deleted = 0;
|
|
804
|
+
for (const file of files) {
|
|
805
|
+
if (!MAP_FILE.test(file)) continue;
|
|
806
|
+
try {
|
|
807
|
+
await promises.rm(file, { force: true });
|
|
808
|
+
deleted++;
|
|
809
|
+
} catch (error) {
|
|
810
|
+
logger?.warn(`could not delete ${file}: ${errorMessage(error)}`);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
for (const file of files) {
|
|
814
|
+
const js = CODE_FILE.test(file);
|
|
815
|
+
if (!js && !CSS_FILE.test(file)) continue;
|
|
816
|
+
try {
|
|
817
|
+
const code = await promises.readFile(file, "utf8");
|
|
818
|
+
if (js) {
|
|
819
|
+
const ref = findSourceMappingUrl(code);
|
|
820
|
+
const local = ref && localMapReference(ref.url);
|
|
821
|
+
if (!ref || local === void 0 || !local.endsWith(".map")) continue;
|
|
822
|
+
if (await exists(path.resolve(path.dirname(file), local))) continue;
|
|
823
|
+
const rel = toRelative(rootReal, file);
|
|
824
|
+
if (options.keepComment && options.keepComment(rel, code)) {
|
|
825
|
+
if (options.onKept) options.onKept(rel);
|
|
826
|
+
continue;
|
|
827
|
+
}
|
|
828
|
+
await replaceFile(file, stripSourceMappingUrl(code, ref), rootReal);
|
|
829
|
+
} else {
|
|
830
|
+
const match = CSS_SOURCE_MAPPING_URL.exec(code);
|
|
831
|
+
const local = match && localMapReference(match[1]);
|
|
832
|
+
if (!match || !local || !local.endsWith(".map")) continue;
|
|
833
|
+
if (await exists(path.resolve(path.dirname(file), local))) continue;
|
|
834
|
+
await replaceFile(file, code.slice(0, match.index), rootReal);
|
|
835
|
+
}
|
|
836
|
+
} catch (error) {
|
|
837
|
+
logger?.warn(`could not remove the sourceMappingURL comment from ${file}: ${errorMessage(error)}`);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return deleted;
|
|
841
|
+
}
|
|
842
|
+
function stripCssSourceMappingUrl(css, shouldStrip) {
|
|
843
|
+
const match = CSS_SOURCE_MAPPING_URL.exec(css);
|
|
844
|
+
return match && shouldStrip(match[1]) ? css.slice(0, match.index) : css;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// src/build/shared/version.ts
|
|
848
|
+
var USER_AGENT = `starko-sdk-build/${version}`;
|
|
849
|
+
|
|
850
|
+
// src/build/shared/upload.ts
|
|
851
|
+
var gzip = promisify(gzip$1);
|
|
852
|
+
var StarkoUploadError = class extends Error {
|
|
853
|
+
constructor(message, options = {}) {
|
|
854
|
+
super(message);
|
|
855
|
+
this.name = "StarkoUploadError";
|
|
856
|
+
this.status = options.status;
|
|
857
|
+
this.fatal = options.fatal ?? false;
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
function sha256Hex(data) {
|
|
861
|
+
return createHash("sha256").update(data).digest("hex");
|
|
862
|
+
}
|
|
863
|
+
function splitParts(data, size) {
|
|
864
|
+
if (data.length === 0) return [data];
|
|
865
|
+
const parts = [];
|
|
866
|
+
for (let at = 0; at < data.length; at += size) parts.push(data.subarray(at, at + size));
|
|
867
|
+
return parts;
|
|
868
|
+
}
|
|
869
|
+
function abortedError() {
|
|
870
|
+
return new StarkoUploadError("the upload was stopped (deadline reached)", { fatal: true });
|
|
871
|
+
}
|
|
872
|
+
function sleep(ms, signal) {
|
|
873
|
+
return new Promise((resolve, reject) => {
|
|
874
|
+
if (signal?.aborted) return reject(abortedError());
|
|
875
|
+
const onAbort = () => {
|
|
876
|
+
clearTimeout(timer);
|
|
877
|
+
reject(abortedError());
|
|
878
|
+
};
|
|
879
|
+
const timer = setTimeout(() => {
|
|
880
|
+
signal?.removeEventListener("abort", onAbort);
|
|
881
|
+
resolve();
|
|
882
|
+
}, ms);
|
|
883
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
function retryAfterMs(header) {
|
|
887
|
+
if (!header) return void 0;
|
|
888
|
+
const seconds = Number(header);
|
|
889
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
|
|
890
|
+
const date = Date.parse(header);
|
|
891
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
|
|
892
|
+
}
|
|
893
|
+
async function mapLimit(items, limit, fn, shouldStop) {
|
|
894
|
+
let next = 0;
|
|
895
|
+
const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
|
|
896
|
+
while (next < items.length && !shouldStop()) {
|
|
897
|
+
const item = items[next++];
|
|
898
|
+
await fn(item);
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
await Promise.all(workers);
|
|
902
|
+
}
|
|
903
|
+
async function readItem(item) {
|
|
904
|
+
const content = item.map ?? (item.load ? await item.load() : void 0);
|
|
905
|
+
if (content === void 0) throw new Error("no source map content");
|
|
906
|
+
return typeof content === "string" ? Buffer.from(content, "utf8") : content;
|
|
907
|
+
}
|
|
908
|
+
async function uploadSourcemaps(items, options) {
|
|
909
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
910
|
+
if (typeof doFetch !== "function") throw new StarkoUploadError("global fetch is not available (Node 18 or later is required)", { fatal: true });
|
|
911
|
+
const partBytes = Math.min(options.partBytes ?? SOURCEMAP_PART_BYTES, SOURCEMAP_PART_BYTES);
|
|
912
|
+
if (!(partBytes > 0)) throw new StarkoUploadError("partBytes must be positive", { fatal: true });
|
|
913
|
+
const retries = options.retries ?? 4;
|
|
914
|
+
const retryBaseMs = options.retryBaseMs ?? 500;
|
|
915
|
+
const maxRetryDelayMs = options.maxRetryDelayMs ?? 3e4;
|
|
916
|
+
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
917
|
+
const maxConsecutiveNetworkErrors = Math.max(1, options.maxConsecutiveNetworkErrors ?? 3);
|
|
918
|
+
const signal = options.signal;
|
|
919
|
+
let consecutiveNetworkErrors = 0;
|
|
920
|
+
const checkBatchSize = Math.max(1, Math.min(options.checkBatchSize ?? 100, SOURCEMAP_MAX_CHUNKS_PER_CHECK));
|
|
921
|
+
const host = options.host.replace(/\/+$/, "");
|
|
922
|
+
const secrets = [options.apiKey];
|
|
923
|
+
const result = { uploaded: [], skipped: [], failed: [] };
|
|
924
|
+
const prepared = /* @__PURE__ */ new Map();
|
|
925
|
+
for (const item of items) {
|
|
926
|
+
if (signal?.aborted) throw abortedError();
|
|
927
|
+
let raw;
|
|
928
|
+
try {
|
|
929
|
+
raw = await readItem(item);
|
|
930
|
+
} catch (error) {
|
|
931
|
+
result.failed.push({ chunkId: item.chunkId, fileName: item.fileName, error: `could not read the source map: ${redact(errorMessage(error), secrets)}` });
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
if (raw.length > SOURCEMAP_MAX_BYTES) {
|
|
935
|
+
result.failed.push({
|
|
936
|
+
chunkId: item.chunkId,
|
|
937
|
+
fileName: item.fileName,
|
|
938
|
+
error: `source map is ${raw.length} bytes, over the ${SOURCEMAP_MAX_BYTES}-byte limit; not uploaded`
|
|
939
|
+
});
|
|
940
|
+
continue;
|
|
941
|
+
}
|
|
942
|
+
let mapDebugId;
|
|
943
|
+
try {
|
|
944
|
+
mapDebugId = JSON.parse(raw.toString("utf8")).debugId;
|
|
945
|
+
} catch {
|
|
946
|
+
result.failed.push({ chunkId: item.chunkId, fileName: item.fileName, error: "source map is not valid JSON; not uploaded" });
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (mapDebugId !== item.chunkId) {
|
|
950
|
+
result.failed.push({
|
|
951
|
+
chunkId: item.chunkId,
|
|
952
|
+
fileName: item.fileName,
|
|
953
|
+
error: `the source map's debugId (${typeof mapDebugId === "string" ? mapDebugId : "missing"}) is not the bundle's debug id; not uploaded`
|
|
954
|
+
});
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
957
|
+
const hash = sha256Hex(raw);
|
|
958
|
+
const seen = prepared.get(item.chunkId);
|
|
959
|
+
if (seen) {
|
|
960
|
+
if (seen.hash !== hash) {
|
|
961
|
+
result.failed.push({
|
|
962
|
+
chunkId: item.chunkId,
|
|
963
|
+
fileName: item.fileName,
|
|
964
|
+
error: `another source map (${seen.fileName ?? "unknown file"}) has the same debug id with different content; not uploaded`
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
continue;
|
|
968
|
+
}
|
|
969
|
+
prepared.set(item.chunkId, { chunkId: item.chunkId, fileName: item.fileName, hash, size: raw.length, item });
|
|
970
|
+
}
|
|
971
|
+
if (prepared.size === 0) return result;
|
|
972
|
+
const backoff = (attempt) => {
|
|
973
|
+
const base = Math.min(retryBaseMs * 2 ** attempt, maxRetryDelayMs);
|
|
974
|
+
return Math.round(base * (0.75 + Math.random() * 0.5));
|
|
975
|
+
};
|
|
976
|
+
async function request(what, path2, init) {
|
|
977
|
+
const url = `${host}${path2}`;
|
|
978
|
+
for (let attempt = 0; ; attempt++) {
|
|
979
|
+
if (signal?.aborted) throw abortedError();
|
|
980
|
+
const controller = new AbortController();
|
|
981
|
+
let timedOut = false;
|
|
982
|
+
const timer = setTimeout(() => {
|
|
983
|
+
timedOut = true;
|
|
984
|
+
controller.abort();
|
|
985
|
+
}, timeoutMs);
|
|
986
|
+
const onAbort = () => controller.abort();
|
|
987
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
988
|
+
const done = () => {
|
|
989
|
+
clearTimeout(timer);
|
|
990
|
+
signal?.removeEventListener("abort", onAbort);
|
|
991
|
+
};
|
|
992
|
+
let res;
|
|
993
|
+
let text;
|
|
994
|
+
try {
|
|
995
|
+
res = await doFetch(url, {
|
|
996
|
+
method: "POST",
|
|
997
|
+
headers: {
|
|
998
|
+
authorization: `Bearer ${options.apiKey}`,
|
|
999
|
+
"content-type": init.contentType,
|
|
1000
|
+
"user-agent": USER_AGENT
|
|
1001
|
+
},
|
|
1002
|
+
// Node's fetch accepts a Buffer (a Uint8Array); the DOM typings are narrower.
|
|
1003
|
+
body: init.body,
|
|
1004
|
+
// Never followed: a redirect would POST the client's source to another address.
|
|
1005
|
+
redirect: "manual",
|
|
1006
|
+
signal: controller.signal
|
|
1007
|
+
});
|
|
1008
|
+
text = await res.text();
|
|
1009
|
+
} catch (error) {
|
|
1010
|
+
done();
|
|
1011
|
+
if (signal?.aborted) throw abortedError();
|
|
1012
|
+
const reason = timedOut ? `no answer within ${Math.round(timeoutMs / 1e3)} s` : redact(errorMessage(error), secrets);
|
|
1013
|
+
consecutiveNetworkErrors++;
|
|
1014
|
+
if (consecutiveNetworkErrors >= maxConsecutiveNetworkErrors) {
|
|
1015
|
+
throw new StarkoUploadError(`cannot reach ${host}: ${consecutiveNetworkErrors} network errors in a row (last: ${what}: ${reason})`, {
|
|
1016
|
+
fatal: true
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
if (attempt >= retries) throw new StarkoUploadError(`${what}: network error after ${attempt + 1} attempts: ${reason}`);
|
|
1020
|
+
options.logger?.warn(`${what}: network error (${reason}), retrying`);
|
|
1021
|
+
await sleep(backoff(attempt), signal);
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
done();
|
|
1025
|
+
consecutiveNetworkErrors = 0;
|
|
1026
|
+
if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") {
|
|
1027
|
+
const location = res.headers.get("location");
|
|
1028
|
+
throw new StarkoUploadError(
|
|
1029
|
+
`${what}: ${host} answered with a redirect (${res.status || "3xx"}${location ? ` to ${redact(location, secrets)}` : ""}); source maps are never sent to another address. Set host to the address Starko answers on.`,
|
|
1030
|
+
{ status: res.status || 307, fatal: true }
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
if (res.status === 429 || res.status >= 500) {
|
|
1034
|
+
const delay = res.status === 429 ? retryAfterMs(res.headers.get("retry-after")) : void 0;
|
|
1035
|
+
if (attempt >= retries) {
|
|
1036
|
+
throw new StarkoUploadError(`${what}: server answered ${res.status} after ${attempt + 1} attempts`, { status: res.status });
|
|
1037
|
+
}
|
|
1038
|
+
options.logger?.warn(`${what}: server answered ${res.status}, retrying`);
|
|
1039
|
+
await sleep(Math.min(delay ?? backoff(attempt), maxRetryDelayMs), signal);
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
let body;
|
|
1043
|
+
try {
|
|
1044
|
+
body = text ? JSON.parse(text) : void 0;
|
|
1045
|
+
} catch {
|
|
1046
|
+
body = void 0;
|
|
1047
|
+
}
|
|
1048
|
+
const serverMessage = body?.message ? `: ${redact(String(body.message), secrets)}` : "";
|
|
1049
|
+
if (res.status === 401) {
|
|
1050
|
+
throw new StarkoUploadError(
|
|
1051
|
+
`Starko rejected the API key (401)${serverMessage}. Set apiKey or STARKO_API_KEY to a secret key with the sourcemaps:write scope (Starko > Settings).`,
|
|
1052
|
+
{ status: 401, fatal: true }
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
if (res.status === 403) {
|
|
1056
|
+
throw new StarkoUploadError(
|
|
1057
|
+
`Starko refused the upload (403)${serverMessage}. The API key needs the sourcemaps:write scope.`,
|
|
1058
|
+
{ status: 403, fatal: true }
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
if (res.status === 409) {
|
|
1062
|
+
throw new StarkoUploadError(
|
|
1063
|
+
`${what}: Starko already has a different source map for this debug id (409)${serverMessage}. A debug id is write-once; delete the stored map in Starko to replace it.`,
|
|
1064
|
+
{ status: 409 }
|
|
1065
|
+
);
|
|
1066
|
+
}
|
|
1067
|
+
if (!res.ok) {
|
|
1068
|
+
throw new StarkoUploadError(`${what}: server answered ${res.status}${serverMessage}`, { status: res.status });
|
|
1069
|
+
}
|
|
1070
|
+
if (!body || body.ok !== true) {
|
|
1071
|
+
throw new StarkoUploadError(`${what}: unexpected response${serverMessage || ` (${res.status})`}`, { status: res.status });
|
|
1072
|
+
}
|
|
1073
|
+
return body;
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
const all = [...prepared.values()];
|
|
1077
|
+
const missing = /* @__PURE__ */ new Set();
|
|
1078
|
+
for (let at = 0; at < all.length; at += checkBatchSize) {
|
|
1079
|
+
if (signal?.aborted) throw abortedError();
|
|
1080
|
+
const batch = all.slice(at, at + checkBatchSize);
|
|
1081
|
+
const payload = {
|
|
1082
|
+
chunks: batch.map((p) => ({ chunk_id: p.chunkId, content_hash: p.hash }))
|
|
1083
|
+
};
|
|
1084
|
+
if (options.release) payload.release = options.release;
|
|
1085
|
+
const res = await request("check", PATHS.SOURCEMAPS_CHECK, {
|
|
1086
|
+
body: JSON.stringify(payload),
|
|
1087
|
+
contentType: "application/json"
|
|
1088
|
+
});
|
|
1089
|
+
if (!res.data || !Array.isArray(res.data.missing)) throw new StarkoUploadError("check: response has no `missing` list");
|
|
1090
|
+
for (const id of res.data.missing) missing.add(String(id));
|
|
1091
|
+
}
|
|
1092
|
+
let fatal;
|
|
1093
|
+
const todo = all.filter((p) => {
|
|
1094
|
+
if (missing.has(p.chunkId)) return true;
|
|
1095
|
+
result.skipped.push({ chunkId: p.chunkId, fileName: p.fileName });
|
|
1096
|
+
return false;
|
|
1097
|
+
});
|
|
1098
|
+
await mapLimit(
|
|
1099
|
+
todo,
|
|
1100
|
+
options.concurrency ?? 4,
|
|
1101
|
+
async (p) => {
|
|
1102
|
+
try {
|
|
1103
|
+
const raw = await readItem(p.item);
|
|
1104
|
+
if (sha256Hex(raw) !== p.hash) throw new StarkoUploadError("the source map changed while it was being uploaded; not uploaded");
|
|
1105
|
+
const gz = await gzip(raw);
|
|
1106
|
+
const parts = splitParts(gz, partBytes);
|
|
1107
|
+
if (parts.length > SOURCEMAP_MAX_PARTS) {
|
|
1108
|
+
throw new StarkoUploadError(
|
|
1109
|
+
`source map is ${gz.length} bytes gzipped, more than ${SOURCEMAP_MAX_PARTS} parts of ${partBytes} bytes; not uploaded`
|
|
1110
|
+
);
|
|
1111
|
+
}
|
|
1112
|
+
for (let part = 0; part < parts.length; part++) {
|
|
1113
|
+
if (fatal || signal?.aborted) return;
|
|
1114
|
+
const query = new URLSearchParams({
|
|
1115
|
+
chunk_id: p.chunkId,
|
|
1116
|
+
part: String(part),
|
|
1117
|
+
parts: String(parts.length),
|
|
1118
|
+
content_hash: p.hash
|
|
1119
|
+
});
|
|
1120
|
+
await request(
|
|
1121
|
+
`upload ${p.fileName ?? p.chunkId} part ${part + 1}/${parts.length}`,
|
|
1122
|
+
`${PATHS.SOURCEMAPS_UPLOAD}?${query.toString()}`,
|
|
1123
|
+
{ body: parts[part], contentType: "application/octet-stream" }
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
const complete = {
|
|
1127
|
+
chunk_id: p.chunkId,
|
|
1128
|
+
parts: parts.length,
|
|
1129
|
+
content_hash: p.hash,
|
|
1130
|
+
size_bytes: p.size
|
|
1131
|
+
};
|
|
1132
|
+
if (p.fileName) complete.file_name = p.fileName;
|
|
1133
|
+
if (options.release) complete.release = { version: options.release.version };
|
|
1134
|
+
await request(`complete ${p.fileName ?? p.chunkId}`, PATHS.SOURCEMAPS_COMPLETE, {
|
|
1135
|
+
body: JSON.stringify(complete),
|
|
1136
|
+
contentType: "application/json"
|
|
1137
|
+
});
|
|
1138
|
+
result.uploaded.push({ chunkId: p.chunkId, fileName: p.fileName, parts: parts.length, sizeBytes: p.size });
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
if (error instanceof StarkoUploadError && error.fatal) {
|
|
1141
|
+
fatal ?? (fatal = error);
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
const message = errorMessage(error);
|
|
1145
|
+
result.failed.push({ chunkId: p.chunkId, fileName: p.fileName, error: redact(message, secrets) });
|
|
1146
|
+
}
|
|
1147
|
+
},
|
|
1148
|
+
() => fatal !== void 0 || signal?.aborted === true
|
|
1149
|
+
);
|
|
1150
|
+
if (fatal) throw fatal;
|
|
1151
|
+
if (signal?.aborted) throw abortedError();
|
|
1152
|
+
return result;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// src/build/shared/pipeline.ts
|
|
1156
|
+
async function runUpload(entries, options) {
|
|
1157
|
+
try {
|
|
1158
|
+
return await runUploadUnsafe(entries, options);
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
const message = errorMessage(error);
|
|
1161
|
+
try {
|
|
1162
|
+
options.logger.error(`source map upload failed: ${message}`);
|
|
1163
|
+
} catch {
|
|
1164
|
+
}
|
|
1165
|
+
return { ok: false, error: message };
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
async function runUploadUnsafe(entries, options) {
|
|
1169
|
+
const { logger } = options;
|
|
1170
|
+
const releaseNote = options.release ? ` for release ${options.release.version}` : "";
|
|
1171
|
+
if (entries.length === 0) {
|
|
1172
|
+
logger.info("no source maps to upload");
|
|
1173
|
+
return { ok: true };
|
|
1174
|
+
}
|
|
1175
|
+
if (options.dryRun) {
|
|
1176
|
+
logger.info(`dry run: would upload ${entries.length} source map(s)${releaseNote} to ${options.host}`);
|
|
1177
|
+
for (const e of entries) logger.info(` ${e.fileName ?? e.mapPath ?? "?"} \u2192 ${e.chunkId}`);
|
|
1178
|
+
return { ok: true };
|
|
1179
|
+
}
|
|
1180
|
+
if (!options.apiKey) {
|
|
1181
|
+
const error = `no API key (set apiKey or STARKO_API_KEY): ${entries.length} source map(s) were not uploaded`;
|
|
1182
|
+
logger.warn(error);
|
|
1183
|
+
return { ok: false, error };
|
|
1184
|
+
}
|
|
1185
|
+
const deadlineMs = options.uploadTimeoutMs !== void 0 && options.uploadTimeoutMs > 0 ? options.uploadTimeoutMs : DEFAULT_UPLOAD_TIMEOUT_MS;
|
|
1186
|
+
const controller = new AbortController();
|
|
1187
|
+
let timer;
|
|
1188
|
+
const deadline = new Promise((resolve) => {
|
|
1189
|
+
timer = setTimeout(() => {
|
|
1190
|
+
controller.abort();
|
|
1191
|
+
resolve("deadline");
|
|
1192
|
+
}, deadlineMs);
|
|
1193
|
+
});
|
|
1194
|
+
const upload = uploadSourcemaps(entries, {
|
|
1195
|
+
...options.client,
|
|
1196
|
+
apiKey: options.apiKey,
|
|
1197
|
+
host: options.host,
|
|
1198
|
+
release: options.release,
|
|
1199
|
+
logger,
|
|
1200
|
+
signal: controller.signal
|
|
1201
|
+
});
|
|
1202
|
+
upload.catch(() => void 0);
|
|
1203
|
+
let result;
|
|
1204
|
+
try {
|
|
1205
|
+
const raced = await Promise.race([upload, deadline]);
|
|
1206
|
+
if (raced === "deadline") {
|
|
1207
|
+
const error = `the upload did not finish within ${Math.round(deadlineMs / 1e3)} s and was abandoned`;
|
|
1208
|
+
logger.warn(`source map upload: ${error}`);
|
|
1209
|
+
return { ok: false, error };
|
|
1210
|
+
}
|
|
1211
|
+
result = raced;
|
|
1212
|
+
} catch (error) {
|
|
1213
|
+
const message = controller.signal.aborted ? `the upload did not finish within ${Math.round(deadlineMs / 1e3)} s and was abandoned` : errorMessage(error);
|
|
1214
|
+
logger.error(`source map upload failed: ${message}`);
|
|
1215
|
+
return { ok: false, error: message };
|
|
1216
|
+
} finally {
|
|
1217
|
+
clearTimeout(timer);
|
|
1218
|
+
}
|
|
1219
|
+
for (const f of result.failed) logger.warn(`could not upload ${f.fileName ?? f.chunkId}: ${f.error}`);
|
|
1220
|
+
logger.info(
|
|
1221
|
+
`source maps${releaseNote}: ${result.uploaded.length} uploaded, ${result.skipped.length} already on the server, ${result.failed.length} failed`
|
|
1222
|
+
);
|
|
1223
|
+
return result.failed.length === 0 ? { ok: true, result } : { ok: false, result, error: `${result.failed.length} source map(s) could not be uploaded` };
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
export { NO_API_KEY_MESSAGE, collectUploads, createFileFilter, createLogger, deleteAllSourcemaps, errorMessage, findDebugId, findSourceMappingUrl, hasNativeRegistration, hasStarkoRegistration, injectDebugId, injectDirectory, localMapReference, planInjection, resolveConnection, resolveReleaseInfo, runUpload, shouldDeleteSourcemaps, stripCssSourceMappingUrl, stripSourceMappingUrl };
|