-
Notifications
You must be signed in to change notification settings - Fork 0
552 lines (473 loc) · 23 KB
/
Copy pathrelease-full.yml
File metadata and controls
552 lines (473 loc) · 23 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
name: Full Release Pipeline
on:
release:
types: [published]
workflow_dispatch:
inputs:
version:
description: 'Version to release (e.g., 1.0.6)'
required: true
type: string
# Общая группа с deploy-www.yml: оба workflow пишут index.html в MAIN bucket,
# параллельный запуск приводил к гонке "кто последний, тот и победил"
concurrency:
group: site-deploy
cancel-in-progress: false
jobs:
release:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: write
packages: write
steps:
# ============================================
# 1. Checkout and Setup
# ============================================
- name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
with:
ref: main
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
fetch-tags: true
- name: Setup Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with:
node-version: '24'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: npm ci
# AWS CLI v2 предустановлен на ubuntu-latest; pip install awscli тянул
# непроверенный пакет в job с облачными секретами
- name: Verify AWS CLI
run: aws --version
- name: Configure AWS CLI for Yandex Cloud
env:
AWS_ACCESS_KEY_ID: ${{ secrets.YANDEX_STORAGE_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.YANDEX_STORAGE_SECRET_KEY }}
run: |
aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
aws configure set default.region ru-central1
# ============================================
# 2. Extract version from release tag
# ============================================
- name: Extract version from tag
id: version
# Имя тега и input - недоверенные строки: передаём только через env,
# интерполяция ${{ }} прямо в тело скрипта позволяла выполнить произвольный код
env:
RAW_TAG: ${{ github.event.release.tag_name }}
RAW_INPUT_VERSION: ${{ github.event.inputs.version }}
run: |
# Get version from release event or workflow_dispatch input
if [ -n "$RAW_TAG" ]; then
TAG="$RAW_TAG"
VERSION="${TAG#v}"
else
VERSION="$RAW_INPUT_VERSION"
TAG="v${VERSION}"
fi
# Строгая валидация: отсекает и payload в имени тега, и нечисловые версии
# (v1.2.0-rc1 ломал бы sed-цепочки следующих релизов)
if ! printf '%s' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "::error::Некорректная версия: '$VERSION' (ожидается X.Y.Z)"
exit 1
fi
echo "tag=$TAG" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "version_folder=v${VERSION}" >> $GITHUB_OUTPUT
echo "📦 Release tag: $TAG"
echo "📦 Version: $VERSION"
# Релиз собирается из main: убеждаемся, что тег указывает именно на main HEAD,
# иначе опубликованные байты разойдутся с тегом (ломается и npm provenance)
- name: Verify tag matches main HEAD
env:
TAG: ${{ steps.version.outputs.tag }}
run: |
if ! git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
echo "::error::Тег $TAG не найден - создайте GitHub Release с этим тегом"
exit 1
fi
TAG_SHA=$(git rev-list -n 1 "$TAG")
HEAD_SHA=$(git rev-parse HEAD)
if [ "$TAG_SHA" != "$HEAD_SHA" ]; then
echo "::error::Тег $TAG ($TAG_SHA) не совпадает с main HEAD ($HEAD_SHA). Пересоздайте тег на актуальном HEAD."
exit 1
fi
echo "✅ Тег $TAG указывает на main HEAD"
# ============================================
# 3. Update package.json and package-lock.json
# ============================================
- name: Update package.json version
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "📝 Updating package.json to version $VERSION..."
npm version $VERSION --no-git-tag-version --allow-same-version
echo "✅ package.json updated"
grep '"version"' package.json | head -1
# ============================================
# 4. Update src/core.js version (source of truth)
# ============================================
# Note: prefetch.js and prefetch.esm.js are now generated by build.js
# which reads version from package.json and replaces __VERSION__ placeholder
- name: Update README.md version
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "📝 Updating README.md to version $VERSION..."
# Update version in JavaScript API example: // "1.0.X"
sed -i "s|// \"[0-9]*\.[0-9]*\.[0-9]*\"|// \"${VERSION}\"|g" README.md
echo "✅ README.md updated"
grep -n "Prefetch.version" README.md | head -1
# ============================================
# 5. Build dist/prefetch.min.js + dist/prefetch.esm.min.js
# ============================================
- name: Build minified versions
run: |
echo "🔨 Building dist/prefetch.min.js + dist/prefetch.esm.min.js..."
npm run build
echo "✅ Build complete"
ls -la dist/
# ============================================
# 6. Calculate SRI Hash
# ============================================
- name: Calculate SRI integrity hash
id: sri
run: |
echo "🔐 Calculating SRI hash..."
# IIFE версия
SRI_HASH=$(openssl dgst -sha384 -binary dist/prefetch.min.js | openssl base64 -A)
FULL_SRI="sha384-${SRI_HASH}"
# ESM версия
ESM_SRI_HASH=$(openssl dgst -sha384 -binary dist/prefetch.esm.min.js | openssl base64 -A)
FULL_ESM_SRI="sha384-${ESM_SRI_HASH}"
echo "sri_hash=$FULL_SRI" >> $GITHUB_OUTPUT
echo "esm_sri_hash=$FULL_ESM_SRI" >> $GITHUB_OUTPUT
echo "🔐 IIFE SRI Hash: $FULL_SRI"
echo "🔐 ESM SRI Hash: $FULL_ESM_SRI"
# ============================================
# 7. Upload to CDN bucket
# ============================================
- name: Upload prefetch.min.js to CDN
env:
BUCKET: ${{ secrets.YANDEX_STORAGE_BUCKET_CDN }}
ENDPOINT: ${{ secrets.YANDEX_STORAGE_ENDPOINT }}
VERSION_FOLDER: ${{ steps.version.outputs.version_folder }}
VERSION: ${{ steps.version.outputs.version }}
SRI_HASH: ${{ steps.sri.outputs.sri_hash }}
run: |
echo "📤 Uploading to CDN: $BUCKET/$VERSION_FOLDER/prefetch.min.js"
aws s3 cp dist/prefetch.min.js \
s3://${BUCKET}/${VERSION_FOLDER}/prefetch.min.js \
--endpoint-url ${ENDPOINT} \
--content-type "application/javascript; charset=utf-8" \
--cache-control "public, max-age=31536000, immutable" \
--metadata "version=${VERSION},sri-hash=${SRI_HASH}"
echo "✅ Uploaded to: s3://${BUCKET}/${VERSION_FOLDER}/prefetch.min.js"
# ============================================
# 8. Update www/index.html
# ============================================
- name: Update index.html with new version and SRI
env:
VERSION: ${{ steps.version.outputs.version }}
VERSION_FOLDER: ${{ steps.version.outputs.version_folder }}
SRI_HASH: ${{ steps.sri.outputs.sri_hash }}
run: |
echo "📝 Updating www/index.html..."
# Replace all version paths: /v1.0.X/ -> /vNEW/
sed -i "s|/v[0-9]*\.[0-9]*\.[0-9]*/|/${VERSION_FOLDER}/|g" www/index.html
# Replace jsDelivr version: @prefetchru/prefetch@X.X.X -> @prefetchru/prefetch@NEW
sed -i "s|@prefetchru/prefetch@[0-9]*\.[0-9]*\.[0-9]*|@prefetchru/prefetch@${VERSION}|g" www/index.html
# Replace all SRI hashes (handles both plain HTML and syntax-highlighted code)
# Pattern 1: integrity="sha384-..."
sed -i "s|integrity=\"sha384-[^\"]*\"|integrity=\"${SRI_HASH}\"|g" www/index.html
# Pattern 2: "sha384-..." in code spans (for syntax highlighting)
sed -i "s|\"sha384-[^\"]*\"|\"${SRI_HASH}\"|g" www/index.html
# Replace "Версия X.X.X" text
sed -i "s|Версия [0-9]*\.[0-9]*\.[0-9]*|Версия ${VERSION}|g" www/index.html
# Replace version in code examples: // "X.X.X"
sed -i "s|// \"[0-9]*\.[0-9]*\.[0-9]*\"|// \"${VERSION}\"|g" www/index.html
echo "✅ www/index.html updated"
echo ""
echo "📄 Updated lines:"
grep -n "/${VERSION_FOLDER}/" www/index.html | head -5
grep -n "Версия ${VERSION}" www/index.html | head -2
# ============================================
# 8a. Update www/llms.txt (версия и SRI для LLM-агентов)
# ============================================
- name: Update llms.txt with new version and SRI
env:
VERSION: ${{ steps.version.outputs.version }}
VERSION_FOLDER: ${{ steps.version.outputs.version_folder }}
SRI_HASH: ${{ steps.sri.outputs.sri_hash }}
run: |
echo "📝 Updating www/llms.txt..."
sed -i "s|/v[0-9]*\.[0-9]*\.[0-9]*/prefetch.min.js|/${VERSION_FOLDER}/prefetch.min.js|g" www/llms.txt
sed -i "s|integrity=\"sha384-[^\"]*\"|integrity=\"${SRI_HASH}\"|g" www/llms.txt
sed -i "s|// \"[0-9]*\.[0-9]*\.[0-9]*\"|// \"${VERSION}\"|g" www/llms.txt
echo "✅ www/llms.txt updated"
grep -n "${VERSION_FOLDER}" www/llms.txt | head -3
# ============================================
# 9. Update www/sitemap.xml
# ============================================
- name: Update sitemap.xml with current date
run: |
echo "📝 Updating www/sitemap.xml..."
TODAY=$(date -u +"%Y-%m-%d")
# Релиз меняет только главную и llms.txt - обновляем lastmod точечно,
# глобальная замена ставила сегодняшнюю дату и неизменённым URL
sed -i "/<loc>https:\/\/prefetch\.ru\/<\/loc>/,/<\/url>/ s|<lastmod>[0-9-]*</lastmod>|<lastmod>${TODAY}</lastmod>|" www/sitemap.xml
sed -i "/<loc>https:\/\/prefetch\.ru\/llms\.txt<\/loc>/,/<\/url>/ s|<lastmod>[0-9-]*</lastmod>|<lastmod>${TODAY}</lastmod>|" www/sitemap.xml
echo "✅ www/sitemap.xml updated with date: $TODAY"
cat www/sitemap.xml
# ============================================
# 10. Minify index.html (only for deploy, not for commit)
# ============================================
- name: Minify index.html for deploy
run: |
echo "🔨 Minifying www/index.html for deploy..."
# Сохраняем оригинал для коммита (в репо всегда несжатый)
cp www/index.html www/index.html.original
# Размер до минификации
BEFORE=$(stat -c%s www/index.html)
echo "📄 Before: $BEFORE bytes"
# Минификация HTML
npx --yes html-minifier-terser \
--collapse-whitespace \
--preserve-line-breaks \
--remove-comments \
--remove-redundant-attributes \
--remove-script-type-attributes \
--remove-style-link-type-attributes \
--minify-css true \
--minify-js true \
--input-dir www \
--output-dir www \
--file-ext html
# Размер после минификации
AFTER=$(stat -c%s www/index.html)
SAVED=$((BEFORE - AFTER))
PERCENT=$((SAVED * 100 / BEFORE))
echo "📄 After: $AFTER bytes"
echo "✅ Saved: $SAVED bytes ($PERCENT%)"
# ============================================
# 11. Upload changed www/ files to MAIN bucket
# ============================================
- name: Upload changed www/ files to MAIN bucket
env:
BUCKET: ${{ secrets.YANDEX_STORAGE_BUCKET_MAIN }}
ENDPOINT: ${{ secrets.YANDEX_STORAGE_ENDPOINT }}
run: |
echo "📤 Uploading changed www/ files to MAIN bucket: $BUCKET"
# During release, only index.html, llms.txt and sitemap.xml are modified
# Upload them directly instead of full sync
for file in www/index.html www/llms.txt www/sitemap.xml; do
if [ -f "$file" ]; then
S3_PATH="${file#www/}"
echo " 📄 Uploading: $file → $S3_PATH"
aws s3 cp "$file" "s3://${BUCKET}/${S3_PATH}" \
--endpoint-url ${ENDPOINT}
fi
done
echo "✅ Changed files uploaded to MAIN bucket"
- name: Verify MAIN bucket contents
env:
BUCKET: ${{ secrets.YANDEX_STORAGE_BUCKET_MAIN }}
ENDPOINT: ${{ secrets.YANDEX_STORAGE_ENDPOINT }}
run: |
echo "📁 Contents of MAIN bucket:"
aws s3 ls s3://${BUCKET}/ \
--endpoint-url ${ENDPOINT} \
--recursive \
--human-readable
# ============================================
# 12. Restore original index.html for commit
# ============================================
- name: Restore original index.html
run: |
echo "📄 Restoring original (unminified) www/index.html for commit..."
mv www/index.html.original www/index.html
echo "✅ Original restored"
# ============================================
# 13. Commit changes back to repository
# ============================================
- name: Commit version updates
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
# Add all files first (including gitignored with -f)
# prefetch.js and prefetch.esm.js are in .gitignore — use -f to force add
# dist/ is NOT committed — only used for CDN upload, npm publish, and release artifacts
git add -f prefetch.js prefetch.esm.js
git add package.json package-lock.json README.md www/index.html www/llms.txt www/sitemap.xml
# Check if there are staged changes
if git diff --cached --quiet; then
echo "ℹ️ No changes to commit"
else
git commit -m "chore: release v${VERSION} - update version, SRI hash, sitemap [skip ci]"
# main мог уйти вперёд за время сборки - rebase, чтобы push не падал
git pull --rebase origin main
git push origin main
echo "✅ Changes committed and pushed"
fi
# ============================================
# 14. Create release artifacts
# ============================================
- name: Create release artifacts
env:
SRI_HASH: ${{ steps.sri.outputs.sri_hash }}
ESM_SRI_HASH: ${{ steps.sri.outputs.esm_sri_hash }}
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "📦 Creating release artifacts..."
# Create artifacts directory
mkdir -p artifacts
# Copy minified files
cp dist/prefetch.min.js artifacts/
cp dist/prefetch.esm.min.js artifacts/
cd artifacts
# IIFE version: MD5 + SRI + ZIP
md5sum prefetch.min.js > prefetch.min.js.md5
echo "${SRI_HASH}" > prefetch.min.js.sri
zip prefetch.min.js.zip prefetch.min.js prefetch.min.js.md5 prefetch.min.js.sri
# ESM version: MD5 + SRI + ZIP
md5sum prefetch.esm.min.js > prefetch.esm.min.js.md5
echo "${ESM_SRI_HASH}" > prefetch.esm.min.js.sri
zip prefetch.esm.min.js.zip prefetch.esm.min.js prefetch.esm.min.js.md5 prefetch.esm.min.js.sri
cd ..
echo "✅ Artifacts created:"
ls -la artifacts/
echo ""
echo "📄 IIFE MD5:"
cat artifacts/prefetch.min.js.md5
echo "📄 IIFE SRI:"
cat artifacts/prefetch.min.js.sri
echo ""
echo "📄 ESM MD5:"
cat artifacts/prefetch.esm.min.js.md5
echo "📄 ESM SRI:"
cat artifacts/prefetch.esm.min.js.sri
echo ""
echo "📦 IIFE ZIP contents:"
unzip -l artifacts/prefetch.min.js.zip
echo ""
echo "📦 ESM ZIP contents:"
unzip -l artifacts/prefetch.esm.min.js.zip
# ============================================
# 15. Upload artifacts to release
# ============================================
- name: Upload release assets
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ steps.version.outputs.tag }}
run: |
echo "📤 Uploading assets to release..."
gh release upload "$TAG" \
artifacts/prefetch.min.js.zip \
artifacts/prefetch.esm.min.js.zip \
--clobber
echo "✅ Assets uploaded to release"
- name: Update release notes with SRI hash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SRI_HASH: ${{ steps.sri.outputs.sri_hash }}
TAG: ${{ steps.version.outputs.tag }}
run: |
echo "📝 Updating release notes..."
# Get current release body
CURRENT_BODY=$(gh release view "$TAG" --json body -q '.body')
# Идемпотентность: при повторном запуске не дублируем секцию SRI
if printf '%s' "$CURRENT_BODY" | grep -q "Integrity (SRI) IIFE"; then
echo "ℹ️ Секция SRI уже есть в release notes - пропускаем"
exit 0
fi
# Create notes file with only SRI
{
echo ""
echo "---"
echo ""
echo "## Integrity (SRI) IIFE — prefetch.min.js"
echo ""
echo '```'
echo "${SRI_HASH}"
echo '```'
} > /tmp/release_notes.md
# Combine current body with new notes
echo "${CURRENT_BODY}" > /tmp/full_notes.md
cat /tmp/release_notes.md >> /tmp/full_notes.md
# Update release
gh release edit "$TAG" --notes-file /tmp/full_notes.md
echo "✅ Release notes updated with SRI hash"
# ============================================
# 16. Publish to npm
# ============================================
- name: Remove auth token for OIDC
run: |
# Remove authToken from .npmrc to allow OIDC authentication
sed -i '/_authToken/d' $NPM_CONFIG_USERCONFIG 2>/dev/null || true
# Раньше здесь стоял continue-on-error, который глушил ЛЮБЫЕ ошибки публикации
# (OIDC, сеть, сборка) при уже обновлённом сайте - jsDelivr-ссылки вели в никуда.
# Теперь пропускаем только честный случай "версия уже опубликована"
- name: Publish to npm (OIDC Trusted Publishing)
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
if npm view "@prefetchru/prefetch@${VERSION}" version >/dev/null 2>&1; then
echo "ℹ️ Версия ${VERSION} уже опубликована в npm - пропускаем"
else
npm publish --access public --provenance
fi
# ============================================
# 17. Publish to GitHub Packages
# ============================================
- name: Setup for GitHub Packages
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with:
node-version: '24'
registry-url: 'https://npm.pkg.github.com'
scope: '@prefetch-ru'
- name: Update package name for GitHub Packages
run: npm pkg set name="@prefetch-ru/prefetch"
- name: Publish to GitHub Packages
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ steps.version.outputs.version }}
run: |
if npm view "@prefetch-ru/prefetch@${VERSION}" version --registry=https://npm.pkg.github.com >/dev/null 2>&1; then
echo "ℹ️ Версия ${VERSION} уже опубликована в GitHub Packages - пропускаем"
else
npm publish --access public
fi
# ============================================
# Summary
# ============================================
- name: Release Summary
env:
VERSION: ${{ steps.version.outputs.version }}
VERSION_FOLDER: ${{ steps.version.outputs.version_folder }}
SRI_HASH: ${{ steps.sri.outputs.sri_hash }}
BUCKET_CDN: ${{ secrets.YANDEX_STORAGE_BUCKET_CDN }}
BUCKET_MAIN: ${{ secrets.YANDEX_STORAGE_BUCKET_MAIN }}
run: |
echo ""
echo "=========================================="
echo "🎉 Release v${VERSION} Complete!"
echo "=========================================="
echo ""
echo "📦 Version: ${VERSION}"
echo "🔐 SRI Hash: ${SRI_HASH}"
echo ""
echo "📁 CDN: s3://${BUCKET_CDN}/${VERSION_FOLDER}/prefetch.min.js"
echo "📁 Main: s3://${BUCKET_MAIN}/ (www/ synced)"
echo ""
echo "📄 HTML:"
echo "<script src=\"//prefetch.ru/${VERSION_FOLDER}/prefetch.min.js\""
echo " integrity=\"${SRI_HASH}\""
echo " crossorigin=\"anonymous\"></script>"
echo ""
echo "=========================================="