/** Surgical source transform shared by local preview and the single-function deployment. */ import fs from 'node:fs'; import assert from 'node:assert/strict'; import vm from 'node:vm'; export const BEGIN = '// FMODE_SELF_HOSTED_ONBOARDING_BEGIN'; export const END = '// FMODE_SELF_HOSTED_ONBOARDING_END'; export function patchOnboarding(source, bundle) { assert.match(bundle.url, /^https:\/\/s3\.fmode\.cn\//); assert.match(bundle.sha256, /^[a-f0-9]{64}$/); const newline = source.includes('\r\n') ? '\r\n' : '\n'; const helper = fs.readFileSync(new URL('../cloud/onboarding/prompt.js', import.meta.url), 'utf8').trim().replace(/\r?\n/g, newline); const owned = [BEGIN, 'var CONTAINER_ONBOARDING_BUNDLE = ' + JSON.stringify(bundle) + ';', helper, END, ''].join(newline); if (source.includes(BEGIN)) { const start = source.indexOf(BEGIN), end = source.indexOf(END, start); assert.ok(end > start && source.indexOf(BEGIN, start + BEGIN.length) < 0, '已有提示词区域不明确'); source = source.slice(0, start) + owned + source.slice(end + END.length).replace(/^\r?\n/, ''); } else { const anchor = "var CLASS_JOB = 'FmodeProvisionJob';"; assert.equal(source.split(anchor).length, 2, '云函数头部结构发生变化,停止定向更新'); source = source.replace(anchor, owned + newline + anchor); } // 2026-12-03:提示词调用改为携带容器专用凭证与有效期(多行形式,正则匹配) const callRe = /^\s*var instruction = _buildSelfHostedInstruction\(oa\.id,[\s\S]*?CONTAINER_ONBOARDING_BUNDLE\);$/m; /** 提示词数组结尾标记:源码里是 ] . join ( ' 反斜杠n ' ) */ const JOIN_MARK = "].join('" + String.fromCharCode(92) + "n');"; const start = source.indexOf(' var mxPass = derivedPass ||'); /* 旧版内联提示词片段(mxPass + 数组)只做删除;新调用保持原样 */ if (start >= 0) { const end = source.indexOf(JOIN_MARK, start); assert.ok(end > start && source.slice(start, end).includes('【Fmode 接入提示词】'), '原试用提示词片段不匹配,停止更新'); source = source.slice(0, start) + source.slice(end + JOIN_MARK.length); } assert.ok(callRe.test(source), '没有找到已知试用接入分支'); if (!source.includes('onboardingBundle: CONTAINER_ONBOARDING_BUNDLE')) { const marker = " mode: 'onboarding',"; assert.equal(source.split(marker).length, 2, '试用响应结构发生变化'); source = source.replace(marker, marker + newline + ' onboardingBundle: CONTAINER_ONBOARDING_BUNDLE,'); } new vm.Script(source); return source; }