@lynx-js/react 0.111.1 → 0.111.2

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 (134) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/components/lib/DeferredListItem.d.ts +3 -1
  3. package/components/lib/DeferredListItem.jsx +4 -2
  4. package/components/lib/DeferredListItem.jsx.map +1 -1
  5. package/components/src/DeferredListItem.tsx +5 -3
  6. package/package.json +6 -1
  7. package/refresh/.turbo/turbo-build.log +1 -1
  8. package/runtime/debug/index.cjs +8 -0
  9. package/runtime/debug/index.d.ts +4 -0
  10. package/runtime/debug/index.js +5 -0
  11. package/runtime/lib/alog/index.d.ts +1 -0
  12. package/runtime/lib/alog/index.js +8 -0
  13. package/runtime/lib/alog/index.js.map +1 -0
  14. package/runtime/lib/alog/render.d.ts +1 -0
  15. package/runtime/lib/alog/render.js +19 -0
  16. package/runtime/lib/alog/render.js.map +1 -0
  17. package/runtime/lib/backgroundSnapshot.d.ts +1 -0
  18. package/runtime/lib/backgroundSnapshot.js +31 -17
  19. package/runtime/lib/backgroundSnapshot.js.map +1 -1
  20. package/runtime/lib/debug/component-stack.d.ts +33 -0
  21. package/runtime/lib/debug/component-stack.js +145 -0
  22. package/runtime/lib/debug/component-stack.js.map +1 -0
  23. package/runtime/lib/debug/formatPatch.d.ts +2 -0
  24. package/runtime/lib/debug/formatPatch.js +27 -0
  25. package/runtime/lib/debug/formatPatch.js.map +1 -0
  26. package/runtime/lib/debug/printSnapshot.d.ts +1 -1
  27. package/runtime/lib/debug/printSnapshot.js +0 -4
  28. package/runtime/lib/debug/printSnapshot.js.map +1 -1
  29. package/runtime/lib/debug/profile.js +1 -3
  30. package/runtime/lib/debug/profile.js.map +1 -1
  31. package/runtime/lib/hydrate.js +11 -7
  32. package/runtime/lib/hydrate.js.map +1 -1
  33. package/runtime/lib/lifecycle/patch/commit.js +1 -1
  34. package/runtime/lib/lifecycle/patch/commit.js.map +1 -1
  35. package/runtime/lib/lifecycle/patch/snapshotPatch.d.ts +4 -0
  36. package/runtime/lib/lifecycle/patch/snapshotPatch.js +28 -0
  37. package/runtime/lib/lifecycle/patch/snapshotPatch.js.map +1 -1
  38. package/runtime/lib/lynx.js +9 -0
  39. package/runtime/lib/lynx.js.map +1 -1
  40. package/runtime/lib/pendingListUpdates.d.ts +2 -1
  41. package/runtime/lib/pendingListUpdates.js +16 -4
  42. package/runtime/lib/pendingListUpdates.js.map +1 -1
  43. package/runtime/lib/renderToOpcodes/constants.d.ts +2 -0
  44. package/runtime/lib/renderToOpcodes/constants.js +2 -0
  45. package/runtime/lib/renderToOpcodes/constants.js.map +1 -1
  46. package/runtime/lib/root.d.ts +6 -0
  47. package/runtime/lib/root.js +4 -0
  48. package/runtime/lib/root.js.map +1 -1
  49. package/runtime/lib/snapshot/platformInfo.js +5 -3
  50. package/runtime/lib/snapshot/platformInfo.js.map +1 -1
  51. package/runtime/lib/snapshot/ref.d.ts +2 -2
  52. package/runtime/lib/snapshot/spread.js +3 -1
  53. package/runtime/lib/snapshot/spread.js.map +1 -1
  54. package/runtime/lib/snapshot.js +13 -7
  55. package/runtime/lib/snapshot.js.map +1 -1
  56. package/runtime/lib/utils.d.ts +2 -0
  57. package/runtime/lib/utils.js +23 -2
  58. package/runtime/lib/utils.js.map +1 -1
  59. package/testing-library/dist/env/vitest.js +12 -4
  60. package/types/react.d.ts +13 -1
  61. package/runtime/src/backgroundSnapshot.ts +0 -501
  62. package/runtime/src/compat/componentIs.ts +0 -30
  63. package/runtime/src/compat/initData.ts +0 -150
  64. package/runtime/src/compat/lynxComponent.ts +0 -79
  65. package/runtime/src/debug/debug.ts +0 -9
  66. package/runtime/src/debug/printSnapshot.ts +0 -28
  67. package/runtime/src/debug/profile.ts +0 -55
  68. package/runtime/src/document.ts +0 -84
  69. package/runtime/src/gesture/processGesture.ts +0 -89
  70. package/runtime/src/gesture/processGestureBagkround.ts +0 -19
  71. package/runtime/src/gesture/types.ts +0 -44
  72. package/runtime/src/hooks/react.ts +0 -62
  73. package/runtime/src/hooks/useLynxGlobalEventListener.ts +0 -59
  74. package/runtime/src/hydrate.ts +0 -368
  75. package/runtime/src/index.ts +0 -94
  76. package/runtime/src/internal.ts +0 -63
  77. package/runtime/src/legacy-react-runtime/index.ts +0 -42
  78. package/runtime/src/lifecycle/destroy.ts +0 -34
  79. package/runtime/src/lifecycle/event/delayEvents.ts +0 -11
  80. package/runtime/src/lifecycle/event/delayLifecycleEvents.ts +0 -15
  81. package/runtime/src/lifecycle/event/jsReady.ts +0 -34
  82. package/runtime/src/lifecycle/pass.ts +0 -14
  83. package/runtime/src/lifecycle/patch/commit.ts +0 -214
  84. package/runtime/src/lifecycle/patch/error.ts +0 -61
  85. package/runtime/src/lifecycle/patch/isMainThreadHydrationFinished.ts +0 -13
  86. package/runtime/src/lifecycle/patch/snapshotPatch.ts +0 -65
  87. package/runtime/src/lifecycle/patch/snapshotPatchApply.ts +0 -145
  88. package/runtime/src/lifecycle/patch/updateMainThread.ts +0 -64
  89. package/runtime/src/lifecycle/ref/delay.ts +0 -99
  90. package/runtime/src/lifecycle/reload.ts +0 -97
  91. package/runtime/src/lifecycle/render.ts +0 -54
  92. package/runtime/src/lifecycleConstant.ts +0 -21
  93. package/runtime/src/list.ts +0 -307
  94. package/runtime/src/listUpdateInfo.ts +0 -221
  95. package/runtime/src/lynx/calledByNative.ts +0 -160
  96. package/runtime/src/lynx/component.ts +0 -113
  97. package/runtime/src/lynx/dynamic-js.ts +0 -36
  98. package/runtime/src/lynx/env.ts +0 -109
  99. package/runtime/src/lynx/injectLepusMethods.ts +0 -53
  100. package/runtime/src/lynx/lazy-bundle.ts +0 -175
  101. package/runtime/src/lynx/performance.ts +0 -148
  102. package/runtime/src/lynx/runWithForce.ts +0 -67
  103. package/runtime/src/lynx/tt.ts +0 -215
  104. package/runtime/src/lynx-api.ts +0 -455
  105. package/runtime/src/lynx.ts +0 -58
  106. package/runtime/src/opcodes.ts +0 -155
  107. package/runtime/src/pendingListUpdates.ts +0 -18
  108. package/runtime/src/renderToOpcodes/constants.ts +0 -24
  109. package/runtime/src/renderToOpcodes/index.ts +0 -306
  110. package/runtime/src/root.ts +0 -23
  111. package/runtime/src/snapshot/dynamicPartType.ts +0 -16
  112. package/runtime/src/snapshot/event.ts +0 -33
  113. package/runtime/src/snapshot/gesture.ts +0 -30
  114. package/runtime/src/snapshot/list.ts +0 -36
  115. package/runtime/src/snapshot/platformInfo.ts +0 -62
  116. package/runtime/src/snapshot/ref.ts +0 -139
  117. package/runtime/src/snapshot/spread.ts +0 -330
  118. package/runtime/src/snapshot/workletEvent.ts +0 -35
  119. package/runtime/src/snapshot/workletRef.ts +0 -88
  120. package/runtime/src/snapshot.ts +0 -634
  121. package/runtime/src/snapshotInstanceHydrationMap.ts +0 -17
  122. package/runtime/src/utils.ts +0 -44
  123. package/runtime/src/worklet/ctx.ts +0 -22
  124. package/runtime/src/worklet/destroy.ts +0 -16
  125. package/runtime/src/worklet/execMap.ts +0 -51
  126. package/runtime/src/worklet/functionCall.ts +0 -42
  127. package/runtime/src/worklet/functionality.ts +0 -29
  128. package/runtime/src/worklet/hmr.ts +0 -34
  129. package/runtime/src/worklet/indexMap.ts +0 -23
  130. package/runtime/src/worklet/runOnBackground.ts +0 -147
  131. package/runtime/src/worklet/runOnMainThread.ts +0 -50
  132. package/runtime/src/worklet/transformToWorklet.ts +0 -26
  133. package/runtime/src/worklet/workletRef.ts +0 -231
  134. package/runtime/src/worklet/workletRefPool.ts +0 -29
@@ -1,160 +0,0 @@
1
- // Copyright 2024 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
- import { hydrate } from '../hydrate.js';
5
- import { isJSReady, jsReady, jsReadyEventIdSwap, resetJSReady } from '../lifecycle/event/jsReady.js';
6
- import { reloadMainThread } from '../lifecycle/reload.js';
7
- import { renderMainThread } from '../lifecycle/render.js';
8
- import { LifecycleConstant } from '../lifecycleConstant.js';
9
- import { ssrHydrateByOpcodes } from '../opcodes.js';
10
- import { __pendingListUpdates } from '../pendingListUpdates.js';
11
- import { __root, setRoot } from '../root.js';
12
- import { applyRefQueue } from '../snapshot/workletRef.js';
13
- import { SnapshotInstance, __page, setupPage } from '../snapshot.js';
14
- import { isEmptyObject } from '../utils.js';
15
- import { markTiming, setPipeline } from './performance.js';
16
-
17
- function ssrEncode() {
18
- const { __opcodes } = __root;
19
- delete __root.__opcodes;
20
-
21
- // eslint-disable-next-line @typescript-eslint/unbound-method
22
- const oldToJSON = SnapshotInstance.prototype.toJSON;
23
- SnapshotInstance.prototype.toJSON = function(this: SnapshotInstance): any {
24
- return [
25
- this.type,
26
- this.__id,
27
- this.__elements,
28
- ];
29
- };
30
-
31
- try {
32
- return JSON.stringify({ __opcodes, __root_values: __root.__values });
33
- } finally {
34
- SnapshotInstance.prototype.toJSON = oldToJSON;
35
- }
36
- }
37
-
38
- function ssrHydrate(info: string) {
39
- const nativePage = __GetPageElement();
40
- if (!nativePage) {
41
- throw new Error('SSR Hydration Failed! Please check if the SSR content loaded successfully!');
42
- }
43
-
44
- resetJSReady();
45
- setupPage(nativePage);
46
- const refsMap = __GetTemplateParts(nativePage);
47
-
48
- const { __opcodes, __root_values } = JSON.parse(info) as {
49
- __opcodes: unknown[];
50
- __root_values: unknown[] | undefined;
51
- };
52
- if (__root_values) {
53
- __root.setAttribute('values', __root_values);
54
- }
55
- ssrHydrateByOpcodes(__opcodes, __root as SnapshotInstance, refsMap);
56
-
57
- (__root as SnapshotInstance).__elements = [nativePage];
58
- (__root as SnapshotInstance).__element_root = nativePage;
59
- }
60
-
61
- function injectCalledByNative(): void {
62
- if (process.env['NODE_ENV'] !== 'test' && __FIRST_SCREEN_SYNC_TIMING__ !== 'jsReady' && __ENABLE_SSR__) {
63
- throw new Error('`firstScreenSyncTiming` must be `jsReady` when SSR is enabled');
64
- }
65
-
66
- const calledByNative: LynxCallByNative = {
67
- renderPage,
68
- updatePage,
69
- updateGlobalProps,
70
- getPageData: function() {
71
- return null;
72
- },
73
- removeComponents: function(): void {},
74
- ...(__ENABLE_SSR__ ? { ssrEncode, ssrHydrate } : {}),
75
- };
76
-
77
- Object.assign(globalThis, calledByNative);
78
- Object.assign(globalThis, {
79
- [LifecycleConstant.jsReady]: jsReady,
80
- });
81
- }
82
-
83
- function renderPage(data: Record<string, unknown> | undefined): void {
84
- // reset `jsReady` state
85
- resetJSReady();
86
-
87
- lynx.__initData = data ?? {};
88
-
89
- setupPage(__CreatePage('0', 0));
90
- (__root as SnapshotInstance).ensureElements();
91
-
92
- renderMainThread();
93
-
94
- // always call this before `__FlushElementTree`
95
- // (There is an implicit `__FlushElementTree` in `renderPage`)
96
- __pendingListUpdates.flush();
97
- applyRefQueue();
98
-
99
- if (__FIRST_SCREEN_SYNC_TIMING__ === 'immediately') {
100
- jsReady();
101
- }
102
- }
103
-
104
- function updatePage(data: Record<string, unknown> | undefined, options?: UpdatePageOption): void {
105
- if (options?.reloadTemplate) {
106
- reloadMainThread(data, options);
107
- return;
108
- }
109
-
110
- if (options?.resetPageData) {
111
- lynx.__initData = {};
112
- }
113
-
114
- if (typeof data == 'object' && !isEmptyObject(data)) {
115
- lynx.__initData ??= {};
116
- Object.assign(lynx.__initData, data);
117
- }
118
-
119
- const flushOptions = options ?? {};
120
- if (!isJSReady) {
121
- const oldRoot = __root;
122
- setRoot(new SnapshotInstance('root'));
123
- __root.__jsx = oldRoot.__jsx;
124
-
125
- setPipeline(options?.pipelineOptions);
126
- markTiming('updateDiffVdomStart');
127
- {
128
- __pendingListUpdates.clear();
129
- renderMainThread();
130
- // As said by codename `jsReadyEventIdSwap`, this swap will only be used for event remap,
131
- // because ref & unref cause by previous render will be ignored
132
- hydrate(
133
- oldRoot as SnapshotInstance,
134
- __root as SnapshotInstance,
135
- { skipUnRef: true, swap: jsReadyEventIdSwap },
136
- );
137
-
138
- // always call this before `__FlushElementTree`
139
- __pendingListUpdates.flush();
140
- applyRefQueue();
141
- }
142
- flushOptions.triggerDataUpdated = true;
143
- markTiming('updateDiffVdomEnd');
144
- }
145
-
146
- __FlushElementTree(__page, flushOptions);
147
- }
148
-
149
- function updateGlobalProps(_data: any, options?: UpdatePageOption): void {
150
- if (options) {
151
- __FlushElementTree(__page, options);
152
- } else {
153
- __FlushElementTree();
154
- }
155
- }
156
-
157
- /**
158
- * @internal
159
- */
160
- export { injectCalledByNative };
@@ -1,113 +0,0 @@
1
- // Copyright 2024 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
- /* eslint-disable */
6
-
7
- import { Component } from 'preact';
8
-
9
- import { PerfSpecificKey, markTimingLegacy } from './performance.js';
10
- import { globalFlushOptions } from '../lifecycle/patch/commit.js';
11
- import { NEXT_STATE } from '../renderToOpcodes/constants.js';
12
-
13
- if (__JS__) {
14
- function reportRefDeprecationError(fnName: string, newFnName: string) {
15
- if (!__DISABLE_CREATE_SELECTOR_QUERY_INCOMPATIBLE_WARNING__) {
16
- lynx.reportError(
17
- new Error(
18
- `${fnName} is deprecated and has different behavior in ReactLynx 3.0, please use ref or ${newFnName} instead.`,
19
- ),
20
- );
21
- }
22
- }
23
-
24
- const __Component = Component as any;
25
-
26
- __Component.prototype._reactAppInstance = lynxCoreInject.tt;
27
-
28
- __Component.prototype.getNodeRef = function(a: string, b?: boolean) {
29
- reportRefDeprecationError('getNodeRef', 'lynx.createSelectorQuery');
30
-
31
- // @ts-expect-error hack lynx-kernel
32
- return lynxCoreInject.tt._reactLynx.ReactComponent.prototype.getNodeRef
33
- .call(
34
- {
35
- _type: '',
36
- // @ts-expect-error hack lynx-kernel
37
- _nativeApp: lynxCoreInject.tt._nativeApp,
38
- // @ts-expect-error hack lynx-kernel
39
- _uiModule: lynxCoreInject.tt._nativeApp.nativeModuleProxy.LynxUIMethodModule,
40
- _reactAppInstance: lynxCoreInject.tt,
41
- },
42
- a,
43
- b,
44
- );
45
- };
46
-
47
- __Component.prototype.getNodeRefFromRoot = function(a: string) {
48
- reportRefDeprecationError('getNodeRefFromRoot', 'lynx.createSelectorQuery');
49
-
50
- // @ts-expect-error hack lynx-kernel
51
- return lynxCoreInject.tt._reactLynx.ReactComponent.prototype
52
- .getNodeRefFromRoot.call(
53
- {
54
- _type: '',
55
- // @ts-expect-error hack lynx-kernel
56
- _nativeApp: lynxCoreInject.tt._nativeApp,
57
- // @ts-expect-error hack lynx-kernel
58
- _uiModule: lynxCoreInject.tt._nativeApp.nativeModuleProxy.LynxUIMethodModule,
59
- _reactAppInstance: lynxCoreInject.tt,
60
- },
61
- a,
62
- );
63
- };
64
-
65
- __Component.prototype.registerModule = function(
66
- name: string,
67
- module: object,
68
- ): void {
69
- this._reactAppInstance.registerModule(name, module);
70
- };
71
-
72
- __Component.prototype.getJSModule = function<Module = unknown>(
73
- name: string,
74
- ): Module {
75
- return this._reactAppInstance.getJSModule(name);
76
- };
77
-
78
- __Component.prototype.addGlobalEventListener = function(
79
- eventName: string,
80
- callback: (...args: unknown[]) => void,
81
- context?: object,
82
- ): void {
83
- return this._reactAppInstance.getJSModule('GlobalEventEmitter').addListener(
84
- eventName,
85
- callback,
86
- context,
87
- );
88
- };
89
-
90
- __Component.prototype.getElementById = function(id: string) {
91
- reportRefDeprecationError('getElementById', 'lynx.getElementById');
92
- return lynx.getElementById(id);
93
- };
94
-
95
- __Component.prototype.GlobalEventEmitter = lynxCoreInject.tt.GlobalEventEmitter;
96
-
97
- __Component.prototype.createSelectorQuery = function() {
98
- reportRefDeprecationError('createSelectorQuery on component instance', 'lynx.createSelectorQuery');
99
- return lynx.createSelectorQuery();
100
- };
101
-
102
- const oldSetState = __Component.prototype.setState;
103
- __Component.prototype.setState = function(state: any, callback: any): void {
104
- oldSetState.call(this, state, callback);
105
- // @ts-ignore
106
- const timingFlag = this[NEXT_STATE][PerfSpecificKey];
107
- if (timingFlag) {
108
- globalFlushOptions.__lynx_timing_flag = timingFlag;
109
- markTimingLegacy('updateSetStateTrigger', timingFlag);
110
- this[NEXT_STATE][PerfSpecificKey] = '';
111
- }
112
- };
113
- }
@@ -1,36 +0,0 @@
1
- // Copyright 2024 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
- import { loadLazyBundle } from './lazy-bundle.js';
5
-
6
- export function loadDynamicJS<T>(url: string): Promise<T> {
7
- if (__LEPUS__) {
8
- _ReportError(
9
- new Error(`A dynamic import (to "${url}") is leaked to Lepus bundle.`),
10
- { errorCode: 202 },
11
- );
12
- // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
13
- return Promise.reject();
14
- }
15
- return new Promise((resolve, reject) => {
16
- lynx.requireModuleAsync<T>(url, (err, data) => {
17
- if (err) {
18
- reject(err);
19
- } else {
20
- resolve(data as T);
21
- }
22
- });
23
- });
24
- }
25
-
26
- export function __dynamicImport<T>(
27
- url: string,
28
- options?: { with?: { type?: 'component' | 'tsx' | 'jsx' } },
29
- ): Promise<T> {
30
- const t = options?.with?.type;
31
- if (t === 'component' || t === 'tsx' || t === 'jsx') {
32
- return loadLazyBundle<any>(url);
33
- } else {
34
- return loadDynamicJS(url);
35
- }
36
- }
@@ -1,109 +0,0 @@
1
- // Copyright 2024 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
- import type { DataProcessorDefinition, InitData, InitDataRaw } from '../lynx-api.js';
5
-
6
- export function setupLynxEnv(): void {
7
- if (!__LEPUS__) {
8
- const { initData, updateData } = lynxCoreInject.tt._params;
9
- lynx.__initData = { ...initData, ...updateData };
10
- lynx.registerDataProcessors = function() {};
11
- }
12
-
13
- if (__LEPUS__) {
14
- lynx.__initData = {
15
- /* available only in renderPage */
16
- };
17
- // @ts-expect-error no type for lynx.SystemInfo
18
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
19
- globalThis.SystemInfo = lynx.SystemInfo ?? {};
20
-
21
- lynx.reportError = function(e: Error) {
22
- _ReportError(e, {
23
- errorCode: 1101, // ErrCode::LYNX_ERROR_CODE_LEPUS in Lynx/base/debug/error_code.h
24
- });
25
- };
26
-
27
- lynx.triggerGlobalEventFromLepus = function(
28
- eventName: string,
29
- params: any,
30
- ) {
31
- __OnLifecycleEvent(['globalEventFromLepus', [eventName, params]]);
32
- };
33
-
34
- {
35
- // eslint-disable-next-line unicorn/consistent-function-scoping
36
- function __name(empty: string) {
37
- return `Native${empty}Modules`;
38
- }
39
- // TODO(hongzhiyuan.hzy): make sure this is run before any other code (especially code access `NativeModules`)
40
- // @ts-expect-error hack
41
- if (typeof globalThis[__name('')] === 'undefined') {
42
- // @ts-expect-error hack
43
- globalThis[__name('')] = undefined;
44
- }
45
- }
46
-
47
- lynx.registerDataProcessors = function(
48
- dataProcessorDefinition?: DataProcessorDefinition,
49
- ) {
50
- let hasDefaultDataProcessorExecuted = false;
51
- globalThis.processData = (data, processorName) => {
52
- if (__PROFILE__) {
53
- console.profile('processData');
54
- }
55
-
56
- let r: InitData | InitDataRaw;
57
- try {
58
- if (processorName) {
59
- r = dataProcessorDefinition?.dataProcessors?.[processorName]?.(data) as InitData ?? data;
60
- } else {
61
- r = dataProcessorDefinition?.defaultDataProcessor?.(data) ?? data;
62
- }
63
- } catch (e: any) {
64
- lynx.reportError(e as Error);
65
- // when there is an error
66
- // we should perform like dataProcessor returns nothing
67
- // so use `{}` rather than `data`
68
- r = {};
69
- }
70
-
71
- if (__PROFILE__) {
72
- console.profileEnd();
73
- }
74
-
75
- if (hasDefaultDataProcessorExecuted === false) {
76
- // @ts-expect-error todo: add types to i18n logic
77
- if (globalThis.__I18N_RESOURCE_TRANSLATION__) {
78
- r = {
79
- ...r,
80
- // @ts-expect-error todo: add types to i18n logic
81
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
82
- __I18N_RESOURCE_TRANSLATION__: globalThis.__I18N_RESOURCE_TRANSLATION__,
83
- };
84
- }
85
-
86
- // @ts-expect-error todo: add types to __EXTRACT_STR__
87
- if (__EXTRACT_STR__) {
88
- r = {
89
- ...r,
90
- // @ts-expect-error todo: add types to __EXTRACT_STR__
91
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
92
- _EXTRACT_STR: __EXTRACT_STR_IDENT_FLAG__,
93
- };
94
- }
95
- }
96
-
97
- if (processorName) {}
98
- else {
99
- hasDefaultDataProcessorExecuted = true;
100
- }
101
-
102
- return r;
103
- };
104
- };
105
-
106
- // register empty DataProcessors to make sure `globalThis.processData` is set
107
- lynx.registerDataProcessors();
108
- }
109
- }
@@ -1,53 +0,0 @@
1
- // Copyright 2024 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
- import { snapshotInstanceManager } from '../snapshot.js';
5
-
6
- function injectLepusMethods(): void {
7
- Object.assign(globalThis, {
8
- getUniqueIdListBySnapshotId,
9
- getSnapshotIdByUniqueId,
10
- });
11
- }
12
-
13
- /**
14
- * Get the list of `unique_id` of the fiber element by the SnapshotInstance `__id`.
15
- */
16
- function getUniqueIdListBySnapshotId({ snapshotId }: { snapshotId: number }) {
17
- const si = snapshotInstanceManager.values.get(snapshotId);
18
- if (si?.__elements?.length) {
19
- const uniqueIdList = [];
20
- for (const element of si.__elements) {
21
- const uniqueId = __GetElementUniqueID(element);
22
- uniqueIdList.push(uniqueId);
23
- }
24
- return {
25
- uniqueIdList,
26
- };
27
- }
28
- return null;
29
- }
30
-
31
- /**
32
- * Get the SnapshotInstance `__id` of the fiber element by the `unique_id`.
33
- */
34
- function getSnapshotIdByUniqueId({ uniqueId }: { uniqueId: number }) {
35
- for (const si of snapshotInstanceManager.values.values()) {
36
- if (si?.__elements?.length) {
37
- for (const element of si.__elements) {
38
- const unique_id = __GetElementUniqueID(element);
39
- if (unique_id === uniqueId) {
40
- return {
41
- snapshotId: si.__id,
42
- };
43
- }
44
- }
45
- }
46
- }
47
- return null;
48
- }
49
-
50
- /**
51
- * @internal
52
- */
53
- export { injectLepusMethods };
@@ -1,175 +0,0 @@
1
- // Copyright 2024 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
- import { Fragment, lazy as backgroundLazy, createElement } from 'preact/compat';
5
-
6
- /**
7
- * To make code below works
8
- * const App1 = lazy(() => import("./x").then(({App1}) => ({default: App1})))
9
- * const App2 = lazy(() => import("./x").then(({App2}) => ({default: App2})))
10
- * @internal
11
- */
12
- export const makeSyncThen = function<T>(result: T): Promise<T>['then'] {
13
- return function<TR1 = T, TR2 = never>(
14
- this: Promise<T>,
15
- onF?: ((value: T) => TR1 | PromiseLike<TR1>) | null,
16
- _onR?: ((reason: any) => TR2 | PromiseLike<TR2>) | null,
17
- ): Promise<TR1 | TR2> {
18
- if (onF) {
19
- let ret: TR1 | PromiseLike<TR1>;
20
- try {
21
- ret = onF(result);
22
- } catch (e) {
23
- // if (onR) {
24
- // return Promise.resolve(onR(e));
25
- // }
26
- return Promise.reject(e as Error);
27
- }
28
-
29
- if (ret && typeof (ret as PromiseLike<TR1>).then === 'function' /* `thenable` object */) {
30
- // lazy(() =>
31
- // import("./x").then(() => new Promise(...))
32
- // )
33
- // Calling `then` and passing a callback is standard behavior
34
- // but in Lepus runtime the callback will never be called
35
- // So can be simplified to code below
36
- return ret as Promise<TR1>;
37
-
38
- // TODO(hongzhiyuan.hzy): Avoid warning that cannot be turned-off, so the warning is commented
39
- // lynx.reportError(
40
- // new Error(
41
- // 'You returned a Promise in promise-chain of lazy-bundle import (eg. `import("./x").then(() => new Promise(...))`), which will cause related Component unavailable at first-screen, '
42
- // ),
43
- // { level: "warning" }
44
- // );
45
- }
46
-
47
- const p = Promise.resolve(ret);
48
-
49
- const then = makeSyncThen(ret as TR1);
50
- p.then = then as Promise<Awaited<TR1>>['then'];
51
-
52
- return p as Promise<TR1 | TR2>;
53
- }
54
-
55
- return this as Promise<TR1 | TR2>;
56
- };
57
- };
58
-
59
- /**
60
- * Load dynamic component from source. Designed to be used with `lazy`.
61
- * @param source - where dynamic component template.js locates
62
- * @returns
63
- * @public
64
- */
65
- export const loadLazyBundle: <
66
- T extends { default: React.ComponentType<any> },
67
- >(source: string) => Promise<T> = /*#__PURE__*/ (() => {
68
- lynx.loadLazyBundle = loadLazyBundle;
69
-
70
- function loadLazyBundle<
71
- T extends { default: React.ComponentType<any> },
72
- >(source: string): Promise<T> {
73
- if (__LEPUS__) {
74
- const query = __QueryComponent(source);
75
- let result: T;
76
- try {
77
- result = query.evalResult as T;
78
- } catch (e) {
79
- // Here we cannot return a rejected promise
80
- // (which will eventually be an unhandled rejection and cause unnecessary redbox)
81
- // But we still need a object in shape of Promise
82
- // So we return a Promise which will never resolve or reject,
83
- // which fit our principle "lepus run only once at first-screen" better
84
- return new Promise(() => {});
85
- }
86
- const r: Promise<T> = Promise.resolve(result);
87
- // Why we should modify the implementation of `then`?
88
- // We should make it `sync` so lepus first-screen render can use result above instantly
89
- // We also should keep promise shape
90
- r.then = makeSyncThen(result);
91
- return r;
92
- } else if (__JS__) {
93
- const resolver = withSyncResolvers<T>();
94
-
95
- const callback: (result: { code: number; detail: { schema: string } }) => void = result => {
96
- const { code, detail } = result;
97
- if (code === 0) {
98
- const { schema } = detail;
99
- const exports = lynxCoreInject.tt.getDynamicComponentExports(schema);
100
- // `code === 0` means that the lazy bundle has been successfully parsed. However,
101
- // its javascript files may still fail to run, which would prevent the retrieval of the exports object.
102
- if (exports) {
103
- resolver.resolve(exports as T);
104
- return;
105
- }
106
- }
107
- resolver.reject(new Error('Lazy bundle load failed: ' + JSON.stringify(result)));
108
- };
109
- if (typeof lynx.QueryComponent === 'function') {
110
- lynx.QueryComponent(source, callback);
111
- } else {
112
- lynx.getNativeLynx().QueryComponent!(source, callback);
113
- }
114
-
115
- if (resolver.result !== null) {
116
- const p = Promise.resolve(resolver.result);
117
- p.then = makeSyncThen(resolver.result) as Promise<Awaited<T>>['then'];
118
- return p;
119
- } else if (resolver.error === null) {
120
- return new Promise((_resolve, _reject) => {
121
- resolver.resolve = _resolve;
122
- resolver.reject = _reject;
123
- });
124
- } else {
125
- return Promise.reject(resolver.error);
126
- }
127
- }
128
-
129
- throw new Error('unreachable');
130
- }
131
-
132
- return loadLazyBundle;
133
- })();
134
-
135
- function withSyncResolvers<T>() {
136
- 'background-only';
137
-
138
- const resolver: {
139
- result: T | null;
140
- error: Error | null;
141
- resolve(result: T): void;
142
- reject(error: Error): void;
143
- } = {
144
- resolve: (result: T): void => {
145
- resolver.result = result;
146
- },
147
- reject: (error: Error): void => {
148
- resolver.error = error;
149
- },
150
- result: null,
151
- error: null,
152
- };
153
-
154
- return resolver;
155
- }
156
-
157
- /**
158
- * @internal
159
- */
160
- export function mainThreadLazy<T>(loader: () => Promise<{ default: T } | T>) {
161
- const Lazy = backgroundLazy<T>(loader);
162
-
163
- function _Lazy(props: any) {
164
- try {
165
- // @ts-expect-error `Lazy` returned from `backgroundLazy` should be a FC
166
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
167
- return Lazy(props);
168
- } catch (e) {
169
- // We should never throw at mainThread
170
- return createElement(Fragment, {});
171
- }
172
- }
173
-
174
- return _Lazy as T;
175
- }