@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
- package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
- package/bundled-assets/skill/LICENSE +21 -0
- package/bundled-assets/skill/README.md +61 -0
- package/bundled-assets/skill/SKILL.md +185 -0
- package/bundled-assets/skill/references/art-directions.md +99 -0
- package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
- package/bundled-assets/skill/references/design-baseline.txt +1 -0
- package/bundled-assets/skill/references/prompt-compiler.md +99 -0
- package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
- package/bundled-assets/skill/references/staged-pptx.md +71 -0
- package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
- package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
- package/bundled-assets/skill/scripts/brand_ref.py +776 -0
- package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
- package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
- package/bundled-assets/skill/scripts/export_images.py +280 -0
- package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
- package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
- package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
- package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
- package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
- package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
- package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
- package/bundled-assets/skill/scripts/render_gradient.py +258 -0
- package/bundled-assets/skill/scripts/slide_brand.py +111 -0
- package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
- package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
- package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
- package/bundled-assets/skill/vendor/README.md +4 -0
- package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
- package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
- package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +11282 -0
- package/lib/index.js +2638 -0
- package/package.json +140 -4
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Optional Oil Slide image CLI for hosts without image tools. Node 22+, no dependencies.
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs/promises';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
const DEFAULT_API_ROOT = 'https://slide.oiloil.org';
|
|
12
|
+
const creditsUrl = root => `${root}/credits`;
|
|
13
|
+
const LOGIN = 'node <skill>/scripts/oiloil-image.mjs login';
|
|
14
|
+
const HELP = `node <skill>/scripts/oiloil-image.mjs image "<说明>" --out slide.png [--ref design.png]
|
|
15
|
+
生图使用 Oil Slide 面板「生图设置」中保存的 Images API 渠道。CLI 可单独设置 OPENAI_BASE_URL、CODEX_PPT_IMAGE_MODEL 和可选 OPENAI_API_KEY。
|
|
16
|
+
login、logout、whoami、balance 仅用于显式操作上游工作区账号。`;
|
|
17
|
+
|
|
18
|
+
class CliError extends Error {
|
|
19
|
+
constructor(code, message, options = {}) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.retryableUnbilled = Boolean(options.retryableUnbilled);
|
|
23
|
+
this.retryDelayMs = Number(options.retryDelayMs) || 0;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const usage = message => { throw new CliError(2, `${message}。用 node <skill>/scripts/oiloil-image.mjs --help 查看用法。`); };
|
|
27
|
+
const quoted = value => JSON.stringify(value);
|
|
28
|
+
export function shellQuote(value, platform = process.platform) {
|
|
29
|
+
const text = String(value);
|
|
30
|
+
return platform === 'win32' ? `'${text.replaceAll("'", "''")}'` : `'${text.replaceAll("'", "'\\''")}'`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
34
|
+
const PREF_VALUES = ['oiloil', 'host'];
|
|
35
|
+
const COMMANDS = ['image', 'balance', 'whoami', 'status', 'pref', 'login', 'logout'];
|
|
36
|
+
|
|
37
|
+
export function parseArgs(argv) {
|
|
38
|
+
const flags = argv.slice(0, argv.includes('--') ? argv.indexOf('--') : argv.length);
|
|
39
|
+
if (!argv.length || flags.includes('--help') || flags.includes('-h')) return { help: true };
|
|
40
|
+
const aliases = { p: 'prompt', s: 'size', o: 'out', r: 'ref', b: 'background' };
|
|
41
|
+
const opts = {}, words = [];
|
|
42
|
+
let command, literal = false;
|
|
43
|
+
for (let i = 0; i < argv.length; i++) {
|
|
44
|
+
const arg = argv[i];
|
|
45
|
+
if (!literal && arg === '--') { literal = true; continue; }
|
|
46
|
+
if (!literal && arg.startsWith('-')) {
|
|
47
|
+
const match = arg.match(/^(?:--([a-z-]+)|-([psorb]))(?:=(.*))?$/s);
|
|
48
|
+
const key = match && (match[1] ?? aliases[match[2]]);
|
|
49
|
+
if (key === 'open') {
|
|
50
|
+
if (match[3] !== undefined) usage('--open 不接受参数值');
|
|
51
|
+
if ('open' in opts) usage('--open 只能写一次');
|
|
52
|
+
opts.open = true;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!['prompt', 'size', 'out', 'ref', 'background', 'timeout'].includes(key)) usage(`不支持选项 ${arg}`);
|
|
56
|
+
if (key in opts) usage(`--${key} 只能写一次${key === 'ref' ? ',参考图仅支持一张' : ''}`);
|
|
57
|
+
const value = match[3] ?? argv[++i];
|
|
58
|
+
if (!value?.trim() || (match[3] === undefined && value.startsWith('-'))) usage(`--${key} 缺少值`);
|
|
59
|
+
opts[key] = value;
|
|
60
|
+
} else if (!command) {
|
|
61
|
+
if (!COMMANDS.includes(arg)) usage(`未知命令 ${arg}`);
|
|
62
|
+
command = arg;
|
|
63
|
+
} else words.push(arg);
|
|
64
|
+
}
|
|
65
|
+
if (!command) usage('缺少 login、logout、whoami、balance、image、status 或 pref 子命令');
|
|
66
|
+
if (command === 'pref') {
|
|
67
|
+
if (Object.keys(opts).length) usage('pref 不接受选项,用法:pref | pref set <oiloil|host> | pref clear');
|
|
68
|
+
if (words.length === 0) {
|
|
69
|
+
opts.action = 'get';
|
|
70
|
+
} else if (words.length === 1 && words[0] === 'clear') {
|
|
71
|
+
opts.action = 'clear';
|
|
72
|
+
} else if (words.length === 2 && words[0] === 'set') {
|
|
73
|
+
if (!PREF_VALUES.includes(words[1])) usage('pref set 只接受 oiloil 或 host');
|
|
74
|
+
opts.action = 'set';
|
|
75
|
+
opts.value = words[1];
|
|
76
|
+
} else {
|
|
77
|
+
usage('pref 用法:pref | pref set <oiloil|host> | pref clear');
|
|
78
|
+
}
|
|
79
|
+
return { command, opts };
|
|
80
|
+
}
|
|
81
|
+
if (command === 'logout') {
|
|
82
|
+
if (words.length || Object.keys(opts).length) usage('logout 不接受参数或选项');
|
|
83
|
+
return { command, opts };
|
|
84
|
+
}
|
|
85
|
+
if (command === 'login') {
|
|
86
|
+
if (words.length || Object.keys(opts).some(key => !['open', 'timeout'].includes(key))) {
|
|
87
|
+
usage('login 只接受 --open 和 --timeout');
|
|
88
|
+
}
|
|
89
|
+
opts.open = Boolean(opts.open);
|
|
90
|
+
opts.timeout = Number(opts.timeout ?? 900000);
|
|
91
|
+
if (!Number.isInteger(opts.timeout) || opts.timeout < 1 || opts.timeout > 900000) usage('--timeout 应为 1..900000 的整数');
|
|
92
|
+
return { command, opts };
|
|
93
|
+
}
|
|
94
|
+
if (command === 'status') {
|
|
95
|
+
if (Object.keys(opts).some(key => !['timeout', 'out'].includes(key))) usage('status 只接受一个幂等键、--out 和 --timeout');
|
|
96
|
+
if (words.length !== 1 || !UUID_RE.test(words[0])) usage('status 需要一个有效的 image 请求幂等键');
|
|
97
|
+
if (opts.out && /[\\/]$/.test(opts.out)) usage('--out 应为文件路径');
|
|
98
|
+
if (opts.out) opts.out = path.resolve(opts.out);
|
|
99
|
+
opts.key = words[0];
|
|
100
|
+
} else if (command === 'balance' || command === 'whoami') {
|
|
101
|
+
if (words.length || Object.keys(opts).some(key => key !== 'timeout')) usage(`${command} 只接受 --timeout`);
|
|
102
|
+
} else {
|
|
103
|
+
if (Object.keys(opts).some(key => key === 'open')) usage('image 不支持 --open');
|
|
104
|
+
if (opts.prompt && words.length) usage('说明文字请用位置参数或 --prompt 中的一种');
|
|
105
|
+
opts.prompt = (opts.prompt ?? words.join(' ')).trim();
|
|
106
|
+
if (!opts.prompt) usage('image 缺少图片说明');
|
|
107
|
+
const size = (opts.size ?? '1K').trim().toUpperCase();
|
|
108
|
+
const dimensions = size.match(/^([1-9]\d*)\s*[X×]\s*([1-9]\d*)$/);
|
|
109
|
+
if (!['1K', '2K', '4K'].includes(size) && !dimensions) usage('--size 应为 1K、2K、4K 或 宽x高');
|
|
110
|
+
if (dimensions) {
|
|
111
|
+
const width = Number(dimensions[1]), height = Number(dimensions[2]);
|
|
112
|
+
const pixels = width * height;
|
|
113
|
+
if (width % 16 !== 0 || height % 16 !== 0 || Math.max(width, height) > 3840
|
|
114
|
+
|| Math.max(width, height) / Math.min(width, height) > 3
|
|
115
|
+
|| pixels < 655360 || pixels > 8294400) {
|
|
116
|
+
usage('自定义 --size 需满足:宽高为 16 的倍数,长边不超过 3840,比例不超过 3:1,总像素为 655360..8294400');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
opts.size = dimensions ? `${dimensions[1]}x${dimensions[2]}` : size;
|
|
120
|
+
if (opts.background !== undefined) {
|
|
121
|
+
const bg = opts.background.trim().toLowerCase();
|
|
122
|
+
opts.background = bg === '透明' ? 'transparent' : bg;
|
|
123
|
+
if (!['transparent', 'opaque', 'auto'].includes(opts.background)) usage('--background 应为 transparent、opaque 或 auto');
|
|
124
|
+
}
|
|
125
|
+
if (opts.out && /[\\/]$/.test(opts.out)) usage('--out 应为文件路径');
|
|
126
|
+
opts.out = path.resolve(opts.out ?? 'assets/generated.png');
|
|
127
|
+
}
|
|
128
|
+
opts.timeout = Number(opts.timeout ?? (command === 'image' ? 250000 : 10000));
|
|
129
|
+
if (!Number.isInteger(opts.timeout) || opts.timeout < 1 || opts.timeout > 900000) usage('--timeout 应为 1..900000 的整数');
|
|
130
|
+
return { command, opts };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function configRootDir(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
134
|
+
const p = platform === 'win32' ? path.win32 : path.posix;
|
|
135
|
+
return platform === 'win32'
|
|
136
|
+
? env.APPDATA || p.join(home, 'AppData', 'Roaming')
|
|
137
|
+
: env.XDG_CONFIG_HOME || p.join(home, '.config');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function slideConfigDir(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
141
|
+
const p = platform === 'win32' ? path.win32 : path.posix;
|
|
142
|
+
return p.join(configRootDir(env, platform, home), 'oil-slide');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function legacyOilConfigDir(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
146
|
+
const p = platform === 'win32' ? path.win32 : path.posix;
|
|
147
|
+
return p.join(configRootDir(env, platform, home), 'oil');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function tokenConfigPath(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
151
|
+
const p = platform === 'win32' ? path.win32 : path.posix;
|
|
152
|
+
return p.join(slideConfigDir(env, platform, home), 'config.json');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function preferencesPath(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
156
|
+
const p = platform === 'win32' ? path.win32 : path.posix;
|
|
157
|
+
return p.join(slideConfigDir(env, platform, home), 'preferences.json');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function legacyPreferencesPath(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
161
|
+
const p = platform === 'win32' ? path.win32 : path.posix;
|
|
162
|
+
return p.join(legacyOilConfigDir(env, platform, home), 'preferences.json');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function readJsonObject(file) {
|
|
166
|
+
let raw;
|
|
167
|
+
try { raw = await fs.readFile(file, 'utf8'); }
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (error.code === 'ENOENT') return { exists: false, data: {} };
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const parsed = JSON.parse(raw);
|
|
174
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
175
|
+
return { exists: true, data: Object.fromEntries(Object.entries(parsed)) };
|
|
176
|
+
}
|
|
177
|
+
return { exists: true, data: {} };
|
|
178
|
+
} catch {
|
|
179
|
+
return { exists: true, data: {} };
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function writeJsonAtomic(file, data, prefix = 'oil-slide') {
|
|
184
|
+
const dir = path.dirname(file);
|
|
185
|
+
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
186
|
+
await fs.chmod(dir, 0o700).catch(() => {});
|
|
187
|
+
const tmp = path.join(dir, `.${prefix}.${process.pid}.${randomUUID()}.tmp`);
|
|
188
|
+
let handle;
|
|
189
|
+
try {
|
|
190
|
+
handle = await fs.open(tmp, 'wx', 0o600);
|
|
191
|
+
await handle.writeFile(`${JSON.stringify(data, null, 2)}\n`, 'utf8');
|
|
192
|
+
await handle.sync();
|
|
193
|
+
await handle.close();
|
|
194
|
+
handle = undefined;
|
|
195
|
+
await fs.chmod(tmp, 0o600).catch(() => {});
|
|
196
|
+
await fs.rename(tmp, file);
|
|
197
|
+
} catch (error) {
|
|
198
|
+
await handle?.close().catch(() => {});
|
|
199
|
+
await fs.rm(tmp, { force: true }).catch(() => {});
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function handlePref(opts) {
|
|
205
|
+
const file = preferencesPath();
|
|
206
|
+
const legacyFile = legacyPreferencesPath();
|
|
207
|
+
const current = await readJsonObject(file);
|
|
208
|
+
const legacy = current.exists ? { exists: false, data: {} } : await readJsonObject(legacyFile);
|
|
209
|
+
const effectiveData = current.exists ? current.data : legacy.data;
|
|
210
|
+
if (opts.action === 'get') {
|
|
211
|
+
const value = Object.hasOwn(effectiveData, 'image_tool') && PREF_VALUES.includes(effectiveData.image_tool)
|
|
212
|
+
? effectiveData.image_tool
|
|
213
|
+
: null;
|
|
214
|
+
if (value === 'oiloil') console.log('当前生图偏好:oiloil(优先使用内置 Oil Slide 生图工具)。');
|
|
215
|
+
else if (value === 'host') console.log('当前生图偏好:host(优先使用宿主自带生图工具)。');
|
|
216
|
+
else console.log('当前生图偏好:未设置(unset)。');
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (opts.action === 'set') {
|
|
220
|
+
await writeJsonAtomic(file, { ...effectiveData, image_tool: opts.value }, 'preferences');
|
|
221
|
+
if (opts.value === 'oiloil') console.log('已保存生图偏好:oiloil(优先使用内置 Oil Slide 生图工具)。');
|
|
222
|
+
else console.log('已保存生图偏好:host(优先使用宿主自带生图工具)。');
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const legacyPresent = (await readJsonObject(legacyFile)).exists;
|
|
226
|
+
if (!current.exists) {
|
|
227
|
+
const hasLegacyPref = Object.hasOwn(legacy.data, 'image_tool') && PREF_VALUES.includes(legacy.data.image_tool);
|
|
228
|
+
if (!hasLegacyPref) {
|
|
229
|
+
console.log('当前生图偏好:未设置(unset),无需清除。');
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const rest = Object.fromEntries(Object.entries(legacy.data).filter(([key]) => key !== 'image_tool'));
|
|
233
|
+
await writeJsonAtomic(file, rest, 'preferences');
|
|
234
|
+
console.log('已清除生图偏好(当前为 unset)。');
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const rest = Object.fromEntries(Object.entries(current.data).filter(([key]) => key !== 'image_tool'));
|
|
238
|
+
if (Object.keys(rest).length === 0 && !legacyPresent) {
|
|
239
|
+
await fs.rm(file, { force: true });
|
|
240
|
+
} else {
|
|
241
|
+
await writeJsonAtomic(file, rest, 'preferences');
|
|
242
|
+
}
|
|
243
|
+
console.log('已清除生图偏好(当前为 unset)。');
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export async function readOilToken(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
247
|
+
if (env.OIL_SLIDE_TOKEN?.trim()) return env.OIL_SLIDE_TOKEN.trim();
|
|
248
|
+
if (env.OIL_TOKEN?.trim()) return env.OIL_TOKEN.trim();
|
|
249
|
+
try {
|
|
250
|
+
const config = JSON.parse(await fs.readFile(tokenConfigPath(env, platform, home), 'utf8'));
|
|
251
|
+
return typeof config?.token === 'string' ? config.token.trim() : '';
|
|
252
|
+
} catch { return ''; }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function apiRoot({ allowDefault = false } = {}) {
|
|
256
|
+
try {
|
|
257
|
+
const url = new URL(process.env.OIL_IMAGE_API?.trim() || DEFAULT_API_ROOT);
|
|
258
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error();
|
|
259
|
+
return url.href.replace(/\/+$/, '');
|
|
260
|
+
} catch {
|
|
261
|
+
if (allowDefault) return DEFAULT_API_ROOT;
|
|
262
|
+
usage('OIL_IMAGE_API 应为不带凭据、查询参数或片段的 HTTP(S) 根地址');
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function safeHttpUrl(value) {
|
|
267
|
+
if (typeof value !== 'string' || !value.trim()) return '';
|
|
268
|
+
try {
|
|
269
|
+
const url = new URL(value.trim());
|
|
270
|
+
return ['http:', 'https:'].includes(url.protocol) ? url.href : '';
|
|
271
|
+
} catch { return ''; }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function openBrowser(url) {
|
|
275
|
+
try {
|
|
276
|
+
const child = process.platform === 'darwin'
|
|
277
|
+
? spawn('open', [url], { detached: true, stdio: 'ignore' })
|
|
278
|
+
: process.platform === 'win32'
|
|
279
|
+
? spawn('rundll32', ['url.dll,FileProtocolHandler', url], { detached: true, stdio: 'ignore' })
|
|
280
|
+
: spawn('xdg-open', [url], { detached: true, stdio: 'ignore' });
|
|
281
|
+
child.on('error', () => {});
|
|
282
|
+
child.unref();
|
|
283
|
+
} catch {
|
|
284
|
+
// Best-effort only; URL is already printed.
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function extractEmail(payload) {
|
|
289
|
+
if (typeof payload?.user?.email === 'string' && payload.user.email.trim()) return payload.user.email.trim();
|
|
290
|
+
if (typeof payload?.email === 'string' && payload.email.trim()) return payload.email.trim();
|
|
291
|
+
return '';
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function extractDeviceError(payload) {
|
|
295
|
+
if (typeof payload?.error === 'string') return payload.error.trim();
|
|
296
|
+
if (typeof payload?.error?.code === 'string') return payload.error.code.trim();
|
|
297
|
+
return '';
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function handleLogin(opts, root) {
|
|
301
|
+
let deadline = Date.now() + opts.timeout;
|
|
302
|
+
let startResp, startRaw;
|
|
303
|
+
try {
|
|
304
|
+
startResp = await fetch(`${root}/api/cli/device`, {
|
|
305
|
+
method: 'POST',
|
|
306
|
+
headers: { 'Content-Type': 'application/json' },
|
|
307
|
+
body: JSON.stringify({ client_name: 'oil-slide-image', platform: process.platform }),
|
|
308
|
+
signal: AbortSignal.timeout(Math.min(opts.timeout, 15000)),
|
|
309
|
+
redirect: 'error',
|
|
310
|
+
});
|
|
311
|
+
startRaw = await startResp.text();
|
|
312
|
+
} catch {
|
|
313
|
+
throw new CliError(6, '连接 Oil Slide 登录接口失败或请求超时,请检查网络后重试。');
|
|
314
|
+
}
|
|
315
|
+
if (startResp.status === 429) {
|
|
316
|
+
const retryAfter = startResp.headers.get('retry-after')?.trim();
|
|
317
|
+
const retryHint = retryAfter && /^\d+$/.test(retryAfter) ? `(建议 ${retryAfter}s 后重试)` : '';
|
|
318
|
+
throw new CliError(7, `Oil Slide 登录请求过于频繁(HTTP 429)${retryHint},请稍后重试。`);
|
|
319
|
+
}
|
|
320
|
+
if (!startResp.ok) {
|
|
321
|
+
throw new CliError(7, `Oil Slide 登录初始化失败(HTTP ${startResp.status}),请稍后重试。`);
|
|
322
|
+
}
|
|
323
|
+
let device;
|
|
324
|
+
try { device = JSON.parse(startRaw); }
|
|
325
|
+
catch { throw new CliError(7, 'Oil Slide 登录接口返回了无法解析的响应,请稍后重试。'); }
|
|
326
|
+
|
|
327
|
+
const deviceCode = typeof device?.device_code === 'string' ? device.device_code.trim() : '';
|
|
328
|
+
const userCode = typeof device?.user_code === 'string' ? device.user_code.trim() : '';
|
|
329
|
+
const verificationUri = safeHttpUrl(device?.verification_uri);
|
|
330
|
+
const verificationUriComplete = safeHttpUrl(device?.verification_uri_complete);
|
|
331
|
+
if (!deviceCode || !userCode || (!verificationUri && !verificationUriComplete)) {
|
|
332
|
+
throw new CliError(7, 'Oil Slide 登录接口返回的授权信息不完整,请稍后重试。');
|
|
333
|
+
}
|
|
334
|
+
const expiresIn = typeof device?.expires_in === 'number' && Number.isFinite(device.expires_in) && device.expires_in > 0
|
|
335
|
+
? Math.round(device.expires_in)
|
|
336
|
+
: 900;
|
|
337
|
+
deadline = Math.min(deadline, Date.now() + expiresIn * 1000);
|
|
338
|
+
const initialIntervalMs = typeof device?.interval === 'number' && Number.isFinite(device.interval) && device.interval > 0
|
|
339
|
+
? Math.max(10, Math.round(device.interval * 1000))
|
|
340
|
+
: 5000;
|
|
341
|
+
|
|
342
|
+
const openUrl = verificationUriComplete || verificationUri;
|
|
343
|
+
const lines = [
|
|
344
|
+
'请在浏览器打开以下链接完成 Oil Slide 登录授权:',
|
|
345
|
+
` 登录链接:${openUrl}`,
|
|
346
|
+
` 授权码:${userCode}`,
|
|
347
|
+
];
|
|
348
|
+
if (verificationUri && verificationUri !== openUrl) {
|
|
349
|
+
lines.push(` 备用入口:${verificationUri}`);
|
|
350
|
+
}
|
|
351
|
+
lines.push(`等待浏览器确认(${Math.round(expiresIn / 60)} 分钟内有效)...`);
|
|
352
|
+
console.log(lines.join('\n'));
|
|
353
|
+
if (opts.open) openBrowser(openUrl);
|
|
354
|
+
|
|
355
|
+
let intervalMs = initialIntervalMs;
|
|
356
|
+
while (true) {
|
|
357
|
+
const remainingBeforeSleep = deadline - Date.now();
|
|
358
|
+
if (remainingBeforeSleep <= 0) {
|
|
359
|
+
throw new CliError(6, `登录链接已过期(${Math.round(expiresIn / 60)} 分钟内未完成授权)。请重新运行 login 命令,会生成新的链接。`);
|
|
360
|
+
}
|
|
361
|
+
await delay(Math.min(intervalMs, remainingBeforeSleep));
|
|
362
|
+
const remaining = deadline - Date.now();
|
|
363
|
+
if (remaining <= 0) {
|
|
364
|
+
throw new CliError(6, `登录链接已过期(${Math.round(expiresIn / 60)} 分钟内未完成授权)。请重新运行 login 命令,会生成新的链接。`);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
let pollResp, pollRaw;
|
|
368
|
+
try {
|
|
369
|
+
pollResp = await fetch(`${root}/api/cli/token`, {
|
|
370
|
+
method: 'POST',
|
|
371
|
+
headers: { 'Content-Type': 'application/json' },
|
|
372
|
+
body: JSON.stringify({ device_code: deviceCode }),
|
|
373
|
+
signal: AbortSignal.timeout(Math.min(15000, Math.max(1000, remaining))),
|
|
374
|
+
redirect: 'error',
|
|
375
|
+
});
|
|
376
|
+
pollRaw = await pollResp.text();
|
|
377
|
+
} catch {
|
|
378
|
+
throw new CliError(6, '轮询 Oil Slide 登录状态失败或请求超时,请检查网络后重新运行 login 命令。');
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
let data = null;
|
|
382
|
+
try { data = JSON.parse(pollRaw); } catch { data = null; }
|
|
383
|
+
|
|
384
|
+
if (pollResp.ok) {
|
|
385
|
+
const token = typeof data?.token === 'string' ? data.token.trim() : '';
|
|
386
|
+
if (!token) throw new CliError(7, 'Oil Slide 登录接口未返回有效令牌,请稍后重试。');
|
|
387
|
+
const configFile = tokenConfigPath();
|
|
388
|
+
await writeJsonAtomic(configFile, { token }, 'config');
|
|
389
|
+
const email = extractEmail(data);
|
|
390
|
+
console.log(`Oil Slide 登录成功${email ? `(${email})` : ''}。凭据已保存到 ${quoted(configFile)},可在 ${creditsUrl(root)} 查看余额或管理设备。`);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (pollResp.status === 400) {
|
|
395
|
+
const errCode = extractDeviceError(data);
|
|
396
|
+
if (errCode === 'authorization_pending') continue;
|
|
397
|
+
if (errCode === 'slow_down') {
|
|
398
|
+
if (typeof data?.interval === 'number' && Number.isFinite(data.interval) && data.interval > 0) {
|
|
399
|
+
intervalMs = Math.max(intervalMs + 1, Math.round(data.interval * 1000));
|
|
400
|
+
} else {
|
|
401
|
+
intervalMs += initialIntervalMs >= 1000 ? 5000 : Math.max(50, initialIntervalMs);
|
|
402
|
+
}
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if (errCode === 'access_denied') {
|
|
406
|
+
throw new CliError(5, 'Oil Slide 登录授权已被拒绝。如需使用,请重新运行 login 命令。');
|
|
407
|
+
}
|
|
408
|
+
if (errCode === 'expired_token') {
|
|
409
|
+
throw new CliError(5, 'Oil Slide 授权码已过期,请重新运行 login 命令。');
|
|
410
|
+
}
|
|
411
|
+
throw new CliError(7, `Oil Slide 登录状态返回异常(HTTP 400${errCode ? `: ${errCode}` : ''}),请重新运行 login 命令。`);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (pollResp.status === 429) {
|
|
415
|
+
const retryAfter = pollResp.headers.get('retry-after')?.trim();
|
|
416
|
+
if (retryAfter && /^\d+$/.test(retryAfter)) {
|
|
417
|
+
intervalMs = Math.max(intervalMs, Number(retryAfter) * 1000);
|
|
418
|
+
} else {
|
|
419
|
+
intervalMs += initialIntervalMs >= 1000 ? 5000 : Math.max(50, initialIntervalMs);
|
|
420
|
+
}
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
throw new CliError(7, `Oil Slide 登录状态查询失败(HTTP ${pollResp.status}),请稍后重试。`);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async function handleLogout(root) {
|
|
429
|
+
const file = tokenConfigPath();
|
|
430
|
+
const { exists, data } = await readJsonObject(file);
|
|
431
|
+
if (!exists) {
|
|
432
|
+
console.log(`当前本机未保存 Oil Slide 登录凭据。如需撤销已有设备授权,请前往 ${creditsUrl(root)}。`);
|
|
433
|
+
} else {
|
|
434
|
+
const rest = Object.fromEntries(Object.entries(data).filter(([key]) => key !== 'token'));
|
|
435
|
+
if (Object.keys(rest).length === 0) {
|
|
436
|
+
await fs.rm(file, { force: true });
|
|
437
|
+
} else {
|
|
438
|
+
await writeJsonAtomic(file, rest, 'config');
|
|
439
|
+
}
|
|
440
|
+
console.log(`已清除本机保存的 Oil Slide 登录凭据。如需撤销该设备授权,请前往 ${creditsUrl(root)} 操作。`);
|
|
441
|
+
}
|
|
442
|
+
if (process.env.OIL_SLIDE_TOKEN?.trim() || process.env.OIL_TOKEN?.trim()) {
|
|
443
|
+
console.log('提示:当前环境变量中仍设置了生图令牌,本次仅清除了本地配置文件。');
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async function renderImage(opts) {
|
|
448
|
+
const script = fileURLToPath(new URL('../vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py', import.meta.url));
|
|
449
|
+
const size = ({ '1K': '1024x1024', '2K': '2048x2048', '4K': '3840x2160' })[opts.size] ?? opts.size;
|
|
450
|
+
const args = [script, opts.ref ? 'edit' : 'generate', '--prompt', opts.prompt,
|
|
451
|
+
'--size', size, '--out', opts.out, '--timeout', String(opts.timeout / 1000)];
|
|
452
|
+
if (opts.ref) args.push('--image', opts.ref);
|
|
453
|
+
if (opts.background) args.push('--background', opts.background);
|
|
454
|
+
return new Promise((resolve, reject) => {
|
|
455
|
+
const child = spawn(process.env.OIL_SLIDE_PYTHON || (process.platform === 'win32' ? 'python' : 'python3'), args, {stdio: 'inherit'});
|
|
456
|
+
child.once('error', () => reject(new CliError(1, '未找到 Python,请安装 Python 3.10+、Pillow 和 requests。')));
|
|
457
|
+
child.once('exit', code => resolve(code ?? 1));
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
462
|
+
try {
|
|
463
|
+
const parsed = parseArgs(argv);
|
|
464
|
+
if (parsed.help) { console.log(HELP); return 0; }
|
|
465
|
+
const { command, opts } = parsed;
|
|
466
|
+
if (command === 'image') return await renderImage(opts);
|
|
467
|
+
if (command === 'status') throw new CliError(2, '自定义渠道按请求直接返回图片。');
|
|
468
|
+
if (command === 'pref') { await handlePref(opts); return 0; }
|
|
469
|
+
if (command === 'logout') { await handleLogout(apiRoot({allowDefault: true})); return 0; }
|
|
470
|
+
const root = apiRoot();
|
|
471
|
+
if (command === 'login') { await handleLogin(opts, root); return 0; }
|
|
472
|
+
const token = await readOilToken();
|
|
473
|
+
if (!token) throw new CliError(3, `尚未登录 Oil Slide。可运行 ${LOGIN} 登录,账户页面为 ${creditsUrl(root)}。`);
|
|
474
|
+
const response = await fetch(`${root}/v1/credits`, {headers: {Authorization: `Bearer ${token}`},
|
|
475
|
+
signal: AbortSignal.timeout(opts.timeout), redirect: 'error'});
|
|
476
|
+
if (!response.ok) throw new CliError(7, `Oil Slide 账号查询失败(HTTP ${response.status})`);
|
|
477
|
+
const result = await response.json();
|
|
478
|
+
const email = extractEmail(result);
|
|
479
|
+
if (command === 'balance' && !Number.isFinite(result?.balance)) throw new CliError(7, '账号未返回有效余额。');
|
|
480
|
+
console.log(command === 'balance' ? `Oil Slide 余额:${result.balance} 积分${email ? `(账号:${email})` : ''}。`
|
|
481
|
+
: `当前登录 Oil Slide 账号:${email || '已登录'}${Number.isFinite(result.balance) ? `(余额:${result.balance} 积分)` : ''}。`);
|
|
482
|
+
return 0;
|
|
483
|
+
} catch (error) {
|
|
484
|
+
console.error(error instanceof CliError ? error.message : '操作失败,请检查路径、设置或网络。');
|
|
485
|
+
return error instanceof CliError ? error.code : 1;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const real = file => fs.realpath(file).catch(() => path.resolve(file));
|
|
490
|
+
if (process.argv[1] && await real(process.argv[1]) === await real(fileURLToPath(import.meta.url))) {
|
|
491
|
+
process.exitCode = await main();
|
|
492
|
+
}
|