/** Preview/apply only the onboarding text in one existing cloud function. */ import { recordProgress } from './lib/project-recovery.mjs'; import fs from 'node:fs'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { patchOnboarding } from './onboarding-cloud-patch.mjs'; const stage = process.argv.find(x => x.startsWith('--stage='))?.slice(8) || 'preview'; const out = 'test-results/new-account-20261128'; const privateDir = '.local-backup/new-account-20261128'; const tag = process.argv.find(x => x.startsWith('--tag='))?.slice(6) || ''; assert.match(tag, /^[a-zA-Z0-9-]*$/); const suffix = tag ? '-' + tag : ''; const previewFile = out + '/cloud-prompt-preview' + suffix + '.json'; const beforeFile = privateDir + '/provision-cloud-preview-before' + suffix + '.json'; const candidateFile = privateDir + '/provision-cloud-candidate' + suffix + '.js'; const target = 'VtW1GT93Ax'; const url = 'https://server.fmode.cn/parse/classes/Function/' + target; const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json')); const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey }; const digest = code => createHash('sha256').update(code).digest('hex'); const note = text => recordProgress(process.cwd(), `[${out}] ${text}`); async function read() { const response = await fetch(url, { headers, signal: AbortSignal.timeout(25000) }); assert.ok(response.ok, '云函数只读回验 HTTP ' + response.status); const row = await response.json(); assert.equal(row.name, 'fmode-provisioning'); assert.equal(typeof row.code, 'string'); return row; } let lock, state; const stateFile = out + '/state.json'; const save = () => { fs.writeFileSync(stateFile + '.next', JSON.stringify(state, null, 2)); fs.renameSync(stateFile + '.next', stateFile); }; try { if (stage === 'apply') { lock = fs.openSync(out + '/runner.lock', 'wx'); fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, stage: 'cloud-prompt' })); state = JSON.parse(fs.readFileSync(stateFile)); } if (stage === 'preview') { const bundle = JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json')); const remote = await read(); const candidate = patchOnboarding(remote.code, bundle); const local = fs.readFileSync('cloud/functions/fmode-provisioning.js', 'utf8'); fs.writeFileSync(beforeFile, JSON.stringify(remote, null, 2), { flag: 'wx' }); fs.writeFileSync(candidateFile, candidate, { flag: 'wx' }); fs.writeFileSync('cloud/functions/fmode-provisioning.js', patchOnboarding(local, bundle)); const preview = { target, name: remote.name, originalUpdatedAt: remote.updatedAt, originalVersion: remote.version, oldSha256: digest(remote.code), newSha256: digest(candidate), bundleSha256: bundle.sha256, bundle, oldBytes: Buffer.byteLength(remote.code), newBytes: Buffer.byteLength(candidate) }; fs.writeFileSync(previewFile, JSON.stringify(preview, null, 2), { flag: 'wx' }); note(`已生成可审查候选,目标 ${target},旧源码 ${preview.oldSha256},候选 ${preview.newSha256};仅替换试用提示词及添加通用包元数据,线上其他逻辑来自刚刚回读版本,尚未 PUT。`); console.log(JSON.stringify(preview)); } else if (stage === 'apply') { assert.ok(!state.actions.cloudPrompt?.attempted, '定向更新已有动作记录,先 status 只读核实,不能重复 PUT'); const preview = JSON.parse(fs.readFileSync(previewFile)); assert.equal(preview.target, target, '预览不属于指定目标云函数'); const bundle = JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json')); assert.equal(preview.bundleSha256, bundle.sha256, '预览与当前包摘要不一致,停止更新'); assert.deepEqual(preview.bundle, bundle, '预览与当前包完整元数据不一致,停止更新'); const published = Object.entries(state.actions).find(([key, action]) => key.startsWith('publishBundle') && action.confirmedAt && action.sha256 === bundle.sha256)?.[1]; assert.ok(published && published.receipt?.url === bundle.url, '当前包尚无同摘要公开上传回验'); const asset = await fetch(bundle.url, { signal: AbortSignal.timeout(30000) }); assert.ok(asset.ok, '部署前接入包公开对象不可读'); assert.equal(digest(Buffer.from(await asset.arrayBuffer())), bundle.sha256, '部署前公开包摘要不一致'); const candidate = fs.readFileSync(candidateFile, 'utf8'); assert.equal(digest(candidate), preview.newSha256); const before = await read(); assert.equal(digest(before.code), preview.oldSha256, '线上源码在预览后发生变化,停止覆盖'); assert.equal(candidate, patchOnboarding(before.code, bundle), '候选不是当前线上源码的指定提示词补丁,停止覆盖'); state.actions.cloudPrompt = { attempted: true, at: new Date().toISOString(), target, oldSha256: preview.oldSha256, newSha256: preview.newSha256, bundleSha256: bundle.sha256, previewFile, phase: 'before-put' }; save(); note(`准备对 Function/${target} 执行一次 PUT,候选 ${preview.newSha256},备份 ${beforeFile};不批量更新云函数。`); const response = await fetch(url, { method: 'PUT', headers, body: JSON.stringify({ code: candidate, version: '0.9.2' }), signal: AbortSignal.timeout(30000) }); state.actions.cloudPrompt.putHttp = response.status; save(); const body = await response.json(); fs.writeFileSync(out + '/cloud-prompt-put-response' + suffix + '.json', JSON.stringify(body, null, 2), { flag: 'wx' }); assert.ok(response.ok && !body.error, '定向更新未确认,先 status 核实'); const after = await read(); assert.equal(digest(after.code), preview.newSha256, '云端源码回验不一致'); state.actions.cloudPrompt.confirmedAt = new Date().toISOString(); state.actions.cloudPrompt.receipt = { target, updatedAt: after.updatedAt, version: after.version, sha256: digest(after.code) }; save(); note(`目标云函数已定向更新并回读摘要一致,版本 ${after.version},回执 ${out}/cloud-prompt-put-response${suffix}.json;待从 APK 重新取得提示词并执行下载校验安装。`); console.log(JSON.stringify(state.actions.cloudPrompt.receipt)); } else if (stage === 'status') { const remote = await read(); console.log(JSON.stringify({ target, version: remote.version, updatedAt: remote.updatedAt, sha256: digest(remote.code) })); } else throw Error('未知阶段:' + stage); } catch (error) { if (lock !== undefined && state) { state.lastFailure = { stage: 'cloud-prompt', at: new Date().toISOString(), message: error.message }; save(); note(`未完成:${error.message};恢复先 status,不重复更新。`); } throw error; } finally { if (lock !== undefined) { fs.closeSync(lock); fs.unlinkSync(out + '/runner.lock'); } }