Files
2026-10-30 17:43:26 +07:00

315 lines
10 KiB
JavaScript

// Реестр Lua-плагинов: каждый плагин — модуль с несколькими функциями-нодами.
// Метаданные и код хранятся в server/data/plugins.json, исходник дополнительно
// выгружается в server/data/plugins/<id>.lua, чтобы плагины можно было править с диска.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const DATA_DIR = path.join(__dirname, 'data');
const DB_FILE = path.join(DATA_DIR, 'plugins.json');
const SOURCE_DIR = path.join(DATA_DIR, 'plugins');
const plugins = new Map();
const uid = () => `plugin_${crypto.randomUUID()}`;
const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
const safeId = (id) => String(id || '').replace(/[^a-zA-Z0-9._-]+/g, '-').slice(0, 80);
const DEFAULT_PLUGINS = [
{
id: 'plugin_effects',
name: 'Эффекты',
description: 'Готовые анимации для слайдов и элементов. Каждая функция — отдельная нода.',
color: '#fb7185',
code: `-- Promptly plugin: эффекты
-- Каждая функция ниже становится нодой с портами in → out.
-- Пульс: мягко увеличивает элемент и возвращает обратно
function pulse(target, scale)
scale = tonumber(scale) or 1.06
anim.play(target or 'slide', { scale = { 1, scale, 1 } }, { duration = 520 })
end
-- Встряска: короткая серия смещений по X
function shake(target)
target = target or 'slide'
anim.play(target, { x = { 0, -2, 2, -1.4, 1.4, 0 } }, { duration = 440 })
end
-- Каскад: по очереди проявляет элементы, id которых перечислены через запятую
function cascade(ids, delay)
local step = tonumber(delay) or 120
local index = 0
for id in string.gmatch(tostring(ids or ''), '[^,]+') do
anim.fadeIn(id:gsub('^%s+', ''):gsub('%s+$', ''), 360, index * step)
index = index + 1
end
end
`,
},
{
id: 'plugin_counter',
name: 'Счётчик и состояние',
description: 'Логика счётчиков, шагов и голосований через общие переменные vars.',
color: '#34d399',
code: `-- Promptly plugin: счётчик и состояние
-- Возвращаемая таблица добавляется к vars презентации.
-- Увеличить счётчик
function inc(key, amount)
key = tostring(key or 'count')
amount = tonumber(amount) or 1
vars[key] = (tonumber(vars[key]) or 0) + amount
return { [key] = vars[key] }
end
-- Сбросить счётчик
function reset(key)
key = tostring(key or 'count')
vars[key] = 0
return { [key] = 0 }
end
-- Зафиксировать выбранный вариант
function vote(option)
option = tostring(option or 'option')
vars.vote = option
vars.votes = (tonumber(vars.votes) or 0) + 1
return { vote = vars.vote, votes = vars.votes }
end
`,
},
{
id: 'plugin_utils',
name: 'Утилиты',
description: 'Полезные функции: лог, ограничение числа, форматирование подписи.',
color: '#38bdf8',
code: `-- Promptly plugin: утилиты
-- Записать сообщение в консоль докладчика
function log(message)
app.log(tostring(message or ''))
end
-- Ограничить число диапазоном
function clamp(value, min, max)
value = tonumber(value) or 0
min = tonumber(min) or 0
max = tonumber(max) or 1
if value < min then value = min end
if value > max then value = max end
return { clamped = value }
end
-- Быстрая установка переменной
function setVar(key, value)
if key then vars[tostring(key)] = value end
return { [tostring(key or '')] = value }
end
`,
},
{
id: 'plugin_lua_element',
name: 'Lua-элементы',
description: 'Заготовки стилей для кастомного Lua-элемента на холсте.',
color: '#c084fc',
code: `-- Promptly plugin: стили для Lua-элемента
-- Такой код можно вставить в элемент «Lua» на холсте.
-- Он возвращает таблицу style/html/text.
-- Стеклянная карточка
function glass()
return {
style = {
background = 'rgba(15, 23, 42, .72)',
border = '1px solid rgba(129, 140, 248, .45)',
borderRadius = '18px',
boxShadow = '0 18px 44px rgba(0, 0, 0, .35)',
color = '#e2e8f0',
padding = '24px'
},
html = '<b>Стеклянная карточка</b><br><span>Стили заданы в Lua</span>'
}
end
-- Акцентная плашка
function badge()
return {
style = {
background = 'linear-gradient(135deg, #4cc2ff, #a855f7)',
borderRadius = '999px',
color = '#ffffff',
fontWeight = '800',
display = 'flex',
alignItems = 'center',
justifyContent = 'center'
},
text = 'LUA'
}
end
`,
},
];
function normalizePlugin(input = {}) {
const source = input && typeof input === 'object' ? input : {};
const id = str(source.id, '') || uid();
return {
id: safeId(id),
name: str(source.name, '').trim() || 'Без названия',
description: str(source.description, ''),
color: /^#[0-9a-f]{3,8}$/i.test(str(source.color, '')) ? source.color : '#4cc2ff',
code: str(source.code, ''),
createdAt: Number(source.createdAt) || Date.now(),
updatedAt: Number(source.updatedAt) || Date.now(),
};
}
// Разбор Lua-модуля: каждая глобальная (или локальная) функция — нода.
function deriveNodes(code) {
const source = String(code || '');
const nodes = [];
const seen = new Set();
const re = /(?:^|\n)[ \t]*(?:local[ \t]+)?function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\(([^)]*)\)/g;
let match;
while ((match = re.exec(source))) {
const fn = match[1];
if (seen.has(fn)) continue;
seen.add(fn);
const before = source.slice(0, match.index).split('\n').slice(-6);
const comments = [];
for (let i = before.length - 1; i >= 0; i -= 1) {
const line = before[i].trim();
if (!line.startsWith('--')) break;
comments.unshift(line.replace(/^--\s?/, '').trim());
}
// Строка "-- @node Заголовок" задаёт имя ноды, остальные комментарии — описание.
let title = '';
const description = [];
comments.forEach((line) => {
if (/^@node\s+/i.test(line)) title = line.replace(/^@node\s+/i, '').trim();
else if (line) description.push(line);
});
const args = match[2].trim();
const label = title || fn.replace(/_/g, ' ');
nodes.push({
id: fn,
fn,
name: label,
description: description.join(' · '),
args,
ports: { in: 'in', out: 'out' },
});
}
return nodes;
}
function publicPlugin(plugin) {
return {
...plugin,
nodes: deriveNodes(plugin.code),
};
}
function loadFromDisk() {
try {
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.mkdirSync(SOURCE_DIR, { recursive: true });
const raw = fs.readFileSync(DB_FILE, 'utf8');
const arr = JSON.parse(raw);
if (Array.isArray(arr)) {
arr.forEach((item) => {
const plugin = normalizePlugin(item);
plugins.set(plugin.id, plugin);
});
console.log(`[plugins] загружено с диска: ${plugins.size}`);
}
} catch (error) {
if (error.code !== 'ENOENT') console.warn('[plugins] не удалось прочитать реестр:', error.message);
}
if (!plugins.size) {
DEFAULT_PLUGINS.forEach((item) => {
const plugin = normalizePlugin(item);
plugins.set(plugin.id, plugin);
});
writeToDisk();
console.log(`[plugins] создан стартовый реестр: ${plugins.size}`);
}
}
function writeToDisk() {
try {
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.mkdirSync(SOURCE_DIR, { recursive: true });
const list = [...plugins.values()].map(publicPlugin);
const tmp = `${DB_FILE}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(list, null, 2));
fs.renameSync(tmp, DB_FILE);
// Параллельно пишем читаемые .lua-файлы: их удобно держать в git и править в IDE.
const keep = new Set();
list.forEach((plugin) => {
const file = `${safeId(plugin.id)}.lua`;
keep.add(file);
fs.writeFileSync(path.join(SOURCE_DIR, file), plugin.code || '');
});
for (const file of fs.readdirSync(SOURCE_DIR)) {
if (file.endsWith('.lua') && !keep.has(file)) {
try { fs.unlinkSync(path.join(SOURCE_DIR, file)); } catch { /* noop */ }
}
}
} catch (error) {
console.error('[plugins] ошибка записи реестра:', error.message);
}
}
function listPlugins() {
return [...plugins.values()]
.sort((a, b) => a.name.localeCompare(b.name, 'ru'))
.map(publicPlugin);
}
function getPlugin(id) {
const plugin = plugins.get(String(id || ''));
return plugin ? publicPlugin(plugin) : null;
}
function createPlugin(input = {}) {
const plugin = normalizePlugin({ ...input, id: '' });
plugin.id = uid();
plugin.createdAt = Date.now();
plugin.updatedAt = Date.now();
plugins.set(plugin.id, plugin);
writeToDisk();
return publicPlugin(plugin);
}
function updatePlugin(id, input = {}) {
const current = plugins.get(String(id || ''));
if (!current) return null;
const next = normalizePlugin({ ...current, ...input, id: current.id, createdAt: current.createdAt });
next.updatedAt = Date.now();
plugins.set(current.id, next);
writeToDisk();
return publicPlugin(next);
}
function deletePlugin(id) {
const ok = plugins.delete(String(id || ''));
if (ok) writeToDisk();
return ok;
}
loadFromDisk();
module.exports = {
listPlugins,
getPlugin,
createPlugin,
updatePlugin,
deletePlugin,
deriveNodes,
DATA_DIR,
DB_FILE,
SOURCE_DIR,
};