| (() => { |
| 'use strict'; |
|
|
| const root = window; |
| const GUARD_KEY = '__tgCore_bootstrapped_v3'; |
| const CORE_VERSION = '3.1.0'; |
|
|
| const makeToken = () => |
| `tg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`; |
|
|
| |
| if (root[GUARD_KEY] && root.__tgCore) { |
| if (!root.__tgBus) { |
| root.__tgBus = Object.freeze({ |
| emit: (name, detail) => { try { root.__tgCore.emitDom(name, detail); } catch {} }, |
| on: (name, fn, opt) => { |
| try { return root.__tgCore.onDom(name, fn, opt || { passive: true }); } catch { return () => {}; } |
| } |
| }); |
| } |
|
|
| |
| try { |
| root.__tgCore.emitDom('tg:core-reused', { |
| ts: Date.now(), |
| version: root.__tgCore?.version || CORE_VERSION, |
| reused: true |
| }); |
| } catch {} |
| return; |
| } |
|
|
| const deepFreeze = (obj) => { |
| if (!obj || typeof obj !== 'object') return obj; |
| Object.freeze(obj); |
| for (const k of Object.getOwnPropertyNames(obj)) { |
| const v = obj[k]; |
| if (v && typeof v === 'object' && !Object.isFrozen(v)) deepFreeze(v); |
| } |
| return obj; |
| }; |
|
|
| if (!root.__tgCore) { |
| const canon = Object.create(null); |
| const owners = Object.create(null); |
| const state = Object.create(null); |
| const listeners = new Map(); |
| const symbolOwners = Object.create(null); |
| const domForwardGuard = '__tgBusOrigin'; |
|
|
| const bootTs = Date.now(); |
| const instanceId = `core_${bootTs.toString(36)}_${Math.random().toString(36).slice(2, 8)}`; |
|
|
| let debugEnabled = !!root.__TG_DEBUG; |
|
|
| const stableJsonDumps = (value) => { |
| const seen = new WeakSet(); |
| const walk = (v) => { |
| if (v === null || typeof v !== 'object') { |
| if (typeof v === 'bigint') return `${String(v)}n`; |
| if (typeof v === 'function') return `[Function ${v.name || 'anonymous'}]`; |
| if (typeof v === 'symbol') return String(v); |
| return v; |
| } |
| if (seen.has(v)) return '[Circular]'; |
| seen.add(v); |
|
|
| if (Array.isArray(v)) return v.map(walk); |
|
|
| const out = {}; |
| for (const k of Object.keys(v).sort()) out[k] = walk(v[k]); |
| return out; |
| }; |
| return JSON.stringify(walk(value)); |
| }; |
|
|
| const loadJson = (raw, fallback = null) => { |
| if (typeof raw !== 'string') return fallback; |
| try { return JSON.parse(raw); } catch { return fallback; } |
| }; |
|
|
| |
| |
| |
| |
| |
| |
| const registerCanonical = (name, fn, owner = 'unknown', opts = null) => { |
| if (typeof name !== 'string' || !name.trim()) { |
| throw new TypeError('Canonical helper name must be a non-empty string'); |
| } |
| if (typeof fn !== 'function') { |
| throw new TypeError(`Canonical helper ${name} must be a function`); |
| } |
|
|
| const key = name.trim(); |
| const current = canon[key]; |
| const currentOwner = owners[key]; |
|
|
| if (current && current !== fn) { |
| const sameOwner = currentOwner === owner; |
| const allowSameOwnerOverride = !!opts?.allowSameOwnerOverride; |
| const allowExistingNoop = !!opts?.allowExistingNoop; |
|
|
| if (allowExistingNoop) return current; |
| if (sameOwner && allowSameOwnerOverride) { |
| canon[key] = fn; |
| owners[key] = owner; |
| return fn; |
| } |
|
|
| throw new Error( |
| `Duplicate canonical helper blocked: ${key} (owned by ${currentOwner}, attempted by ${owner})` |
| ); |
| } |
|
|
| if (!current) { |
| canon[key] = fn; |
| owners[key] = owner; |
| } |
| return canon[key]; |
| }; |
|
|
| const blockDuplicateUtility = (name, owner = 'unknown') => { |
| const existingOwner = owners[name] || null; |
| if (existingOwner && existingOwner !== owner) { |
| throw new Error( |
| `Duplicate utility symbol blocked: ${name} (canonical owner: ${existingOwner}, attempted by ${owner})` |
| ); |
| } |
| return true; |
| }; |
|
|
| |
| |
| |
| const claimGlobalSymbol = (name, owner = 'unknown', opts = null) => { |
| if (typeof name !== 'string' || !name.trim()) { |
| throw new TypeError('Global symbol name must be a non-empty string'); |
| } |
| const key = name.trim(); |
| const existing = symbolOwners[key]; |
|
|
| if (!existing) { |
| symbolOwners[key] = owner; |
| return true; |
| } |
|
|
| if (existing === owner) return true; |
| if (opts?.allowTakeover === true) { |
| symbolOwners[key] = owner; |
| return true; |
| } |
|
|
| throw new Error( |
| `Global symbol already claimed: ${key} (owner: ${existing}, attempted by: ${owner})` |
| ); |
| }; |
|
|
| const releaseGlobalSymbol = (name, owner = 'unknown') => { |
| const key = String(name || '').trim(); |
| if (!key) return false; |
| const existing = symbolOwners[key]; |
| if (!existing) return false; |
| if (existing !== owner) return false; |
| delete symbolOwners[key]; |
| return true; |
| }; |
|
|
| const createPrivateName = (owner, localName) => |
| `__tg_${String(owner).replace(/[^a-zA-Z0-9_]+/g, '_')}__${String(localName || '').replace(/[^a-zA-Z0-9_]+/g, '_')}`; |
|
|
| |
| const emit = (event, detail = null) => { |
| const evt = String(event || ''); |
| if (!evt) return 0; |
| const set = listeners.get(evt); |
| if (!set || set.size === 0) return 0; |
| let n = 0; |
| for (const fn of set) { |
| try { fn(detail); n++; } catch {} |
| } |
| return n; |
| }; |
|
|
| const on = (event, fn, opts = null) => { |
| if (typeof fn !== 'function') throw new TypeError('listener must be a function'); |
| const evt = String(event || ''); |
| if (!evt) throw new TypeError('event must be a non-empty string'); |
|
|
| let set = listeners.get(evt); |
| if (!set) { |
| set = new Set(); |
| listeners.set(evt, set); |
| } |
|
|
| if (opts?.once) { |
| const onceWrapper = (detail) => { |
| try { fn(detail); } finally { try { off(evt, onceWrapper); } catch {} } |
| }; |
| set.add(onceWrapper); |
| return () => off(evt, onceWrapper); |
| } |
|
|
| set.add(fn); |
| return () => off(evt, fn); |
| }; |
|
|
| const off = (event, fn) => { |
| const evt = String(event || ''); |
| if (!evt) return false; |
| const set = listeners.get(evt); |
| if (!set) return false; |
| const had = set.delete(fn); |
| if (set.size === 0) listeners.delete(evt); |
| return had; |
| }; |
|
|
| |
| const emitDom = (event, detail = null) => { |
| const evt = String(event || ''); |
| if (!evt) return false; |
| try { |
| const token = |
| (detail && typeof detail === 'object' && detail.__tgEventToken) |
| ? detail.__tgEventToken |
| : makeToken(); |
|
|
| const payload = (detail && typeof detail === 'object') |
| ? { ...detail, __tgEventToken: token, [domForwardGuard]: true } |
| : { value: detail, __tgEventToken: token, [domForwardGuard]: true }; |
|
|
| window.dispatchEvent(new CustomEvent(evt, { detail: payload })); |
| return true; |
| } catch { |
| return false; |
| } |
| }; |
|
|
| const onDom = (event, fn, opts = null) => { |
| const evt = String(event || ''); |
| if (!evt || typeof fn !== 'function') return () => {}; |
|
|
| const once = !!opts?.once; |
| const nativeOpts = { |
| passive: (opts?.passive !== false), |
| capture: !!opts?.capture, |
| once |
| }; |
|
|
| const handler = (e) => { |
| try { fn(e?.detail ?? null, e); } catch {} |
| }; |
|
|
| try { |
| window.addEventListener(evt, handler, nativeOpts); |
| return () => { |
| try { window.removeEventListener(evt, handler, nativeOpts); } catch {} |
| }; |
| } catch { |
| return () => {}; |
| } |
| }; |
|
|
| |
| const emitBoth = (event, detail = null) => { |
| const payload = (detail && typeof detail === 'object') |
| ? { ...detail } |
| : { value: detail }; |
|
|
| if (!payload.__tgEventToken) payload.__tgEventToken = makeToken(); |
|
|
| const n = emit(event, payload); |
| emitDom(event, payload); |
| return n; |
| }; |
|
|
| |
| const onAny = (event, fn, opts = null) => { |
| if (typeof fn !== 'function') return () => {}; |
| let lastToken = null; |
|
|
| const offInternal = on(event, (detail) => { |
| const tok = detail && typeof detail === 'object' ? detail.__tgEventToken : null; |
| if (tok && tok === lastToken) return; |
| lastToken = tok || null; |
| fn(detail); |
| }); |
|
|
| const offDom = onDom(event, (detail) => { |
| const tok = detail && typeof detail === 'object' ? detail.__tgEventToken : null; |
| if (tok && tok === lastToken) return; |
| lastToken = tok || null; |
| fn(detail); |
| }, opts); |
|
|
| return () => { try { offInternal(); } catch {} try { offDom(); } catch {} }; |
| }; |
|
|
| const setState = (k, v) => { state[k] = v; return v; }; |
| const getState = (k, fallback = null) => (Object.prototype.hasOwnProperty.call(state, k) ? state[k] : fallback); |
| const snapshotState = () => Object.assign({}, state); |
| const clearState = (k) => { |
| if (typeof k === 'undefined') { |
| for (const key of Object.keys(state)) delete state[key]; |
| return true; |
| } |
| const key = String(k); |
| const had = Object.prototype.hasOwnProperty.call(state, key); |
| if (had) delete state[key]; |
| return had; |
| }; |
|
|
| const debug = (...args) => { |
| try { if (debugEnabled) console.debug('[tgCore]', ...args); } catch {} |
| }; |
| const setDebug = (v) => { debugEnabled = !!v; return debugEnabled; }; |
| const getDebug = () => !!debugEnabled; |
|
|
| |
| const EVENTS = deepFreeze({ |
| PERF_PROFILE: 'tg:perf-profile', |
| SIGNAL_FRESHNESS: 'tg:signal-freshness', |
| REPLY_READY: 'tg:reply-ready', |
| WARMUP_STAGE: 'tg:warmup-stage', |
| NOTIFY_HEALTH: 'tg:notify-health', |
| CORE_READY: 'tg:core-ready', |
| CORE_REUSED: 'tg:core-reused' |
| }); |
|
|
| const knownEventSet = new Set(Object.values(EVENTS)); |
|
|
| const isKnownEventName = (name) => { |
| const s = String(name || ''); |
| return knownEventSet.has(s); |
| }; |
|
|
| const diagnostics = () => ({ |
| version: CORE_VERSION, |
| bootTs, |
| instanceId, |
| canonicals: Object.keys(canon).sort(), |
| owners: Object.assign({}, owners), |
| claimedGlobals: Object.assign({}, symbolOwners), |
| stateKeys: Object.keys(state).sort(), |
| listeners: Array.from(listeners.entries()).map(([k, v]) => ({ event: k, count: v.size })) |
| }); |
|
|
| registerCanonical('load_json', loadJson, 'core-utils'); |
| registerCanonical('stable_json_dumps', stableJsonDumps, 'core-utils'); |
|
|
| root.__tgCore = Object.freeze({ |
| version: CORE_VERSION, |
| bootTs, |
| instanceId, |
|
|
| registerCanonical, |
| blockDuplicateUtility, |
| claimGlobalSymbol, |
| releaseGlobalSymbol, |
| createPrivateName, |
|
|
| getCanonical: (name) => canon[name] || null, |
| getOwner: (name) => owners[name] || null, |
| listCanonicals: () => Object.keys(canon).sort(), |
|
|
| emit, |
| on, |
| off, |
|
|
| emitDom, |
| onDom, |
| emitBoth, |
| onAny, |
|
|
| setState, |
| getState, |
| snapshotState, |
| clearState, |
|
|
| EVENTS, |
| isKnownEventName, |
|
|
| diagnostics, |
|
|
| debug, |
| setDebug, |
| getDebug |
| }); |
| } |
|
|
| root.__tgCoreVersion = CORE_VERSION; |
| root[GUARD_KEY] = true; |
|
|
| |
| if (!root.__tgBus) { |
| root.__tgBus = Object.freeze({ |
| emit: (name, detail) => { try { root.__tgCore.emitDom(name, detail); } catch {} }, |
| on: (name, fn, opt) => { |
| try { return root.__tgCore.onDom(name, fn, opt || { passive: true }); } catch { return () => {}; } |
| } |
| }); |
| } |
|
|
| |
| try { |
| root.__tgCore.emitDom('tg:core-ready', { |
| ts: Date.now(), |
| version: root.__tgCore?.version || CORE_VERSION, |
| instanceId: root.__tgCore?.instanceId || '', |
| bootTs: root.__tgCore?.bootTs || 0 |
| }); |
| } catch {} |
| })(); |