-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
290 lines (251 loc) · 11.6 KB
/
Copy pathindex.js
File metadata and controls
290 lines (251 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
const fs = require('fs-extra');
const path = require('path');
const crypto = require('crypto');
const axios = require('axios');
const FormData = require('form-data');
// @semantic-release/error v4+ is ESM with a default export; older versions
// exported the class directly. Support both so handleError can actually throw.
const semanticReleaseErrorModule = require('@semantic-release/error');
const SemanticReleaseError = semanticReleaseErrorModule.default || semanticReleaseErrorModule;
const DEFAULT_PANO_URL = 'https://api.panomc.com';
const DEFAULT_MAX_CHANGELOG_LENGTH = 6500;
const TRUNCATION_SUFFIX = '...';
function getConfigs(pluginConfig) {
if (Array.isArray(pluginConfig.configs)) {
return pluginConfig.configs.map(config => {
// Do NOT inherit `branches` from the top level in multi-config mode:
// semantic-release merges the resolved GLOBAL options (including the
// release configuration's `branches`, e.g. [{name:"dev"},"main"]) into
// the plugin config. Inheriting that into every entry would activate
// ALL entries on ALL release branches — e.g. a dev prerelease would
// also publish to the production store. Branch scoping in multi-config
// mode must be declared per entry.
const { configs, branches, ...baseConfig } = pluginConfig;
return {
...baseConfig,
...config
};
});
}
return [pluginConfig];
}
function currentBranchName(context) {
return (
(context && context.branch && context.branch.name) ||
(context && context.envCi && context.envCi.branch) ||
null
);
}
// A config without `branches` runs everywhere (backward compat). With `branches`,
// it only runs when the release branch matches one of the listed names. If we
// can't resolve the branch (unusual — semantic-release normally sets it), we
// fall back to running so a missing context can't silently drop a release.
//
// IMPORTANT: semantic-release merges the resolved GLOBAL options into every
// plugin's config, so `config.branches` is usually the release configuration's
// top-level branch list — whose entries are branch SPECS (strings OR objects
// like { name: "dev", prerelease: true }), not the plain name list this option
// documents. A plain `includes(branch)` therefore missed every object entry and
// silently skipped publishing on prerelease branches (dev releases never reached
// the Pano store while string-spec branches like "main" kept working). Normalize
// specs to names before matching.
function configMatchesBranch(config, branch) {
const branches = config && config.branches;
if (!Array.isArray(branches) || branches.length === 0) return true;
if (!branch) return true;
const names = branches
.map((entry) => (typeof entry === 'string' ? entry : entry && entry.name))
.filter(Boolean);
if (names.length === 0) return true;
return names.includes(branch);
}
function getActiveConfigs(pluginConfig, context) {
const branch = currentBranchName(context);
return getConfigs(pluginConfig).filter(c => configMatchesBranch(c, branch));
}
// Truncate the changelog to fit the receiving Pano resource system's `changelog`
// validation budget. semantic-release-generated notes can balloon when the first
// stable release on a branch aggregates a long prerelease history, and the Pano
// backend rejects oversized payloads with BAD_REQUEST. We cut to `maxLength`
// characters total — `TRUNCATION_SUFFIX` included — so the body never grows past
// the configured budget, regardless of where the cut lands inside a word.
function truncateChangelog(notes, maxLength) {
if (!notes) return notes || '';
const cap = Number.isFinite(maxLength) && maxLength > 0
? Math.floor(maxLength)
: DEFAULT_MAX_CHANGELOG_LENGTH;
if (notes.length <= cap) return notes;
const suffixLen = TRUNCATION_SUFFIX.length;
if (cap <= suffixLen) return TRUNCATION_SUFFIX.slice(0, cap);
return notes.slice(0, cap - suffixLen) + TRUNCATION_SUFFIX;
}
/**
* Compute SHA-256 hash of a file.
*/
async function computeFileHash(filePath) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
stream.on('data', (data) => hash.update(data));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
/**
* Build the GitHub Release asset download URL.
*
* @param {string} repositoryUrl - e.g. "https://github.com/PanoMC/pano-mc-plugin.git"
* @param {string} tagName - e.g. "v1.2.3"
* @param {string} fileName - basename of the asset, e.g. "Pano-Spigot-1.2.3.jar"
*/
function buildGitHubAssetUrl(repositoryUrl, tagName, fileName) {
// Normalize: strip .git suffix, trailing slashes
let repoUrl = repositoryUrl.replace(/\.git$/, '').replace(/\/+$/, '');
// Convert SSH URLs to HTTPS
if (repoUrl.startsWith('git@')) {
repoUrl = repoUrl.replace(':', '/').replace('git@', 'https://');
}
return `${repoUrl}/releases/download/${tagName}/${encodeURIComponent(fileName)}`;
}
async function verifyConditions(pluginConfig, context) {
const { env, logger } = context;
const configs = getActiveConfigs(pluginConfig, context);
const errors = [];
if (configs.length === 0 && logger) {
const branch = currentBranchName(context) || '(unknown)';
logger.log(`No semantic-release-pano configs match branch "${branch}"; skipping.`);
}
for (const config of configs) {
const { resourceId, file, panoVersion, tokenVar, useGitHubLink, repositoryUrl } = config;
const panoToken = tokenVar ? env[tokenVar] : env.PANO_TOKEN;
if (!panoToken) {
errors.push(`PANO_TOKEN environment variable is required${tokenVar ? ` (checked ${tokenVar})` : ''}.`);
}
if (!resourceId) {
errors.push('resourceId configuration is required.');
}
if (!file) {
errors.push('file configuration is required.');
}
if (!panoVersion) {
errors.push('panoVersion configuration is required (e.g. "1.0.0").');
}
if (useGitHubLink && !repositoryUrl) {
errors.push('repositoryUrl is required when useGitHubLink is true.');
}
}
if (errors.length > 0) {
throw new AggregateError(errors.map(msg => new SemanticReleaseError(msg, 'EINVALIDCONFIG')));
}
}
async function publish(pluginConfig, context) {
const { env, nextRelease, logger } = context;
const configs = getActiveConfigs(pluginConfig, context);
const results = [];
if (configs.length === 0) {
const branch = currentBranchName(context) || '(unknown)';
logger.log(`No semantic-release-pano configs match branch "${branch}"; nothing to publish.`);
return undefined;
}
for (const config of configs) {
const { resourceId, file, panoUrl, panoVersion, tokenVar, useGitHubLink, repositoryUrl, maxChangelogLength } = config;
const panoToken = tokenVar ? env[tokenVar] : env.PANO_TOKEN;
const apiUrl = panoUrl || DEFAULT_PANO_URL;
const version = nextRelease.version;
const tagName = nextRelease.gitTag || `v${version}`;
const rawNotes = nextRelease.notes || '';
const notes = truncateChangelog(rawNotes, maxChangelogLength);
if (notes.length < rawNotes.length) {
logger.log(`Changelog truncated from ${rawNotes.length} to ${notes.length} chars (maxChangelogLength=${maxChangelogLength ?? DEFAULT_MAX_CHANGELOG_LENGTH}).`);
}
// Resolve file path with version substitution
const resolvedFile = file.replace(/\${version}/g, version);
const filePath = path.resolve(resolvedFile);
if (!(await fs.pathExists(filePath))) {
throw new SemanticReleaseError(`File ${filePath} not found.`, 'ENOFILE');
}
const fileHash = await computeFileHash(filePath);
const fileName = path.basename(filePath);
logger.log(`Publishing version ${version} (tag: ${tagName}) to Pano Resource System...`);
logger.log(`API URL: ${apiUrl}`);
logger.log(`Resource ID: ${resourceId}`);
logger.log(`File: ${filePath}`);
logger.log(`SHA-256: ${fileHash}`);
if (useGitHubLink) {
// Link mode: send GitHub Release asset URL + hash instead of uploading the file
const assetUrl = buildGitHubAssetUrl(repositoryUrl, tagName, fileName);
logger.log(`Mode: GitHub Link`);
logger.log(`Asset URL: ${assetUrl}`);
const formData = new FormData();
formData.append('title', `v${version}`);
formData.append('changelog', notes);
formData.append('tag', tagName);
formData.append('panoVersion', panoVersion);
formData.append('url', assetUrl);
formData.append('hash', fileHash);
try {
const response = await axios.post(`${apiUrl}/v1/resources/${resourceId}/versions`, formData, {
headers: {
...formData.getHeaders(),
'Authorization': `Bearer ${panoToken}`
}
});
logger.log(`Successfully published version ${version} to Pano (GitHub link mode)!`);
logger.log(`Response: ${JSON.stringify(response.data)}`);
results.push({
name: `Pano Resource Release ${version}`,
url: `${apiUrl}/resources/${resourceId}`
});
} catch (error) {
handleError(error, logger);
}
} else {
// Upload mode: upload file directly (original behavior)
logger.log(`Mode: File Upload`);
const formData = new FormData();
formData.append('title', `v${version}`);
formData.append('changelog', notes);
formData.append('tag', tagName);
formData.append('panoVersion', panoVersion);
formData.append('file', fs.createReadStream(filePath));
try {
const response = await axios.post(`${apiUrl}/v1/resources/${resourceId}/versions`, formData, {
headers: {
...formData.getHeaders(),
'Authorization': `Bearer ${panoToken}`
},
maxContentLength: Infinity,
maxBodyLength: Infinity
});
logger.log(`Successfully published version ${version} to Pano (upload mode)!`);
logger.log(`Response: ${JSON.stringify(response.data)}`);
results.push({
name: `Pano Resource Release ${version}`,
url: `${apiUrl}/resources/${resourceId}`
});
} catch (error) {
handleError(error, logger);
}
}
}
return results.length > 0 ? results[0] : undefined;
}
function handleError(error, logger) {
logger.error('Failed to publish to Pano.');
if (error.response) {
logger.error(`Status: ${error.response.status}`);
logger.error(`Data: ${JSON.stringify(error.response.data)}`);
throw new SemanticReleaseError(
`Pano API Error: ${error.response.status} - ${JSON.stringify(error.response.data)}`,
'EPANOAPI',
JSON.stringify(error.response.data)
);
} else {
logger.error(error.message);
throw new SemanticReleaseError(error.message, 'ENETWORK');
}
}
module.exports = {
verifyConditions,
publish
};