@lynx-js/lynx-runtime 0.0.0 → 0.0.1

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.
Files changed (54) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +354 -2
  3. package/dist/bts/data.d.ts +1 -0
  4. package/dist/bts/data.js +28 -0
  5. package/dist/bts/events.d.ts +1 -0
  6. package/dist/bts/events.js +57 -0
  7. package/dist/bts/scope.d.ts +1 -0
  8. package/dist/bts/scope.js +129 -0
  9. package/dist/bts/services.d.ts +1 -0
  10. package/dist/bts/services.js +34 -0
  11. package/dist/bts.d.ts +14 -0
  12. package/dist/bts.js +30 -0
  13. package/dist/common/host-types.d.ts +1 -0
  14. package/dist/common/host-types.js +1 -0
  15. package/dist/common/messages.d.ts +1 -0
  16. package/dist/common/messages.js +69 -0
  17. package/dist/common/performance.d.ts +1 -0
  18. package/dist/common/performance.js +26 -0
  19. package/dist/common/protocol.d.ts +20 -0
  20. package/dist/common/protocol.js +53 -0
  21. package/dist/common/types.d.ts +203 -0
  22. package/dist/common/types.js +1 -0
  23. package/dist/iife/bts.js +1 -0
  24. package/dist/iife/mts.js +1 -0
  25. package/dist/index.d.ts +16 -0
  26. package/dist/index.js +1 -0
  27. package/dist/mts/data.d.ts +71 -0
  28. package/dist/mts/data.js +46 -0
  29. package/dist/mts/flush.d.ts +11 -0
  30. package/dist/mts/flush.js +16 -0
  31. package/dist/mts/host.d.ts +35 -0
  32. package/dist/mts/host.js +124 -0
  33. package/dist/mts/services.d.ts +21 -0
  34. package/dist/mts/services.js +46 -0
  35. package/dist/mts.d.ts +5 -0
  36. package/dist/mts.js +4 -0
  37. package/package.json +54 -7
  38. package/skills/lynx-runtime/SKILL.md +67 -0
  39. package/src/bts/data.ts +94 -0
  40. package/src/bts/events.ts +100 -0
  41. package/src/bts/scope.ts +279 -0
  42. package/src/bts/services.ts +88 -0
  43. package/src/bts.ts +110 -0
  44. package/src/common/host-types.ts +161 -0
  45. package/src/common/messages.ts +129 -0
  46. package/src/common/performance.ts +65 -0
  47. package/src/common/protocol.ts +98 -0
  48. package/src/common/types.ts +259 -0
  49. package/src/index.ts +35 -0
  50. package/src/mts/data.ts +200 -0
  51. package/src/mts/flush.ts +50 -0
  52. package/src/mts/host.ts +297 -0
  53. package/src/mts/services.ts +102 -0
  54. package/src/mts.ts +36 -0
@@ -0,0 +1,297 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ import type {
6
+ HostContextProxy,
7
+ HostGlobalScope,
8
+ HostMessageEvent,
9
+ } from '../common/host-types.js';
10
+ import { clearMultiplexed } from '../common/messages.js';
11
+ import type { MessageSubscriptions } from '../common/messages.js';
12
+ import {
13
+ NATIVE_EVENT_DESTROY_LIFETIME,
14
+ NATIVE_EVENT_RENDER_PAGE,
15
+ NATIVE_EVENT_UPDATE_GLOBAL_PROPS,
16
+ NATIVE_EVENT_UPDATE_PAGE,
17
+ copyHostData,
18
+ dispatchListeners,
19
+ invokeAll,
20
+ subscribeListener,
21
+ } from '../common/protocol.js';
22
+ import type {
23
+ MTSFlushContext,
24
+ MTSReloadOptions,
25
+ MTSRenderOptions,
26
+ MTSUpdateOptions,
27
+ Unsubscribe,
28
+ } from '../common/types.js';
29
+
30
+ /** @internal */
31
+ export type MTSSingleOwnerKey = 'processData' | 'getPageData';
32
+
33
+ /** @internal */
34
+ export interface MTSHostState {
35
+ destroyed: boolean;
36
+ hasDestroyProxy: boolean;
37
+ destroyListeners: Map<() => void, Unsubscribe>;
38
+ jsContext?: HostContextProxy | undefined;
39
+ globalProps: Record<string, unknown>;
40
+ initData: Record<string, unknown>;
41
+ renderListeners: Map<
42
+ (data: Record<string, unknown>, options: MTSRenderOptions) => void,
43
+ Unsubscribe
44
+ >;
45
+ updateListeners: Map<
46
+ (data: Record<string, unknown>, options: MTSUpdateOptions) => void,
47
+ Unsubscribe
48
+ >;
49
+ reloadListeners: Map<
50
+ (data: Record<string, unknown>, options: MTSReloadOptions) => void,
51
+ Unsubscribe
52
+ >;
53
+ globalPropsListeners: Map<
54
+ (
55
+ globalProps: Record<string, unknown>,
56
+ options?: MTSFlushContext,
57
+ ) => void,
58
+ Unsubscribe
59
+ >;
60
+ slots: {
61
+ [K in MTSSingleOwnerKey]?: HostGlobalScope[K];
62
+ };
63
+ messages?: MessageSubscriptions | undefined;
64
+ }
65
+
66
+ const mtsStateMap = new WeakMap<object, MTSHostState>();
67
+
68
+ /** @internal */
69
+ export const defaultProcessData = <T>(data: T): T => data;
70
+ /** @internal */
71
+ export const defaultGetPageData = (): null => null;
72
+ const noop = (): void => {
73
+ // Safe placeholder for C++ QuickContext::GetAndCall (try_call = false) entrypoints.
74
+ };
75
+
76
+ /** @internal */
77
+ export function isMTSHostDestroyed(host: HostGlobalScope): boolean {
78
+ return mtsStateMap.get(host.lynx ?? host)?.destroyed === true;
79
+ }
80
+
81
+ /** @internal */
82
+ export function initMTSHostState(host: HostGlobalScope): MTSHostState {
83
+ const key = host.lynx ?? host;
84
+ const existing = mtsStateMap.get(key);
85
+ if (existing) return existing;
86
+
87
+ const nativeProxy = host.lynx?.getNative?.();
88
+ const state: MTSHostState = {
89
+ destroyed: false,
90
+ hasDestroyProxy: nativeProxy !== undefined,
91
+ destroyListeners: new Map(),
92
+ globalProps: {},
93
+ initData: {},
94
+ renderListeners: new Map(),
95
+ updateListeners: new Map(),
96
+ reloadListeners: new Map(),
97
+ globalPropsListeners: new Map(),
98
+ slots: {},
99
+ };
100
+ mtsStateMap.set(key, state);
101
+
102
+ const onRenderInput = (
103
+ data?: Record<string, unknown> | null,
104
+ options?: MTSRenderOptions,
105
+ ): void => {
106
+ if (state.destroyed) return;
107
+ const normalizedData = data ?? {};
108
+ state.initData = copyHostData(normalizedData);
109
+ const normalizedOptions = options ?? {};
110
+ dispatchListeners(state.renderListeners, (listener) => {
111
+ listener(normalizedData, normalizedOptions);
112
+ });
113
+ };
114
+
115
+ const onUpdateInput = (
116
+ data?: Record<string, unknown> | null,
117
+ options?: MTSReloadOptions,
118
+ ): void => {
119
+ if (state.destroyed) return;
120
+ const normalizedData = data ?? {};
121
+ const normalizedOptions = options ?? {};
122
+ if (normalizedOptions.reloadTemplate) {
123
+ state.initData = copyHostData(normalizedData);
124
+ dispatchListeners(state.reloadListeners, (listener) => {
125
+ listener(normalizedData, normalizedOptions);
126
+ });
127
+ } else {
128
+ dispatchListeners(state.updateListeners, (listener) => {
129
+ listener(normalizedData, normalizedOptions);
130
+ });
131
+ }
132
+ };
133
+
134
+ const onGlobalPropsInput = (
135
+ data?: Record<string, unknown> | null,
136
+ options?: MTSFlushContext,
137
+ ): void => {
138
+ if (state.destroyed) return;
139
+ const normalizedData = data ?? {};
140
+ dispatchListeners(state.globalPropsListeners, (listener) => {
141
+ listener(normalizedData, options);
142
+ });
143
+ };
144
+
145
+ // Install global entrypoints and placeholders upfront so C++ GetAndCall (try_call = false)
146
+ // never fails when a capability (such as updateGlobalProps or processData) has no user listener.
147
+ host.renderPage = onRenderInput;
148
+ host.updatePage = onUpdateInput;
149
+ host.updateGlobalProps = onGlobalPropsInput;
150
+ host.processData ??= defaultProcessData;
151
+ host.removeComponents ??= noop;
152
+ host.getPageData ??= defaultGetPageData;
153
+ if (host.lynx?.SystemInfo && !host.SystemInfo) {
154
+ // Native UpdateScreenMetrics mutates global SystemInfo.pixelRatio in place.
155
+ host.SystemInfo = host.lynx.SystemInfo;
156
+ }
157
+
158
+ const engine = host.lynx?.getEngine?.();
159
+ if (engine) {
160
+ engine.addEventListener(
161
+ NATIVE_EVENT_RENDER_PAGE,
162
+ (event: HostMessageEvent<unknown[]>) => {
163
+ const [data, options] = event.data;
164
+ onRenderInput(
165
+ data as Record<string, unknown> | null | undefined,
166
+ options as MTSRenderOptions | undefined,
167
+ );
168
+ },
169
+ );
170
+ engine.addEventListener(
171
+ NATIVE_EVENT_UPDATE_PAGE,
172
+ (event: HostMessageEvent<unknown[]>) => {
173
+ const [data, options] = event.data;
174
+ onUpdateInput(
175
+ data as Record<string, unknown> | null | undefined,
176
+ options as MTSReloadOptions | undefined,
177
+ );
178
+ },
179
+ );
180
+ engine.addEventListener(
181
+ NATIVE_EVENT_UPDATE_GLOBAL_PROPS,
182
+ (event: HostMessageEvent<unknown[]>) => {
183
+ const [data, options] = event.data;
184
+ onGlobalPropsInput(
185
+ data as Record<string, unknown> | null | undefined,
186
+ options as MTSFlushContext | undefined,
187
+ );
188
+ },
189
+ );
190
+ }
191
+
192
+ if (nativeProxy) {
193
+ const onNativeDestroy = (): void => {
194
+ if (state.destroyed) return;
195
+ state.globalProps = host.lynx?.__globalProps ?? state.globalProps;
196
+ state.destroyed = true;
197
+ try {
198
+ if (state.messages) {
199
+ clearMultiplexed(state.messages);
200
+ state.messages = undefined;
201
+ }
202
+ invokeAll(
203
+ [...state.destroyListeners].map(([listener, reg]) => () => {
204
+ if (state.destroyListeners.get(listener) === reg) {
205
+ listener();
206
+ }
207
+ }),
208
+ );
209
+ } finally {
210
+ state.renderListeners.clear();
211
+ state.updateListeners.clear();
212
+ state.reloadListeners.clear();
213
+ state.globalPropsListeners.clear();
214
+ state.destroyListeners.clear();
215
+ if (
216
+ state.slots.processData
217
+ && host.processData === state.slots.processData
218
+ ) {
219
+ host.processData = defaultProcessData;
220
+ }
221
+ state.slots.processData = undefined;
222
+ if (
223
+ state.slots.getPageData
224
+ && host.getPageData === state.slots.getPageData
225
+ ) {
226
+ host.getPageData = defaultGetPageData;
227
+ }
228
+ state.slots.getPageData = undefined;
229
+ nativeProxy.removeEventListener(
230
+ NATIVE_EVENT_DESTROY_LIFETIME,
231
+ onNativeDestroy,
232
+ );
233
+ }
234
+ };
235
+ nativeProxy.addEventListener(
236
+ NATIVE_EVENT_DESTROY_LIFETIME,
237
+ onNativeDestroy,
238
+ );
239
+ }
240
+
241
+ return state;
242
+ }
243
+
244
+ /** @internal */
245
+ export function getAliveMTSState(host: HostGlobalScope): MTSHostState {
246
+ const state = initMTSHostState(host);
247
+ if (state.destroyed) {
248
+ throw new Error(
249
+ '[@lynx-js/lynx-runtime/mts] Cannot register or activate a capability on a destroying or destroyed host. Check isDestroyed() before registering in async callbacks.',
250
+ );
251
+ }
252
+ return state;
253
+ }
254
+
255
+ /**
256
+ * True once the MTS host destruction signal (`lynx.getNative()` `__DestroyLifetime`)
257
+ * is observed, before DSL teardown callbacks run.
258
+ *
259
+ * @remarks
260
+ * Observing MTS destruction requires `lynx.getNative()` (**Lynx SDK 3.4+** on Native
261
+ * and Web). On older hosts without `lynx.getNative()` (**Lynx SDK 2.14–3.3** or
262
+ * earlier `web-core`), `isDestroyed()` remains `false`; a `false` return value means
263
+ * destruction has not been observed rather than guaranteeing host liveness.
264
+ *
265
+ * @since Lynx 3.4 (always `false` when host lacks `lynx.getNative()`)
266
+ */
267
+ export function isDestroyed(): boolean {
268
+ return isMTSHostDestroyed(globalThis as unknown as HostGlobalScope);
269
+ }
270
+
271
+ /**
272
+ * Subscribe to MTS page destruction (`__DestroyLifetime` on `lynx.getNative()`).
273
+ *
274
+ * @remarks
275
+ * Host destruction notifications on MTS require `lynx.getNative()` (**Lynx SDK 3.4+**
276
+ * on Native and Web). On **Lynx SDK 2.14–3.3** or earlier `web-core` without
277
+ * `lynx.getNative()`, calling `onDestroy` safely degrades to a no-op and returns an
278
+ * idempotent `Unsubscribe` function without throwing, because the single-page context
279
+ * is torn down as a whole without an MTS destroy event.
280
+ *
281
+ * Note: `ReloadTemplate` / `ReloadFromJS` (`globalThis.removeComponents` + `onReload`)
282
+ * reuses the same MTS context and does **not** dispatch `__DestroyLifetime`.
283
+ * Runtime objects recreated across reloads or entry re-evaluations must invoke
284
+ * the returned `Unsubscribe` disposer when retiring so listeners do not accumulate
285
+ * until page teardown.
286
+ *
287
+ * @param listener - Callback invoked synchronously when MTS destruction begins.
288
+ * @returns An idempotent disposer that unsubscribes `listener` (no-op when the host does not emit MTS destroy notifications).
289
+ * @since Lynx 3.4 (safe no-op when host lacks `lynx.getNative()`)
290
+ */
291
+ export function onDestroy(listener: () => void): Unsubscribe {
292
+ const state = getAliveMTSState(globalThis as unknown as HostGlobalScope);
293
+ if (!state.hasDestroyProxy) {
294
+ return noop;
295
+ }
296
+ return subscribeListener(state.destroyListeners, listener);
297
+ }
@@ -0,0 +1,102 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ import { getAliveMTSState, isMTSHostDestroyed } from './host.js';
6
+ import type { MTSHostState } from './host.js';
7
+ import type {
8
+ HostContextProxy,
9
+ HostGlobalScope,
10
+ } from '../common/host-types.js';
11
+ import { subscribeMessage } from '../common/messages.js';
12
+ import { createHostPipeline, markHostTiming } from '../common/performance.js';
13
+ import type {
14
+ CreatePipelineOptions,
15
+ CreatedPipelineOptions,
16
+ LynxSystemInfo,
17
+ PipelineOptions,
18
+ Unsubscribe,
19
+ } from '../common/types.js';
20
+
21
+ function resolveSystemInfo(host: HostGlobalScope): LynxSystemInfo {
22
+ return host.lynx?.SystemInfo ?? host.SystemInfo ?? {};
23
+ }
24
+
25
+ function getJSContext(
26
+ host: HostGlobalScope,
27
+ state: MTSHostState,
28
+ ): HostContextProxy {
29
+ let proxy = state.jsContext;
30
+ if (!proxy) {
31
+ proxy = host.lynx?.getJSContext?.();
32
+ if (!proxy) {
33
+ throw new Error(
34
+ '[@lynx-js/lynx-runtime/mts] Message communication requires lynx.getJSContext(). Ensure the MTS host context is initialized before calling sendMessage() or onMessage().',
35
+ );
36
+ }
37
+ state.jsContext = proxy;
38
+ }
39
+ return proxy;
40
+ }
41
+
42
+ /** Read live host environment information without initializing MTS input bindings. */
43
+ export function getSystemInfo(): Readonly<LynxSystemInfo> {
44
+ const host = globalThis as unknown as HostGlobalScope;
45
+ if (!isMTSHostDestroyed(host) && host.lynx?.SystemInfo && !host.SystemInfo) {
46
+ // Native UpdateScreenMetrics updates global `SystemInfo.pixelRatio` in place.
47
+ host.SystemInfo = host.lynx.SystemInfo;
48
+ }
49
+ return resolveSystemInfo(host);
50
+ }
51
+
52
+ /** Create a host performance pipeline without imposing DSL timing stages. */
53
+ export function createPipeline(
54
+ options?: CreatePipelineOptions,
55
+ ): CreatedPipelineOptions | undefined {
56
+ const host = globalThis as unknown as HostGlobalScope;
57
+ if (isMTSHostDestroyed(host)) return undefined;
58
+ return createHostPipeline(host.lynx?.performance, options, 'mts');
59
+ }
60
+
61
+ /** Mark a host timing key; the DSL decides whether a key needs timestamps. */
62
+ export function markTiming(
63
+ pipeline: string | PipelineOptions | undefined,
64
+ timingKey: string,
65
+ ): void {
66
+ const host = globalThis as unknown as HostGlobalScope;
67
+ if (isMTSHostDestroyed(host)) return;
68
+ markHostTiming(host.lynx?.performance, pipeline, timingKey);
69
+ }
70
+
71
+ /**
72
+ * Send a named message to this page's BTS without a completion receipt.
73
+ * Requires a live MTS host and peer proxy. Install the receiver first: there is
74
+ * no startup queue, retry, RPC, or cross-type ordering guarantee. Awaiting this
75
+ * void return does not wait for the peer. T does not validate the payload at runtime.
76
+ */
77
+ export function sendMessage<T = undefined>(
78
+ type: string,
79
+ ...args: undefined extends T ? [data?: T] : [data: T]
80
+ ): void;
81
+ export function sendMessage(type: string, data?: unknown): void {
82
+ const host = globalThis as unknown as HostGlobalScope;
83
+ const state = getAliveMTSState(host);
84
+ getJSContext(host, state).dispatchEvent({ type, data });
85
+ }
86
+
87
+ /**
88
+ * Subscribe to named messages from this page's BTS, preserving the raw payload.
89
+ * Requires a live host and peer proxy; missed messages are not replayed. Identical
90
+ * callbacks for a type share a registration. Dispose when the owning entry retires;
91
+ * observed page destruction also removes listeners. T is not runtime validation.
92
+ */
93
+ export function onMessage<T = unknown>(
94
+ type: string,
95
+ listener: (this: void, data: T) => void,
96
+ ): Unsubscribe {
97
+ const host = globalThis as unknown as HostGlobalScope;
98
+ const state = getAliveMTSState(host);
99
+ const proxy = getJSContext(host, state);
100
+ state.messages ??= new Map();
101
+ return subscribeMessage(state.messages, proxy, type, listener);
102
+ }
package/src/mts.ts ADDED
@@ -0,0 +1,36 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ export type {
6
+ CreatedPipelineOptions,
7
+ CreatePipelineOptions,
8
+ LynxSystemInfo,
9
+ MTSFlushContext,
10
+ MTSFlushOptions,
11
+ MTSReloadOptions,
12
+ MTSRenderOptions,
13
+ MTSUpdateOptions,
14
+ PipelineOptions,
15
+ Unsubscribe,
16
+ } from './common/types.js';
17
+
18
+ export {
19
+ getGlobalProps,
20
+ getInitData,
21
+ onGlobalPropsChanged,
22
+ onReload,
23
+ onRenderPage,
24
+ onUpdateData,
25
+ setDataProcessor,
26
+ setPageDataGetter,
27
+ } from './mts/data.js';
28
+ export { flushElementTree } from './mts/flush.js';
29
+ export { isDestroyed, onDestroy } from './mts/host.js';
30
+ export {
31
+ createPipeline,
32
+ getSystemInfo,
33
+ markTiming,
34
+ onMessage,
35
+ sendMessage,
36
+ } from './mts/services.js';