mirror of
https://git.zhongyuan.online/ytke/tap.git
synced 2026-11-24 22:15:18 -08:00
支持自部署需求管理、交付流程与飞书集成
This commit is contained in:
1 parent
4556a5b483
commit
e22b66d9dd
148 files changed
+8300
-6393
No files matched your search
@@ -0,0 +1,49 @@
|
||||
import { DatabaseSync, backup } from 'node:sqlite';
|
||||
import { chmod, link, mkdir, stat, unlink } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
process.umask(0o077);
|
||||
|
||||
const dataDir = resolve(process.env.DATA_DIR || './data');
|
||||
const sourcePath = resolve(dataDir, 'demand-center.sqlite');
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const destination = resolve(process.argv[2] || `${dataDir}/backups/demand-${stamp}.sqlite`);
|
||||
const temporary = `${destination}.${randomUUID()}.tmp`;
|
||||
|
||||
let source;
|
||||
try {
|
||||
if (sourcePath === destination) throw new Error('备份文件不能覆盖正在使用的数据库。');
|
||||
if (!(await stat(sourcePath)).isFile()) throw new Error('数据库文件不存在。');
|
||||
const existing = await stat(destination).catch(error => {
|
||||
if (error.code === 'ENOENT') return null;
|
||||
throw error;
|
||||
});
|
||||
if (existing) throw new Error('目标文件已经存在,请选择新的备份文件名。');
|
||||
|
||||
await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
|
||||
source = new DatabaseSync(sourcePath, { readOnly: true });
|
||||
source.exec('PRAGMA busy_timeout = 5000');
|
||||
await backup(source, temporary);
|
||||
source.close();
|
||||
source = undefined;
|
||||
|
||||
const check = new DatabaseSync(temporary, { readOnly: true });
|
||||
try {
|
||||
const rows = check.prepare('PRAGMA integrity_check').all();
|
||||
if (rows.length !== 1 || rows[0].integrity_check !== 'ok') {
|
||||
throw new Error('备份完整性检查失败。');
|
||||
}
|
||||
} finally {
|
||||
check.close();
|
||||
}
|
||||
await chmod(temporary, 0o600);
|
||||
await link(temporary, destination);
|
||||
await unlink(temporary);
|
||||
process.stdout.write(`${destination}\n`);
|
||||
} catch (error) {
|
||||
if (source) source.close();
|
||||
await unlink(temporary).catch(() => {});
|
||||
process.stderr.write(`备份失败:${error.message}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
if [[ "${SITES_ENV_READY:-}" != "1" ]]; then
|
||||
exec "${script_dir}/sites-env.sh" -- "$0" "$@"
|
||||
fi
|
||||
|
||||
command -v timeout || {
|
||||
echo "build-verified.sh requires GNU timeout." >&2
|
||||
exit 69
|
||||
}
|
||||
|
||||
vinext="${SITES_PROJECT_ROOT}/node_modules/.bin/vinext"
|
||||
if [[ ! -x "${vinext}" ]]; then
|
||||
echo "vinext is unavailable. Run npm run install:ci and wait for it to finish before building." >&2
|
||||
exit 69
|
||||
fi
|
||||
|
||||
echo "Running bounded vinext build..."
|
||||
timeout \
|
||||
--signal=TERM \
|
||||
--kill-after="${SITES_BUILD_KILL_AFTER:-10s}" \
|
||||
"${SITES_BUILD_TIMEOUT:-3m}" \
|
||||
"${vinext}" build
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Generate authenticated Word downloads from the canonical SOP Markdown files.
|
||||
Run with the bundled document Python runtime, then render/inspect all outputs.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from docx import Document
|
||||
from docx.shared import Cm, Pt, RGBColor
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
|
||||
from docx.oxml import OxmlElement
|
||||
from docx.oxml.ns import qn
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / 'content/docs'
|
||||
OUTPUT = ROOT / 'content/word'
|
||||
OUTPUT.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
def plain(text):
|
||||
text = re.sub(r'\[([^\]]+)\]\([^)]*\)', r'\1', text)
|
||||
return text.replace('**', '').replace('`', '').replace('- [ ] ', '□ ').strip()
|
||||
|
||||
|
||||
def style_run(run, bold=False, size=None):
|
||||
run.font.name = 'Arial'
|
||||
run.font.color.rgb = RGBColor(0, 0, 0)
|
||||
run.bold = bold
|
||||
if size:
|
||||
run.font.size = Pt(size)
|
||||
fonts = run._element.get_or_add_rPr().get_or_add_rFonts()
|
||||
fonts.set(qn('w:eastAsia'), 'SimSun')
|
||||
|
||||
|
||||
def add_inline(paragraph, text):
|
||||
text = re.sub(r'\[([^\]]+)\]\([^)]*\)', r'\1', text)
|
||||
parts = re.split(r'(\*\*[^*]+\*\*)', text)
|
||||
for part in parts:
|
||||
bold = part.startswith('**') and part.endswith('**')
|
||||
run = paragraph.add_run(part[2:-2] if bold else part.replace('`', ''))
|
||||
style_run(run, bold=bold)
|
||||
|
||||
|
||||
def initialize(title):
|
||||
doc = Document()
|
||||
for border in doc.styles.element.xpath('.//w:pBdr'):
|
||||
border.getparent().remove(border)
|
||||
for fonts in doc.styles.element.xpath('.//w:rFonts'):
|
||||
for attribute in ['asciiTheme', 'hAnsiTheme', 'eastAsiaTheme', 'cstheme']:
|
||||
fonts.attrib.pop(qn('w:' + attribute), None)
|
||||
section = doc.sections[0]
|
||||
section.page_width = Cm(21)
|
||||
section.page_height = Cm(29.7)
|
||||
section.top_margin = Cm(2)
|
||||
section.bottom_margin = Cm(2)
|
||||
section.left_margin = Cm(2)
|
||||
section.right_margin = Cm(2)
|
||||
section.header_distance = Cm(.8)
|
||||
section.footer_distance = Cm(.8)
|
||||
for grid in section._sectPr.findall(qn('w:docGrid')):
|
||||
section._sectPr.remove(grid)
|
||||
for name in ['Normal', 'Title', 'Heading 1', 'Heading 2', 'Heading 3', 'Heading 4']:
|
||||
style = doc.styles[name]
|
||||
style.font.name = 'Arial'
|
||||
style.font.color.rgb = RGBColor(0, 0, 0)
|
||||
style._element.get_or_add_rPr().get_or_add_rFonts().set(qn('w:eastAsia'), 'SimSun')
|
||||
style.paragraph_format.space_before = Pt(0)
|
||||
style.paragraph_format.space_after = Pt(6)
|
||||
style.paragraph_format.line_spacing = 1.2
|
||||
snap = OxmlElement('w:snapToGrid'); snap.set(qn('w:val'), '0'); style._element.get_or_add_pPr().append(snap)
|
||||
doc.styles['Normal'].font.size = Pt(10.5)
|
||||
doc.styles['Normal'].paragraph_format.widow_control = True
|
||||
doc.styles['Title'].font.size = Pt(22)
|
||||
doc.styles['Title'].paragraph_format.space_after = Pt(16)
|
||||
for name, size in [('Heading 1', 16), ('Heading 2', 13), ('Heading 3', 11.5), ('Heading 4', 11)]:
|
||||
doc.styles[name].font.size = Pt(size)
|
||||
doc.styles[name].font.bold = True
|
||||
doc.styles[name].paragraph_format.keep_with_next = True
|
||||
doc.styles[name].paragraph_format.space_before = Pt(14)
|
||||
doc.styles[name].paragraph_format.space_after = Pt(7)
|
||||
title_paragraph = doc.add_paragraph(style='Title')
|
||||
style_run(title_paragraph.add_run(title), size=22)
|
||||
intro = doc.add_paragraph('可使用 Word 或 WPS 填写。填写完成后上传到需求记录,或通过系统关联文档链接。' if '模板' in title else '本规范用于明确需求、开发、验收与发布过程中的职责和交付要求。配套模板可在系统“流程与规范”中查看。')
|
||||
intro.paragraph_format.space_after = Pt(14)
|
||||
footer = section.footer.paragraphs[0]
|
||||
footer.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
||||
style_run(footer.add_run('第 '), size=9)
|
||||
field = OxmlElement('w:fldSimple'); field.set(qn('w:instr'), 'PAGE'); footer._p.append(field)
|
||||
style_run(footer.add_run(' 页'), size=9)
|
||||
doc.core_properties.author = '需有序'
|
||||
doc.core_properties.title = title
|
||||
doc.core_properties.subject = '业务协作模板' if '模板' in title else '软件开发流程管理规范'
|
||||
return doc
|
||||
|
||||
|
||||
def add_table(doc, lines):
|
||||
rows = [[plain(cell) for cell in line.strip().strip('|').split('|')] for line in lines]
|
||||
rows = [row for row in rows if not all(re.fullmatch(r':?-+:?', cell.replace(' ', '')) for cell in row)]
|
||||
if not rows:
|
||||
return
|
||||
columns = len(rows[0])
|
||||
weights = [max(8, min(34, max(len(row[i]) if i < len(row) else 0 for row in rows))) for i in range(columns)]
|
||||
total = sum(weights)
|
||||
widths = [17 * weight / total for weight in weights]
|
||||
if rows[0] == ['验收编号', '关联功能', '场景/操作', '预期结果', '验收结果', '证据/缺陷编号']:
|
||||
widths = [1.8, 1.8, 3.9, 3.9, 2.2, 3.4]
|
||||
for row in rows[1:]:
|
||||
row[4] = row[4].replace('/', '\n')
|
||||
elif rows[0] == ['日期及文档版本', '变更内容及原因', '影响评估', '调整后的范围及计划', '确认人']:
|
||||
widths = [2.5, 4.3, 3.7, 4.5, 2]
|
||||
rows[0][0] = '日期及\n文档版本'
|
||||
elif rows[0] == ['角色', '主要职责', '主要交付或确认事项']:
|
||||
widths = [3, 7, 7]
|
||||
table = doc.add_table(rows=1, cols=columns)
|
||||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
table.autofit = False
|
||||
for column, width in zip(table.columns, widths):
|
||||
column.width = Cm(width)
|
||||
props = table._tbl.tblPr
|
||||
borders = OxmlElement('w:tblBorders')
|
||||
for edge in ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']:
|
||||
item = OxmlElement('w:' + edge)
|
||||
for key, value in [('val', 'single'), ('sz', '4'), ('color', 'D9D9D9')]:
|
||||
item.set(qn('w:' + key), value)
|
||||
borders.append(item)
|
||||
props.append(borders)
|
||||
for index, row in enumerate(rows):
|
||||
cells = table.rows[0].cells if index == 0 else table.add_row().cells
|
||||
table.rows[index]._tr.get_or_add_trPr().append(OxmlElement('w:cantSplit'))
|
||||
for col, cell in enumerate(cells):
|
||||
cell.width = Cm(widths[col])
|
||||
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
|
||||
cell_props = cell._tc.get_or_add_tcPr()
|
||||
margins = OxmlElement('w:tcMar')
|
||||
for edge in ['top', 'left', 'bottom', 'right']:
|
||||
item = OxmlElement('w:' + edge); item.set(qn('w:w'), '95'); item.set(qn('w:type'), 'dxa'); margins.append(item)
|
||||
cell_props.append(margins)
|
||||
if index == 0:
|
||||
fill = OxmlElement('w:shd'); fill.set(qn('w:fill'), 'E8EFF7'); cell_props.append(fill)
|
||||
para = cell.paragraphs[0]
|
||||
para.paragraph_format.line_spacing = 1.25
|
||||
para.paragraph_format.space_after = Pt(3)
|
||||
para.paragraph_format.space_before = Pt(3)
|
||||
value = row[col] if col < len(row) else ''
|
||||
style_run(para.add_run(value), bold=index == 0, size=9.5)
|
||||
if index == 0 or (len(value) < 8 and columns > 2):
|
||||
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
if index == 0:
|
||||
repeat = OxmlElement('w:tblHeader'); table.rows[0]._tr.get_or_add_trPr().append(repeat)
|
||||
doc.add_paragraph().paragraph_format.space_after = Pt(2)
|
||||
|
||||
|
||||
def build(path):
|
||||
source = path.read_text()
|
||||
lines = source.splitlines()
|
||||
title = plain(lines[0].lstrip('# '))
|
||||
title = re.sub(r'^附件\d+[::]\s*', '', title)
|
||||
doc = initialize(title)
|
||||
fenced = False
|
||||
index = 1
|
||||
while index < len(lines):
|
||||
line = lines[index]
|
||||
stripped = line.strip()
|
||||
if stripped.startswith('```'):
|
||||
fenced = not fenced; index += 1; continue
|
||||
if not stripped:
|
||||
index += 1; continue
|
||||
if not fenced and stripped.startswith('|'):
|
||||
group = []
|
||||
while index < len(lines) and lines[index].strip().startswith('|'):
|
||||
group.append(lines[index]); index += 1
|
||||
add_table(doc, group); continue
|
||||
heading = re.match(r'^(#{2,5})\s+(.+)$', stripped)
|
||||
if heading:
|
||||
doc.add_heading(plain(heading[2]), min(len(heading[1]) - 1, 4))
|
||||
elif fenced and (re.match(r'^[一二三四五六七八九十]+、', stripped) or (stripped.startswith('【') and stripped.endswith('】'))):
|
||||
doc.add_heading(plain(stripped.strip('【】')), 2)
|
||||
else:
|
||||
text = stripped
|
||||
if text.startswith('> '):
|
||||
text = text[2:]
|
||||
if text.startswith('- [ ] '):
|
||||
text = '□ ' + text[6:]
|
||||
elif text.startswith('- '):
|
||||
text = '• ' + text[2:]
|
||||
if fenced and text.endswith(':'):
|
||||
text += '【填写】'
|
||||
paragraph = doc.add_paragraph()
|
||||
add_inline(paragraph, text)
|
||||
if fenced and line.startswith(' '):
|
||||
paragraph.paragraph_format.left_indent = Cm(.5)
|
||||
paragraph.paragraph_format.space_after = Pt(7)
|
||||
elif fenced:
|
||||
paragraph.paragraph_format.space_after = Pt(6)
|
||||
index += 1
|
||||
destination = OUTPUT / (path.stem + '.docx')
|
||||
doc.save(destination)
|
||||
return {'source': path.name, 'sourceSha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'file': destination.name, 'fileSha256': hashlib.sha256(destination.read_bytes()).hexdigest()}
|
||||
|
||||
|
||||
manifest = [build(path) for path in sorted(SOURCE.glob('*.md'))]
|
||||
assert len(manifest) == 8
|
||||
(OUTPUT / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
|
||||
print(json.dumps({'generated': len(manifest), 'directory': str(OUTPUT)}, ensure_ascii=False))
|
||||
@@ -1,16 +0,0 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function readExecutionProfile() {
|
||||
let settings;
|
||||
try {
|
||||
settings = JSON.parse(readFileSync(new URL("../.sites-runtime/execution-profile.json", import.meta.url), "utf8"));
|
||||
} catch (error) {
|
||||
// Clean clones and remote builds have no checkout-local selection.
|
||||
if (error.code === "ENOENT") return "portable";
|
||||
throw error;
|
||||
}
|
||||
if (!["managed-linux", "portable"].includes(settings?.executionProfile)) {
|
||||
throw new Error("Invalid local execution profile; rerun the Sites plugin's configure-execution-profile.mjs.");
|
||||
}
|
||||
return settings.executionProfile;
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { accessSync, constants } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { projectRoot } from "./sites-env.mjs";
|
||||
import { readExecutionProfile } from "./execution-profile.mjs";
|
||||
|
||||
if (!process.env.npm_execpath) {
|
||||
throw new Error("Run this installer with npm run install:ci.");
|
||||
}
|
||||
|
||||
if (![
|
||||
"SHARP_IGNORE_GLOBAL_LIBVIPS",
|
||||
"SHARP_FORCE_GLOBAL_LIBVIPS",
|
||||
"npm_config_build_from_source",
|
||||
"NPM_CONFIG_BUILD_FROM_SOURCE",
|
||||
].some((key) => key in process.env)) {
|
||||
process.env.SHARP_IGNORE_GLOBAL_LIBVIPS = "1";
|
||||
}
|
||||
|
||||
if (readExecutionProfile() === "managed-linux") {
|
||||
const result = spawnSync("bash", [path.join(projectRoot, "scripts/install-ci.sh")], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
// Invoke npm's JavaScript entrypoint, avoiding platform-specific shell shims.
|
||||
const installed = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
process.env.npm_execpath, "ci", "--prefix", projectRoot, "--workspaces=false",
|
||||
"--include=dev", "--include=optional", "--prefer-offline", "--no-audit", "--no-fund",
|
||||
],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
if (installed.error) throw installed.error;
|
||||
if (installed.status !== 0) process.exit(installed.status ?? 1);
|
||||
|
||||
try {
|
||||
accessSync(
|
||||
path.join(
|
||||
projectRoot, "node_modules", ".bin",
|
||||
process.platform === "win32" ? "vinext.cmd" : "vinext",
|
||||
),
|
||||
process.platform === "win32" ? constants.F_OK : constants.X_OK,
|
||||
);
|
||||
} catch {
|
||||
console.error("npm ci exited successfully but the local vinext executable is unavailable.");
|
||||
process.exitCode = 69;
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
if [[ "${SITES_ENV_READY:-}" != "1" ]]; then
|
||||
exec "${script_dir}/sites-env.sh" -- "$0" "$@"
|
||||
fi
|
||||
|
||||
command -v flock || {
|
||||
echo "install-ci.sh requires Linux flock." >&2
|
||||
exit 69
|
||||
}
|
||||
command -v timeout || {
|
||||
echo "install-ci.sh requires GNU timeout." >&2
|
||||
exit 69
|
||||
}
|
||||
command -v curl || {
|
||||
echo "install-ci.sh requires curl for the locked-tarball preflight." >&2
|
||||
exit 69
|
||||
}
|
||||
command -v sha256sum || {
|
||||
echo "install-ci.sh requires sha256sum for cache and install verification." >&2
|
||||
exit 69
|
||||
}
|
||||
|
||||
runtime_root="${SITES_RUNTIME_ROOT:-${SITES_PROJECT_ROOT}/.sites-runtime}"
|
||||
expected_home="${runtime_root}/home"
|
||||
expected_cache="${runtime_root}/npm-cache"
|
||||
|
||||
echo "[sites] validating writable install environment"
|
||||
if [[ "${HOME}" != "${expected_home}" ]]; then
|
||||
echo "Expected HOME=${expected_home}, got HOME=${HOME}." >&2
|
||||
exit 78
|
||||
fi
|
||||
actual_cache="$(npm --prefix "${SITES_PROJECT_ROOT}" --workspaces=false config get cache)"
|
||||
if [[ "${actual_cache}" != "${expected_cache}" ]]; then
|
||||
echo "Expected npm cache ${expected_cache}, got ${actual_cache}." >&2
|
||||
exit 78
|
||||
fi
|
||||
touch "${HOME}/.sites-write-test" "${expected_cache}/.sites-write-test"
|
||||
rm -f "${HOME}/.sites-write-test" "${expected_cache}/.sites-write-test"
|
||||
echo "[sites] environment passed: HOME=${HOME}, cache=${expected_cache}"
|
||||
|
||||
lock_file="${runtime_root}/install.lock"
|
||||
exec 9>"${lock_file}"
|
||||
if ! flock -n 9; then
|
||||
echo "Another dependency install is already running for ${SITES_PROJECT_ROOT}." >&2
|
||||
exit 75
|
||||
fi
|
||||
|
||||
# Catch an installer started outside this helper. Linux exposes both its command
|
||||
# line and working directory through /proc, so avoid broad process-name matches.
|
||||
for process in /proc/[0-9]*; do
|
||||
pid="${process##*/}"
|
||||
[[ "${pid}" != "$$" && "${pid}" != "${PPID}" ]] || continue
|
||||
process_cwd="$(readlink -f "${process}/cwd" || true)"
|
||||
[[ "${process_cwd}" == "${SITES_PROJECT_ROOT}" ]] || continue
|
||||
process_command="$(tr '\0' ' ' <"${process}/cmdline" || true)"
|
||||
if [[ "${process_command}" == *"npm ci"* ]]; then
|
||||
echo "Another npm ci is visible in ${SITES_PROJECT_ROOT}; refusing to overlap installs." >&2
|
||||
exit 75
|
||||
fi
|
||||
done
|
||||
|
||||
lockfile_sha256="$(sha256sum "${SITES_PROJECT_ROOT}/package-lock.json" | awk '{print $1}')"
|
||||
use_seeded_cache=0
|
||||
# Report seed selection separately from package cache hits or downloads.
|
||||
cache_seed_result=seed_unavailable
|
||||
seed_cache="${SITES_NPM_CACHE_SEED:-}"
|
||||
if [[ -n "${seed_cache}" && -d "${seed_cache}" ]]; then
|
||||
seed_lockfile_sha256="$(cat "${seed_cache}/.sites-lockfile-sha256" || true)"
|
||||
if [[ "${seed_lockfile_sha256}" == "${lockfile_sha256}" ]]; then
|
||||
echo "[sites] restoring image-seeded npm cache"
|
||||
cp -a "${seed_cache}/." "${expected_cache}/"
|
||||
use_seeded_cache=1
|
||||
cache_seed_result=seed_used
|
||||
echo "[sites] image cache seed matched; registry fallback remains available"
|
||||
else
|
||||
cache_seed_result=seed_lockfile_mismatch
|
||||
echo "[sites] image cache seed does not match this lockfile; using the network path"
|
||||
fi
|
||||
fi
|
||||
|
||||
locked_vinext_output="$({ node --input-type=module - "${SITES_PROJECT_ROOT}/package-lock.json" <<'NODE'
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
const lock = JSON.parse(await readFile(process.argv[2], "utf8"));
|
||||
const vinext = lock.packages?.["node_modules/vinext"];
|
||||
if (!vinext?.resolved || !vinext?.integrity) {
|
||||
throw new Error("package-lock.json does not contain a resolved, integrity-pinned vinext tarball");
|
||||
}
|
||||
console.log(vinext.resolved);
|
||||
console.log(vinext.integrity);
|
||||
NODE
|
||||
})" || {
|
||||
echo "Could not read the integrity-pinned vinext tarball from package-lock.json." >&2
|
||||
exit 65
|
||||
}
|
||||
mapfile -t locked_vinext <<<"${locked_vinext_output}"
|
||||
if [[ "${#locked_vinext[@]}" -ne 2 ]]; then
|
||||
echo "Expected exactly one Vinext URL and integrity value from package-lock.json." >&2
|
||||
exit 65
|
||||
fi
|
||||
|
||||
locked_tarball="${locked_vinext[0]}"
|
||||
locked_integrity="${locked_vinext[1]}"
|
||||
|
||||
if [[ "${use_seeded_cache}" == "0" ]]; then
|
||||
registry="$(npm --prefix "${SITES_PROJECT_ROOT}" --workspaces=false config get registry)"
|
||||
preflight_url="$({ node --input-type=module - "${locked_tarball}" "${registry}" <<'NODE'
|
||||
const locked = new URL(process.argv[2]);
|
||||
const registry = new URL(process.argv[3]);
|
||||
if (locked.hostname === "registry.npmjs.org") {
|
||||
locked.protocol = registry.protocol;
|
||||
locked.host = registry.host;
|
||||
locked.pathname = `${registry.pathname.replace(/\/$/, "")}${locked.pathname}`;
|
||||
}
|
||||
process.stdout.write(locked.href);
|
||||
NODE
|
||||
})" || {
|
||||
echo "Could not construct the locked-tarball preflight URL." >&2
|
||||
exit 65
|
||||
}
|
||||
|
||||
preflight_dir="${runtime_root}/preflight"
|
||||
preflight_tarball="${preflight_dir}/vinext.tgz"
|
||||
mkdir -p "${preflight_dir}"
|
||||
|
||||
echo "[sites] downloading the complete locked vinext tarball"
|
||||
curl \
|
||||
--fail \
|
||||
--location \
|
||||
--silent \
|
||||
--show-error \
|
||||
--retry 0 \
|
||||
--connect-timeout 15 \
|
||||
--max-time 120 \
|
||||
--output "${preflight_tarball}" \
|
||||
"${preflight_url}"
|
||||
|
||||
echo "[sites] verifying locked vinext tarball integrity"
|
||||
node --input-type=module - "${preflight_tarball}" "${locked_integrity}" <<'NODE'
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
const [algorithm, expected] = process.argv[3].split("-", 2);
|
||||
if (!algorithm || !expected) {
|
||||
throw new Error(`unsupported integrity value: ${process.argv[3]}`);
|
||||
}
|
||||
const actual = createHash(algorithm)
|
||||
.update(await readFile(process.argv[2]))
|
||||
.digest("base64");
|
||||
if (actual !== expected) {
|
||||
throw new Error(`vinext tarball integrity mismatch for ${algorithm}`);
|
||||
}
|
||||
NODE
|
||||
echo "[sites] network and integrity preflight passed"
|
||||
fi
|
||||
|
||||
echo "[sites] running exactly one bounded npm ci"
|
||||
export NPM_CONFIG_MAXSOCKETS=1
|
||||
export NPM_CONFIG_FETCH_RETRIES=0
|
||||
export NPM_CONFIG_FETCH_TIMEOUT=30000
|
||||
npm_ci_args=(ci --prefix "${SITES_PROJECT_ROOT}" --workspaces=false --include=dev --include=optional --cache "${expected_cache}")
|
||||
if [[ "${use_seeded_cache}" == "1" ]]; then
|
||||
npm_ci_args+=(--prefer-offline)
|
||||
fi
|
||||
timeout \
|
||||
--signal=TERM \
|
||||
--kill-after="${SITES_INSTALL_KILL_AFTER:-15s}" \
|
||||
"${SITES_INSTALL_TIMEOUT:-8m}" \
|
||||
npm "${npm_ci_args[@]}"
|
||||
|
||||
vinext="${SITES_PROJECT_ROOT}/node_modules/.bin/vinext"
|
||||
if [[ ! -x "${vinext}" ]]; then
|
||||
echo "npm ci exited successfully but node_modules/.bin/vinext is unavailable." >&2
|
||||
exit 69
|
||||
fi
|
||||
|
||||
node --input-type=module - "${SITES_PROJECT_ROOT}/node_modules/.sites-install.json" "${lockfile_sha256}" "${cache_seed_result}" <<'NODE'
|
||||
import { constants } from "node:fs";
|
||||
import { open, writeFile } from "node:fs/promises";
|
||||
|
||||
await writeFile(
|
||||
process.argv[2],
|
||||
`${JSON.stringify({
|
||||
lockfile_sha256: process.argv[3],
|
||||
node: process.version,
|
||||
platform: `${process.platform}-${process.arch}`,
|
||||
}, null, 2)}\n`,
|
||||
);
|
||||
// The measured plugin wrapper supplies an existing private file for this attempt.
|
||||
// Cache telemetry must not change the install result or create arbitrary files.
|
||||
const reportPath = process.env.SITES_INSTALL_REPORT_PATH;
|
||||
if (reportPath) {
|
||||
let report;
|
||||
try {
|
||||
report = await open(reportPath, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
if ((await report.stat()).isFile()) {
|
||||
await report.truncate(0);
|
||||
await report.writeFile(`${JSON.stringify({ version: 1, cache_seed: process.argv[4] })}\n`);
|
||||
}
|
||||
} catch {
|
||||
// Leave the decision unavailable rather than inventing seed use or failing setup.
|
||||
} finally {
|
||||
await report?.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
NODE
|
||||
echo "[sites] npm ci passed and vinext is available"
|
||||
@@ -1,216 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
if [[ "${SITES_ENV_READY:-}" != "1" ]]; then
|
||||
exec "${script_dir}/sites-env.sh" -- "$0" "$@"
|
||||
fi
|
||||
|
||||
require_shared=0
|
||||
prepare_only=0
|
||||
for argument in "$@"; do
|
||||
case "${argument}" in
|
||||
--require-shared) require_shared=1 ;;
|
||||
--prepare-store) prepare_only=1 ;;
|
||||
*) echo "Unknown pnpm installation option: ${argument}" >&2; exit 64 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
for tool in flock timeout node; do
|
||||
command -v "${tool}" >/dev/null || { echo "pnpm setup requires Linux flock, GNU timeout, and Node.js." >&2; exit 69; }
|
||||
done
|
||||
cache_seed=decision_unavailable
|
||||
store_scope=unknown
|
||||
store_state=unavailable
|
||||
report_store() {
|
||||
node "${script_dir}/pnpm-install.mjs" --report-store "${cache_seed}" "${store_scope}" "${store_state}" "${prepare_only}"
|
||||
}
|
||||
# Publish preparation failures too; the optional report never decides success.
|
||||
trap 'report_store || true' EXIT
|
||||
|
||||
if [[ -n "${SITES_PNPM_BIN:-}" && -f "${SITES_PNPM_BIN}" && -r "${SITES_PNPM_BIN}" ]]; then
|
||||
pnpm_command=(node "${SITES_PNPM_BIN}")
|
||||
elif [[ "${require_shared}" == 1 ]]; then
|
||||
echo "[sites] the image-pinned pnpm is unavailable" >&2
|
||||
exit 69
|
||||
elif command -v corepack >/dev/null; then
|
||||
# Corepack honors the established project's pin even when PATH has a different
|
||||
# pnpm version. A bare pnpm is used only if Corepack is absent, then verified.
|
||||
pnpm_command=(corepack pnpm)
|
||||
elif command -v pnpm >/dev/null; then
|
||||
pnpm_command=(pnpm)
|
||||
else
|
||||
echo "This pnpm project requires pnpm 11.25.0 or Corepack." >&2
|
||||
exit 69
|
||||
fi
|
||||
|
||||
runtime_root="${SITES_RUNTIME_ROOT:-${SITES_PROJECT_ROOT}/.sites-runtime}"
|
||||
private_store="${runtime_root}/pnpm-store"
|
||||
if [[ "${HOME}" != "${runtime_root}/home" || -L "${private_store}" ]]; then
|
||||
echo "Dependency setup requires a project-owned writable home and pnpm store." >&2
|
||||
exit 78
|
||||
fi
|
||||
# A single Node process owns the regular-file descriptors for both leases.
|
||||
# Closing its input (including this shell exiting) releases the project lock.
|
||||
coproc SITES_INSTALL_LOCKS {
|
||||
node "${script_dir}/pnpm-install.mjs" --hold-install-locks \
|
||||
"${runtime_root}/install.lock" "${SITES_PNPM_SHARED_STORE:-}.seed.lock" \
|
||||
"${SITES_PNPM_STORE_LOCK_TIMEOUT:-30}"
|
||||
}
|
||||
install_lock_pid="${SITES_INSTALL_LOCKS_PID}"
|
||||
install_lock_output="${SITES_INSTALL_LOCKS[0]}"
|
||||
install_lock_input="${SITES_INSTALL_LOCKS[1]}"
|
||||
lock_status=unavailable
|
||||
read -r lock_status <&"${install_lock_output}" || true
|
||||
if [[ "${lock_status}" != locked ]]; then
|
||||
exec {install_lock_input}>&-
|
||||
exec {install_lock_output}<&-
|
||||
wait "${install_lock_pid}" || true
|
||||
if [[ "${lock_status}" == busy ]]; then
|
||||
echo "Another dependency install is already running for ${SITES_PROJECT_ROOT}." >&2
|
||||
exit 75
|
||||
fi
|
||||
echo "Dependency setup requires a regular, writable project install lock." >&2
|
||||
exit 78
|
||||
fi
|
||||
export XDG_CACHE_HOME="${runtime_root}/xdg-cache" XDG_DATA_HOME="${runtime_root}/xdg-data"
|
||||
mkdir -p "${XDG_CACHE_HOME}" "${XDG_DATA_HOME}" || exit 70
|
||||
pnpm_version="$(timeout --signal=TERM --kill-after="${SITES_INSTALL_KILL_AFTER:-15s}" \
|
||||
"${SITES_PNPM_BOOTSTRAP_TIMEOUT:-30s}" "${pnpm_command[@]}" --version)"
|
||||
if [[ "${pnpm_version}" != "11.25.0" ]]; then
|
||||
echo "This project requires pnpm 11.25.0 and its v11 store format." >&2
|
||||
exit 69
|
||||
fi
|
||||
|
||||
can_write_directory() {
|
||||
local probe
|
||||
# access()/test -w can succeed even when a kernel sandbox denies a write.
|
||||
probe="$(mktemp "${1}/.sites-store-probe.XXXXXX" 2>/dev/null)" || return 1
|
||||
rm -f -- "${probe}" 2>/dev/null
|
||||
}
|
||||
|
||||
release_shared_lock() {
|
||||
if [[ "${shared_lock_held:-}" == 1 ]]; then
|
||||
printf '%s\n' release-shared >&"${install_lock_input}"
|
||||
local status
|
||||
read -r status <&"${install_lock_output}" && [[ "${status}" == released ]] || return 70
|
||||
shared_lock_held=0
|
||||
fi
|
||||
}
|
||||
|
||||
acquire_shared_lock() {
|
||||
# The Node holder opens this workspace-controlled entry with no-follow and
|
||||
# nonblocking flags, then verifies a regular file before bounded flock.
|
||||
printf '%s\n' shared >&"${install_lock_input}"
|
||||
local status
|
||||
if read -r status <&"${install_lock_output}" && [[ "${status}" == locked ]]; then
|
||||
shared_lock_held=1
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
writable_store="${private_store}"
|
||||
shared_store="${SITES_PNPM_SHARED_STORE:-}"
|
||||
if [[ "${shared_store}" == "/workspace/.sites-runtime/pnpm-store" &&
|
||||
! -L "${shared_store}" && ! -L "${shared_store%/*}" &&
|
||||
-d "${shared_store%/*/*}" ]]; then
|
||||
# Normal Work already writes this owner's workspace. Narrower profiles must
|
||||
# pass the actual create probe, without widening their permissions.
|
||||
if mkdir -p "${shared_store%/*}" 2>/dev/null &&
|
||||
can_write_directory "${shared_store%/*}" &&
|
||||
acquire_shared_lock; then
|
||||
if [[ ! -L "${shared_store}" && ! -L "${shared_store%/*}" &&
|
||||
( ! -e "${shared_store}" || ( -d "${shared_store}" && ! -L "${shared_store}" && -w "${shared_store}" ) ) ]] &&
|
||||
{ [[ ! -d "${shared_store}" ]] || can_write_directory "${shared_store}"; }; then
|
||||
writable_store="${shared_store}"
|
||||
store_scope=workspace
|
||||
else
|
||||
release_shared_lock
|
||||
fi
|
||||
else
|
||||
release_shared_lock
|
||||
fi
|
||||
fi
|
||||
if [[ "${store_scope}" != workspace ]]; then
|
||||
if [[ "${require_shared}" == 1 ]]; then
|
||||
echo "[sites] the workspace pnpm store is unavailable" >&2
|
||||
exit 69
|
||||
fi
|
||||
store_scope=project
|
||||
fi
|
||||
|
||||
seed="${SITES_PNPM_CACHE_SEED:-}"
|
||||
cache_seed=seed_unavailable
|
||||
if [[ -d "${writable_store}" ]]; then
|
||||
# Never merge a newer image seed into an existing mutable store.
|
||||
store_state=reused
|
||||
cache_seed=not_applicable
|
||||
if [[ -f "${writable_store}/.sites-pnpm-seed-applied.json" ]]; then cache_seed=seed_used; fi
|
||||
else
|
||||
seed_compatible=0
|
||||
if [[ -n "${seed}" && -d "${seed}/v11" ]] && node --input-type=module - "${seed}/.sites-pnpm-seed.json" <<'NODE'
|
||||
import { readFileSync, statSync } from "node:fs";
|
||||
try {
|
||||
const filename = process.argv[2];
|
||||
if (statSync(filename).size > 4096) process.exit(1);
|
||||
const seed = JSON.parse(readFileSync(filename, "utf8"));
|
||||
process.exit(seed.version === 1 && seed.pnpm_version === "11.25.0" &&
|
||||
seed.store_version === "v11" && /^[a-f0-9]{64}$/.test(seed.lockfile_sha256) ? 0 : 1);
|
||||
} catch { process.exit(1); }
|
||||
NODE
|
||||
then seed_compatible=1; fi
|
||||
if [[ "${seed_compatible}" == 1 ]]; then
|
||||
if [[ "${prepare_only}" == 1 ]]; then
|
||||
echo "[sites] copying the image seed into the writable ${store_scope} pnpm store" >&2
|
||||
else
|
||||
echo "[sites] copying the image seed into the writable ${store_scope} pnpm store"
|
||||
fi
|
||||
seed_stage="$(mktemp -d "${writable_store}.seed.XXXXXX")" || exit 70
|
||||
trap 'if [[ -n "${seed_stage:-}" ]]; then rm -rf -- "${seed_stage}"; fi; report_store || true' EXIT
|
||||
timeout --signal=TERM --kill-after="${SITES_INSTALL_KILL_AFTER:-15s}" \
|
||||
"${SITES_PNPM_STORE_PREPARE_TIMEOUT:-60s}" bash -c \
|
||||
'cp -a --no-preserve=ownership "$1/." "$2/" && chmod -R u+rwX "$2"' _ "${seed}" "${seed_stage}" || exit 70
|
||||
cp "${seed}/.sites-pnpm-seed.json" "${seed_stage}/.sites-pnpm-seed-applied.json" || exit 70
|
||||
# An ordinary pnpm command can initialize the store without our seed lock.
|
||||
# Publish without replacing even an empty directory created by that command.
|
||||
mv -T --update=none "${seed_stage}" "${writable_store}" || exit 70
|
||||
if [[ -d "${seed_stage}" ]]; then
|
||||
if [[ -L "${writable_store}" || ! -d "${writable_store}" ]]; then exit 78; fi
|
||||
rm -rf -- "${seed_stage}" || exit 70
|
||||
store_state=reused
|
||||
cache_seed=not_applicable
|
||||
if [[ -f "${writable_store}/.sites-pnpm-seed-applied.json" ]]; then cache_seed=seed_used; fi
|
||||
else
|
||||
store_state=seeded
|
||||
cache_seed=seed_used
|
||||
fi
|
||||
seed_stage=""
|
||||
else
|
||||
mkdir -p "${writable_store}" || exit 70
|
||||
store_state=created
|
||||
fi
|
||||
fi
|
||||
if ! can_write_directory "${writable_store}"; then store_state=unavailable; exit 70; fi
|
||||
release_shared_lock
|
||||
report_store
|
||||
trap - EXIT
|
||||
if [[ "${prepare_only}" == 1 ]]; then exit 0; fi
|
||||
|
||||
# Configuration travels with source without embedding an absolute machine path.
|
||||
# A later restricted session selects a private store before its frozen repair.
|
||||
configured_store=.sites-runtime/pnpm-store
|
||||
if [[ "${store_scope}" == workspace ]]; then
|
||||
configured_store='${SITES_PNPM_SHARED_STORE:-.sites-runtime/pnpm-store}'
|
||||
elif [[ "${runtime_root}" != "${SITES_PROJECT_ROOT}/.sites-runtime" ]]; then
|
||||
configured_store='${SITES_RUNTIME_ROOT:-.sites-runtime}/pnpm-store'
|
||||
fi
|
||||
"${pnpm_command[@]}" config set package-import-method clone-or-copy --location project
|
||||
"${pnpm_command[@]}" config set store-dir "${configured_store}" --location project
|
||||
"${pnpm_command[@]}" config set cache-dir "${configured_store}/policy-cache" --location project
|
||||
|
||||
# CI=true lets native pnpm install rebuild modules whose store moved, without a
|
||||
# prompt, --force, changing the lockfile, or translating the project into npm.
|
||||
CI=true timeout --signal=TERM --kill-after="${SITES_INSTALL_KILL_AFTER:-15s}" \
|
||||
"${SITES_INSTALL_TIMEOUT:-8m}" node "${script_dir}/pnpm-install.mjs" \
|
||||
"${cache_seed}" "${store_scope}" "${store_state}" "${writable_store}" "${pnpm_command[@]}"
|
||||
@@ -1,261 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
accessSync,
|
||||
closeSync,
|
||||
constants,
|
||||
fstatSync,
|
||||
ftruncateSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
writeSync,
|
||||
} from "node:fs";
|
||||
import { constants as osConstants } from "node:os";
|
||||
import path from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const MAX_PACKAGES = 100_000;
|
||||
const CACHE_SEEDS = new Set(["seed_used", "seed_unavailable", "seed_lockfile_mismatch", "decision_unavailable", "not_applicable"]);
|
||||
const STORE_STATES = new Set(["created", "seeded", "reused", "unavailable"]);
|
||||
// The caller may use operational status only for
|
||||
// initial-setup fallback; an established project always retains pnpm. Broad
|
||||
// fetch failures can include TLS/auth errors and stay fatal.
|
||||
const OPERATIONAL_FAILURE_CODES = new Set([
|
||||
"ERR_PNPM_UNEXPECTED_STORE",
|
||||
"ERR_PNPM_UNEXPECTED_VIRTUAL_STORE",
|
||||
"ERR_PNPM_OUTDATED_LOCKFILE",
|
||||
"ERR_PNPM_FROZEN_LOCKFILE_WITH_OUTDATED_LOCKFILE",
|
||||
"ERR_PNPM_NO_LOCKFILE",
|
||||
"ERR_PNPM_FETCH_408",
|
||||
"ERR_PNPM_FETCH_429",
|
||||
"ERR_PNPM_FETCH_500",
|
||||
"ERR_PNPM_FETCH_502",
|
||||
"ERR_PNPM_FETCH_503",
|
||||
"ERR_PNPM_FETCH_504",
|
||||
]);
|
||||
|
||||
// These are pnpm-reported package IDs, not an assertion about network bytes or
|
||||
// image-cache provenance. Do not interpret an installed-tree no-op as 100% reuse.
|
||||
export class InstallProgress {
|
||||
constructor(project) {
|
||||
this.project = path.resolve(project);
|
||||
this.reused = new Set();
|
||||
this.downloaded = new Set();
|
||||
this.complete = false;
|
||||
this.added = undefined;
|
||||
this.invalid = false;
|
||||
}
|
||||
|
||||
accept(event) {
|
||||
if (event?.name === "pnpm:stats" && event.prefix === this.project &&
|
||||
Number.isSafeInteger(event.added) && event.added >= 0) this.added = event.added;
|
||||
if (event?.name === "pnpm:stage" && event.stage === "importing_done" &&
|
||||
event.prefix === this.project) this.complete = true;
|
||||
if (event?.name !== "pnpm:progress" || event.requester !== this.project ||
|
||||
!["fetched", "found_in_store"].includes(event.status)) return;
|
||||
if (typeof event.packageId !== "string" || !event.packageId || event.packageId.length > 4096 ||
|
||||
this.reused.size + this.downloaded.size >= MAX_PACKAGES) {
|
||||
this.invalid = true;
|
||||
return;
|
||||
}
|
||||
if (event.status === "fetched") {
|
||||
this.reused.delete(event.packageId);
|
||||
this.downloaded.add(event.packageId);
|
||||
} else if (!this.downloaded.has(event.packageId)) {
|
||||
this.reused.add(event.packageId);
|
||||
}
|
||||
}
|
||||
|
||||
counts(success) {
|
||||
if (!success || !this.complete || !(this.added > 0) || this.invalid ||
|
||||
this.reused.size + this.downloaded.size === 0) return {};
|
||||
return { packages_reused: this.reused.size, packages_downloaded: this.downloaded.size };
|
||||
}
|
||||
}
|
||||
|
||||
function openReport() {
|
||||
const report = process.env.SITES_INSTALL_REPORT_PATH;
|
||||
if (!report || !constants.O_NOFOLLOW) return undefined;
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(report, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
if (fstatSync(fd).isFile()) return fd;
|
||||
} catch {}
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function writeReport(fd, report) {
|
||||
if (fd === undefined) return;
|
||||
try {
|
||||
const body = `${JSON.stringify(report)}\n`;
|
||||
writeSync(fd, body, 0, "utf8");
|
||||
ftruncateSync(fd, Buffer.byteLength(body));
|
||||
} catch {
|
||||
// Optional telemetry must not change installation behavior or expose its path.
|
||||
}
|
||||
}
|
||||
|
||||
function showLine(line, progress, failure) {
|
||||
let event;
|
||||
try {
|
||||
event = JSON.parse(line);
|
||||
} catch {
|
||||
process.stdout.write(`${line}\n`);
|
||||
return;
|
||||
}
|
||||
progress.accept(event);
|
||||
if (event?.level === "error" && failure.code !== 65) {
|
||||
failure.code = event.name === "pnpm" && OPERATIONAL_FAILURE_CODES.has(event.err?.code)
|
||||
? 70 : 65;
|
||||
}
|
||||
const message = event?.message ?? event?.err?.message;
|
||||
if (event?.name === "pnpm:lifecycle" && typeof event.line === "string") {
|
||||
process.stdout.write(`${event.line}\n`);
|
||||
} else if (typeof message === "string" && ["warn", "error", "info"].includes(event.level)) {
|
||||
const output = event.level === "error" ? process.stderr : process.stdout;
|
||||
output.write(`${message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
async function openLock(filename, waitSeconds) {
|
||||
let fd;
|
||||
try {
|
||||
if (!filename || !constants.O_NOFOLLOW || !constants.O_NONBLOCK) throw new Error("Unsupported lock");
|
||||
fd = openSync(filename, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
|
||||
if (!fstatSync(fd).isFile()) throw new Error("Expected a regular lock file");
|
||||
const child = spawn("flock", ["-w", waitSeconds, "3"], { stdio: ["ignore", "ignore", "ignore", fd] });
|
||||
const code = await new Promise((resolve) => {
|
||||
child.once("error", () => resolve(undefined));
|
||||
child.once("close", resolve);
|
||||
});
|
||||
if (code === 0) return { status: "locked", fd };
|
||||
closeSync(fd);
|
||||
return { status: code === undefined ? "unavailable" : "busy" };
|
||||
} catch {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
}
|
||||
|
||||
async function holdInstallLocks(projectLock, sharedLock, waitSeconds) {
|
||||
// The shell holds both leases through stdin. EOF (including caller exit)
|
||||
// releases the same open file descriptions that flock locked in its child.
|
||||
const requests = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
const project = await openLock(projectLock, "0");
|
||||
let shared;
|
||||
try {
|
||||
process.stdout.write(`${project.status}\n`);
|
||||
for await (const request of requests) {
|
||||
if (request === "shared" && project.fd !== undefined) {
|
||||
shared ??= await openLock(sharedLock, waitSeconds);
|
||||
process.stdout.write(`${shared.status}\n`);
|
||||
} else if (request === "release-shared") {
|
||||
if (shared?.fd !== undefined) closeSync(shared.fd);
|
||||
shared = undefined;
|
||||
process.stdout.write("released\n");
|
||||
} else {
|
||||
process.stdout.write("unavailable\n");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (shared?.fd !== undefined) closeSync(shared.fd);
|
||||
if (project.fd !== undefined) closeSync(project.fd);
|
||||
requests.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const argsIn = process.argv.slice(2);
|
||||
if (argsIn[0] === "--hold-install-locks") {
|
||||
await holdInstallLocks(argsIn[1], argsIn[2], argsIn[3]);
|
||||
return;
|
||||
}
|
||||
if (argsIn[0] === "--report-store") {
|
||||
const [, cacheSeed, storeScope, storeState, stdout] = argsIn;
|
||||
if (!CACHE_SEEDS.has(cacheSeed) || !["project", "workspace", "unknown"].includes(storeScope) ||
|
||||
!STORE_STATES.has(storeState)) { process.exitCode = 64; return; }
|
||||
const report = { version: 1, cache_seed: cacheSeed, store_scope: storeScope, store_state: storeState };
|
||||
const fd = openReport();
|
||||
writeReport(fd, report);
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
if (stdout === "1") process.stdout.write(`${JSON.stringify(report)}\n`);
|
||||
return;
|
||||
}
|
||||
const [cacheSeed, storeScope, storeState, store, executable, ...prefix] = argsIn;
|
||||
if (!CACHE_SEEDS.has(cacheSeed) || !["project", "workspace"].includes(storeScope) ||
|
||||
!STORE_STATES.has(storeState) || storeState === "unavailable" ||
|
||||
!store || !path.isAbsolute(store) || !executable) {
|
||||
process.stderr.write("Invalid pnpm installation arguments.\n");
|
||||
process.exitCode = 64;
|
||||
return;
|
||||
}
|
||||
const fd = openReport();
|
||||
const report = { version: 1, cache_seed: cacheSeed, store_scope: storeScope, store_state: storeState };
|
||||
writeReport(fd, report);
|
||||
const progress = new InstallProgress(process.cwd());
|
||||
const failure = {};
|
||||
const env = { ...process.env };
|
||||
delete env.SITES_INSTALL_REPORT_PATH;
|
||||
const args = [...prefix, "install", "--prod=false", "--ignore-scripts=false",
|
||||
"--frozen-lockfile", "--prefer-offline", "--store-dir", store,
|
||||
"--cache-dir", path.join(store, "policy-cache"), "--fetch-retries=0",
|
||||
"--fetch-timeout=30000", "--network-concurrency=1", "--reporter=ndjson",
|
||||
"--package-import-method=clone-or-copy"];
|
||||
let result = { code: 1, signal: null };
|
||||
let receivedSignal;
|
||||
try {
|
||||
const child = spawn(executable, args, { env, stdio: ["inherit", "pipe", "inherit"] });
|
||||
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
||||
lines.on("line", (line) => showLine(line, progress, failure));
|
||||
// timeout/exec owns the inherited group. Relaying would deliver signals twice.
|
||||
const signalHandlers = ["SIGINT", "SIGHUP", "SIGTERM"].map((signal) => {
|
||||
const handler = () => { receivedSignal ??= signal; };
|
||||
process.on(signal, handler);
|
||||
return [signal, handler];
|
||||
});
|
||||
let spawnError;
|
||||
child.once("error", (error) => { spawnError = error; });
|
||||
result = await new Promise((resolve) => child.once("close", (code, signal) => {
|
||||
resolve({ code: spawnError ? (spawnError.code === "ENOENT" ? 127 : 1) : code, signal });
|
||||
}));
|
||||
for (const [signal, handler] of signalHandlers) process.removeListener(signal, handler);
|
||||
lines.close();
|
||||
result.signal ??= receivedSignal;
|
||||
if (spawnError) {
|
||||
process.stderr.write("Unable to start pnpm.\n");
|
||||
result.code = spawnError.code === "ENOENT" ? 127 : 65;
|
||||
} else if (result.code !== 0 && !result.signal) {
|
||||
result.code = failure.code ?? 65;
|
||||
}
|
||||
if (result.code === 0 && !result.signal) {
|
||||
accessSync("node_modules/.bin/vinext", constants.X_OK);
|
||||
const lock = readFileSync("pnpm-lock.yaml");
|
||||
writeFileSync("node_modules/.sites-install.json", `${JSON.stringify({
|
||||
package_manager: "pnpm@11.25.0",
|
||||
lockfile_sha256: createHash("sha256").update(lock).digest("hex"),
|
||||
node: process.version,
|
||||
platform: `${process.platform}-${process.arch}`,
|
||||
}, null, 2)}\n`);
|
||||
}
|
||||
} catch {
|
||||
process.stderr.write("Dependency setup did not produce a usable Vinext installation.\n");
|
||||
result = { code: 65, signal: receivedSignal ?? null };
|
||||
} finally {
|
||||
Object.assign(report, progress.counts(result.code === 0 && !result.signal));
|
||||
writeReport(fd, report);
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
if (report.packages_reused !== undefined) {
|
||||
process.stdout.write(`[sites] pnpm reused ${report.packages_reused} packages and downloaded ${report.packages_downloaded}\n`);
|
||||
}
|
||||
if (result.code === 0 && !result.signal) process.stdout.write("[sites] dependency setup passed\n");
|
||||
process.exitCode = result.signal ? 128 + (osConstants.signals[result.signal] ?? 0) : result.code ?? 1;
|
||||
if (result.signal) {
|
||||
try { process.kill(process.pid, result.signal); } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();
|
||||
@@ -0,0 +1,10 @@
|
||||
import { cp, mkdir } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
const standalone=resolve('.next/standalone');
|
||||
await mkdir(`${standalone}/.next`,{recursive:true});
|
||||
await Promise.all([
|
||||
cp('public',`${standalone}/public`,{recursive:true}),
|
||||
cp('content',`${standalone}/content`,{recursive:true}),
|
||||
cp('.next/static',`${standalone}/.next/static`,{recursive:true}),
|
||||
]);
|
||||
console.log('Standalone server prepared with page assets and authenticated documents.');
|
||||
@@ -1,23 +0,0 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readExecutionProfile } from "./execution-profile.mjs";
|
||||
|
||||
const [command, ...args] = process.argv.slice(2);
|
||||
if (!["dev", "build"].includes(command)) throw new Error("Expected dev or build.");
|
||||
const managedLinux = readExecutionProfile() === "managed-linux";
|
||||
|
||||
if (managedLinux && command === "build") {
|
||||
const result = spawnSync("bash", [
|
||||
fileURLToPath(new URL("./build-verified.sh", import.meta.url)), ...args,
|
||||
], { stdio: "inherit" });
|
||||
if (result.error) throw result.error;
|
||||
process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
// Import in this process so the preview owner retains its PID and signals.
|
||||
const cli = new URL(managedLinux
|
||||
? "../node_modules/vite/bin/vite.js"
|
||||
: "../node_modules/vinext/dist/cli.js", import.meta.url);
|
||||
process.argv = [process.execPath, fileURLToPath(cli), command,
|
||||
...(!managedLinux && command === "dev" ? ["--port", "5173"] : []), ...args];
|
||||
await import(cli.href);
|
||||
@@ -1,22 +0,0 @@
|
||||
import { mkdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const projectRoot = fileURLToPath(new URL("../", import.meta.url));
|
||||
const runtimeRoot = process.env.SITES_RUNTIME_ROOT || path.join(projectRoot, ".sites-runtime");
|
||||
|
||||
process.env.CLOUDFLARE_CF_FETCH_ENABLED ||= "false";
|
||||
process.env.WRANGLER_SEND_METRICS ||= "false";
|
||||
process.env.WRANGLER_WRITE_LOGS ||= "false";
|
||||
process.env.WRANGLER_LOG_PATH ||= path.join(runtimeRoot, "wrangler/logs");
|
||||
process.env.WRANGLER_REGISTRY_PATH ||= path.join(runtimeRoot, "wrangler/dev-registry");
|
||||
process.env.MINIFLARE_REGISTRY_PATH ||= path.join(runtimeRoot, "wrangler/registry");
|
||||
|
||||
process.chdir(projectRoot);
|
||||
for (const directory of [
|
||||
path.dirname(process.env.WRANGLER_LOG_PATH),
|
||||
process.env.WRANGLER_REGISTRY_PATH,
|
||||
process.env.MINIFLARE_REGISTRY_PATH,
|
||||
]) {
|
||||
mkdirSync(directory, { recursive: true });
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
runtime_root="${SITES_RUNTIME_ROOT:-${project_root}/.sites-runtime}"
|
||||
|
||||
mkdir -p \
|
||||
"${runtime_root}/home" \
|
||||
"${runtime_root}/npm-cache" \
|
||||
"${runtime_root}/xdg-config" \
|
||||
"${runtime_root}/tmp" \
|
||||
"${runtime_root}/wrangler/logs"
|
||||
|
||||
export SITES_ENV_READY=1
|
||||
export SITES_PROJECT_ROOT="${project_root}"
|
||||
export HOME="${runtime_root}/home"
|
||||
export XDG_CONFIG_HOME="${runtime_root}/xdg-config"
|
||||
export TMPDIR="${runtime_root}/tmp"
|
||||
export WRANGLER_WRITE_LOGS=false
|
||||
export WRANGLER_LOG_PATH="${runtime_root}/wrangler/logs"
|
||||
export MINIFLARE_REGISTRY_PATH="${runtime_root}/wrangler/registry"
|
||||
|
||||
# The runtime may provide a global npm cache. Keep the image's read-only Sites
|
||||
# seed separate and make this project's writable cache authoritative.
|
||||
unset NPM_CONFIG_CACHE npm_config_cache || true
|
||||
export npm_config_cache="${runtime_root}/npm-cache"
|
||||
export npm_config_audit=false
|
||||
export npm_config_fund=false
|
||||
export npm_config_update_notifier=false
|
||||
|
||||
# The runtime already supplies the standard HTTP(S)_PROXY variables. Remove
|
||||
# npm-specific aliases so npm 11 does not reinterpret or warn about them.
|
||||
unset \
|
||||
npm_config_proxy \
|
||||
npm_config_http_proxy \
|
||||
npm_config_https_proxy \
|
||||
NPM_CONFIG_PROXY \
|
||||
NPM_CONFIG_HTTP_PROXY \
|
||||
NPM_CONFIG_HTTPS_PROXY \
|
||||
|| true
|
||||
|
||||
if [[ "${1:-}" == "--" ]]; then
|
||||
shift
|
||||
fi
|
||||
|
||||
if [[ "$#" -eq 0 ]]; then
|
||||
echo "usage: scripts/sites-env.sh -- command [args...]" >&2
|
||||
exit 64
|
||||
fi
|
||||
|
||||
cd "${project_root}"
|
||||
exec "$@"
|
||||
@@ -0,0 +1,12 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { access } from 'node:fs/promises';
|
||||
const root=fileURLToPath(new URL('../',import.meta.url));
|
||||
const server=resolve(root,'.next/standalone/server.js');
|
||||
process.env.NODE_ENV='production';
|
||||
process.env.DATA_DIR=resolve(root,process.env.DATA_DIR||'./data');
|
||||
process.env.HOSTNAME ||= '127.0.0.1';
|
||||
process.env.PORT ||= '3000';
|
||||
if(!process.env.APP_URL){console.error('请先在 .env 中设置 APP_URL 和初始管理员配置。');process.exit(1);}
|
||||
try{await access(server);}catch{console.error('尚未生成部署文件,请先执行 npm run build。');process.exit(1);}
|
||||
await import(pathToFileURL(server).href);
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile, readdir } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
const directory=resolve('content/word');
|
||||
const manifest=JSON.parse(await readFile(resolve(directory,'manifest.json'),'utf8'));
|
||||
const sources=(await readdir(resolve('content/docs'))).filter(name=>name.endsWith('.md')).sort();
|
||||
if(JSON.stringify(manifest.map(item=>item.source).sort())!==JSON.stringify(sources))throw new Error('模板源文件列表已变化,请重新生成 Word 模板。');
|
||||
for(const item of manifest){
|
||||
const source=await readFile(resolve('content/docs',item.source));
|
||||
const output=await readFile(resolve(directory,item.file));
|
||||
const digest=bytes=>createHash('sha256').update(bytes).digest('hex');
|
||||
if(digest(source)!==item.sourceSha256||digest(output)!==item.fileSha256)throw new Error('Word 模板与正文不同步,请重新生成:'+item.source);
|
||||
if(output[0]!==0x50||output[1]!==0x4b)throw new Error('Word 模板文件格式无效:'+item.file);
|
||||
}
|
||||
console.log(`Verified ${manifest.length} Word templates against their source documents.`);
|
||||
Reference in new issue
Block a user