/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
// 创作页前端埋点(WP B-7,方案 §7.1),批量发往 POST /api/creation/events(WP A1-11)。
// - 每 10 秒 / 攒满 50 条 / 页面隐藏或 pagehide 时发送;每批 ≤ 50 条(后端上限);
// - fire-and-forget:发送失败直接丢弃、不重试;任何情况下都不抛异常、不打断页面。
// - 卸载时优先 fetch keepalive(UserAuth 需要 New-Api-User 头,sendBeacon 不能带头),
// fetch 不可用时回退 sendBeacon(尽力而为)。
export const EVENTS_ENDPOINT = '/api/creation/events';
export const EVENTS_MAX_BATCH = 50;
export const EVENTS_FLUSH_MS = 10 * 1000;
// 发送持续失败时队列的上限(超出丢弃最旧的)
export const EVENTS_MAX_QUEUE = 200;
const safe = (fn) => {
try {
const r = fn();
if (r && typeof r.catch === 'function') r.catch(() => {});
return r;
} catch (e) {
return undefined;
}
};
/**
* 可注入传输层的事件队列(单测直接用;页面使用下方默认单例)。
* @param {{
* send: (events: object[]) => Promise|any, 常规发送
* sendOnUnload?: (events: object[]) => any, 页面卸载时发送(同步发起)
* now?: () => number,
* setTimer?: (fn, ms) => any, clearTimer?: (id) => void,
* flushMs?: number, maxBatch?: number, maxQueue?: number,
* }} options
*/
export const createCreationEventQueue = ({
send,
sendOnUnload,
now = () => Date.now(),
setTimer = (fn, ms) => setTimeout(fn, ms),
clearTimer = (id) => clearTimeout(id),
flushMs = EVENTS_FLUSH_MS,
maxBatch = EVENTS_MAX_BATCH,
maxQueue = EVENTS_MAX_QUEUE,
} = {}) => {
let queue = [];
let timer = null;
const takeBatches = () => {
const batches = [];
while (queue.length) batches.push(queue.splice(0, maxBatch));
return batches;
};
const stopTimer = () => {
if (timer !== null) safe(() => clearTimer(timer));
timer = null;
};
const flush = () => {
stopTimer();
takeBatches().forEach((batch) => safe(() => send && send(batch)));
};
const flushOnUnload = () => {
stopTimer();
const fn = sendOnUnload || send;
takeBatches().forEach((batch) => safe(() => fn && fn(batch)));
};
const track = (event, props) => {
safe(() => {
if (!event || typeof event !== 'string') return;
const item = { event, ts: Math.floor(now() / 1000) };
if (props && typeof props === 'object' && !Array.isArray(props)) {
item.props = props;
}
queue.push(item);
if (queue.length > maxQueue) queue = queue.slice(-maxQueue);
if (queue.length >= maxBatch) {
flush();
} else if (timer === null) {
timer = setTimer(() => {
timer = null;
flush();
}, flushMs);
}
});
};
return {
track,
flush,
flushOnUnload,
size: () => queue.length,
};
};
// ---------------------------------------------------------------------------
// 默认单例:常规发送走 API(axios 拦截器带 New-Api-User),卸载时 fetch keepalive
// ---------------------------------------------------------------------------
const readUserId = () => {
try {
const raw = window.localStorage.getItem('user');
const id = raw ? JSON.parse(raw)?.id : null;
return id === undefined || id === null ? '' : String(id);
} catch (e) {
return '';
}
};
const defaultSend = async (events) => {
const { API } = await import('./api');
await API.post(
EVENTS_ENDPOINT,
{ events },
{ skipErrorHandler: true, timeout: 10000 },
);
};
const defaultSendOnUnload = (events) => {
const body = JSON.stringify({ events });
const base =
(typeof window !== 'undefined' && window.__APP_CONFIG__?.SERVER_URL) || '';
const url = `${base}${EVENTS_ENDPOINT}`;
try {
if (typeof fetch === 'function') {
fetch(url, {
method: 'POST',
keepalive: true,
credentials: base ? 'include' : 'same-origin',
headers: {
'Content-Type': 'application/json',
'New-API-User': readUserId(),
},
body,
}).catch(() => {});
return;
}
} catch (e) {
// 落到 sendBeacon
}
try {
if (navigator?.sendBeacon) {
navigator.sendBeacon(url, new Blob([body], { type: 'application/json' }));
}
} catch (e) {
// 忽略
}
};
let defaultQueue = null;
const getDefaultQueue = () => {
if (defaultQueue) return defaultQueue;
defaultQueue = createCreationEventQueue({
send: defaultSend,
sendOnUnload: defaultSendOnUnload,
});
if (typeof window !== 'undefined') {
safe(() => {
window.addEventListener('pagehide', () => defaultQueue.flushOnUnload());
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') defaultQueue.flushOnUnload();
});
});
}
return defaultQueue;
};
/**
* 记录一个创作页事件(事件名需在后端白名单内:studio_view / prompt_focus / model_switch /
* quote_shown / submit / reuse_params / api_code_open / key_created_from_studio)。永不抛异常。
*/
export const trackCreationEvent = (event, props) => {
safe(() => getDefaultQueue().track(event, props));
};
/** 立即发送队列中的事件(如离开创作页时)。 */
export const flushCreationEvents = () => {
safe(() => defaultQueue && defaultQueue.flush());
};