#!/usr/bin/env node import {readFileSync} from 'node:fs'; import {pathToFileURL} from 'node:url'; import * as XLSX from 'xlsx'; import {lessonExportColumns} from '../projects/shared/lesson-export-columns.mjs'; export async function processLessonExport(call){ const job=await call('claim',{});if(!job.jobId)return false; const identity={jobId:job.jobId,lease:job.lease}; try{ if(!job.snapshotReady)await call('snapshot',identity); const sheet=XLSX.utils.json_to_sheet([]);let offset=0,total=Infinity; while(offset{});throw Error('export_job_failed');} } async function main(){ const config=process.env.XIAOSHU_EXPORT_ENV_FILE||'/Users/mac/.config/xiaoshu/legacy-sync-nightly.env',env={...process.env}; for(const line of readFileSync(config,'utf8').split('\n')){const m=line.match(/^(?:export\s+)?(XIAOSHU_[A-Z0-9_]+)=(.*)$/);if(m&&!env[m[1]])env[m[1]]=m[2].replace(/^['"]|['"]$/g,'');} const token=env.XIAOSHU_EXPORT_OPERATOR_TOKEN||env.XIAOSHU_SYNC_OPERATOR_TOKEN;if(!token)throw Error('export_operator_missing'); const base=env.XIAOSHU_EXPORT_GATEWAY_URL||'https://server.xiaoshu.pro/api/functions/xiaoshu/ops/gateway-v3'; const call=async(action,params)=>{const r=await fetch(base,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token,params:{operation:'ops/lessons/export/'+action,...params}}),signal:AbortSignal.timeout(action==='snapshot'?90_000:20_000)});const data=await r.json();if(!r.ok||!data.success)throw Error('export_gateway_'+r.status);return data.data;}; let lastMaintenance=0;let stopped=false;for(const event of ['SIGINT','SIGTERM'])process.on(event,()=>{stopped=true;}); do{try{if(Date.now()-lastMaintenance>86_400_000){await call('maintenance',{});lastMaintenance=Date.now();}await processLessonExport(call);}catch{console.error('导出任务失败,错误状态已回写或将由租约恢复');}if(process.argv.includes('--once'))break;if(!stopped)await new Promise(r=>setTimeout(r,5000));}while(!stopped); } if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)main().catch(()=>{console.error('导出 worker 启动失败,请检查私密配置和权限');process.exitCode=1;});