@weapp-container/react-native 0.0.0-stage → 0.1.0-preview.7.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.
package/lib/index.d.ts ADDED
@@ -0,0 +1,188 @@
1
+ import React from 'react';
2
+ import type { ViewProps } from 'react-native';
3
+ export type JSONValue = null | boolean | number | string | JSONValue[] | {
4
+ [key: string]: JSONValue;
5
+ };
6
+ export type JSONObject = {
7
+ [key: string]: JSONValue;
8
+ };
9
+ export type TrustedApplication = {
10
+ hostAppId: string;
11
+ tenantId: string;
12
+ publisherId: string;
13
+ appId: string;
14
+ environment: 'develop' | 'trial' | 'release';
15
+ version: string;
16
+ packRoot: string;
17
+ };
18
+ export type HostAccount = {
19
+ principalId: string | null;
20
+ epoch: string;
21
+ };
22
+ export type HostServicesConfiguration = {
23
+ application: TrustedApplication;
24
+ account: HostAccount;
25
+ apis?: string[];
26
+ syncValues?: JSONObject;
27
+ };
28
+ export type NativeDeviceApiOptions = {
29
+ bluetooth?: boolean;
30
+ allowedNetworkOrigins?: string[];
31
+ allowLoopbackForDevelopment?: boolean;
32
+ allowedMediaOrigins?: string[];
33
+ dedicatedAudioSession?: boolean;
34
+ nfc?: boolean;
35
+ enableWifi?: boolean;
36
+ wifiConfiguration?: {
37
+ connectToNetworks: boolean;
38
+ readCurrentNetwork: boolean;
39
+ };
40
+ nfcConfiguration?: {
41
+ ndef?: boolean;
42
+ isoDep?: boolean;
43
+ mifareUltralight?: boolean;
44
+ nfcF?: boolean;
45
+ nfcV?: boolean;
46
+ };
47
+ };
48
+ export type HostSnapshotContext = {
49
+ application: TrustedApplication;
50
+ account: HostAccount;
51
+ sessionId: string;
52
+ };
53
+ export type HostApiCallContext = HostSnapshotContext & {
54
+ callId: string;
55
+ api: string;
56
+ deadlineNs: string | null;
57
+ cancelToken: string | null;
58
+ componentTarget?: {
59
+ pageId: string;
60
+ nodeId: string;
61
+ ownerScopeId: string | null;
62
+ };
63
+ };
64
+ export type Configuration = {
65
+ storage: {
66
+ key: string;
67
+ } | {
68
+ memoryOnly: true;
69
+ };
70
+ hostServices?: HostServicesConfiguration;
71
+ };
72
+ /** Asset paths are relative to Android assets or the iOS main resource bundle. */
73
+ export type PackSource = {
74
+ directory: string;
75
+ } | {
76
+ asset: string;
77
+ };
78
+ export type HostErrorCode = 'invalid_request' | 'permission_denied' | 'timeout' | 'cancelled' | 'unsupported';
79
+ export declare class HostError extends Error {
80
+ readonly code: HostErrorCode;
81
+ readonly retryable: boolean;
82
+ readonly details: JSONObject;
83
+ constructor(code: HostErrorCode, message: string, retryable?: boolean, details?: JSONObject);
84
+ }
85
+ export type HostHandler = (payload: JSONValue, context: {
86
+ signal: AbortSignal;
87
+ callId: string;
88
+ method: string;
89
+ deadlineNs?: string;
90
+ cancelToken?: string;
91
+ apiContext?: HostApiCallContext;
92
+ }) => JSONValue | Promise<JSONValue>;
93
+ export type WxRequestPaymentOptions = {
94
+ timeStamp: string;
95
+ nonceStr: string;
96
+ package: string;
97
+ signType: 'MD5' | 'HMAC-SHA256' | 'RSA';
98
+ paySign: string;
99
+ };
100
+ export type WxRequestPaymentHandler = (options: WxRequestPaymentOptions, context: Parameters<HostHandler>[1]) => void | Promise<void>;
101
+ export type AccountCleanupHandler = (context: {
102
+ operationId: string;
103
+ signal: AbortSignal;
104
+ }) => void | Promise<void>;
105
+ export type ContainerEvent = {
106
+ type: 'accountCleanupRequired' | 'ready' | 'navigation' | 'message' | 'error' | 'closed' | 'presented' | 'accountSwitch' | 'hostApiEvent';
107
+ payload: JSONValue;
108
+ };
109
+ /** Session owner. Keep it outside render; detach and close are separate operations. */
110
+ export declare class WeappContainerController {
111
+ readonly sessionId: string;
112
+ private handlers;
113
+ private apiHandlers;
114
+ private calls;
115
+ private listeners;
116
+ private cleanupHandlers;
117
+ private cleanup?;
118
+ private cleanupTasks;
119
+ private cleanupTail;
120
+ private closing?;
121
+ private closeRequested;
122
+ private closed;
123
+ private constructor();
124
+ static create(configuration: Configuration): Promise<WeappContainerController>;
125
+ private command;
126
+ registerHostMethod(name: string, handler: HostHandler): Promise<void>;
127
+ configureHostServices(configuration: HostServicesConfiguration): Promise<void>;
128
+ registerApiHandler(name: string, handler: HostHandler): Promise<void>;
129
+ /**
130
+ * Install the standard mini-program JSAPI payment boundary.
131
+ * The handler must call the configured official payment SDK and resolve only
132
+ * after its terminal callback; backend order confirmation remains the host's
133
+ * responsibility.
134
+ */
135
+ installWxRequestPayment(handler: WxRequestPaymentHandler): Promise<void>;
136
+ /** Await custom resources before a new account owner can start. */
137
+ registerAccountCleanupHandler(handler: AccountCleanupHandler): () => void;
138
+ installNativeDeviceApis(options?: NativeDeviceApiOptions): Promise<void>;
139
+ retryAccountCleanup(): Promise<void>;
140
+ hostComponents(): Promise<JSONValue>;
141
+ authorizeInstalledPack(application: TrustedApplication): Promise<void>;
142
+ migrateLegacyStorage(sourceKey: string): Promise<void>;
143
+ deleteAccountData(principalId: string): Promise<JSONValue>;
144
+ emitHostApiEvent(event: JSONObject): Promise<void>;
145
+ submitHostComponentFrame(frame: JSONObject): Promise<JSONValue>;
146
+ emitHostComponentEvent(event: JSONObject): Promise<void>;
147
+ authorizePhoneButton(nodeId: string): Promise<void>;
148
+ prepareAccountHostServiceSnapshots(operationId: string, values: JSONObject): Promise<void>;
149
+ /** Async producers must capture this native owner before starting their work. */
150
+ updateHostServiceSnapshots(values: JSONObject, context?: HostSnapshotContext): Promise<void>;
151
+ switchAccount(account: HostAccount, launches?: JSONObject): Promise<JSONValue>;
152
+ queryAccountSwitch(operationId?: string): Promise<JSONValue>;
153
+ updateAccountSwitchLaunch(options: JSONObject): Promise<void>;
154
+ retryAccountSwitch(options?: JSONObject): Promise<void>;
155
+ cancelAccountSwitch(operationId: string): Promise<void>;
156
+ createHostBinary(bytes: Uint8Array): Promise<JSONValue>;
157
+ readHostBinary(id: string, offset: number, length: number): Promise<JSONValue>;
158
+ /** Read only the asset bound to an exact live API context; requires apiResourceChunks 1.0. */
159
+ readHostApiResource(context: HostApiCallContext, offset: number, length: number): Promise<JSONValue>;
160
+ retainHostBinary(id: string): Promise<void>;
161
+ releaseHostBinary(id: string): Promise<void>;
162
+ load(source: PackSource, options?: {
163
+ route?: string;
164
+ options?: JSONObject;
165
+ }): Promise<void>;
166
+ sendMessage(message: JSONValue): Promise<void>;
167
+ navigate(route: string, query?: JSONObject, replace?: boolean): Promise<void>;
168
+ back(): Promise<void>;
169
+ setForeground(visible: boolean): Promise<void>;
170
+ flushStorage(): Promise<void>;
171
+ state(): Promise<JSONValue>;
172
+ capabilities(): Promise<JSONValue>;
173
+ subscribe(listener: (event: ContainerEvent) => void): () => void;
174
+ close(): Promise<void>;
175
+ private receive;
176
+ private cleanupAccount;
177
+ private dispatchHostCall;
178
+ }
179
+ export type WeappContainerViewProps = ViewProps & {
180
+ controller: WeappContainerController;
181
+ onSurfaceError?: (error: {
182
+ code: string;
183
+ message: string;
184
+ }) => void;
185
+ };
186
+ export declare function WeappContainerView({ controller, onSurfaceError, ...props }: WeappContainerViewProps): React.JSX.Element;
187
+ /** Await before replacing an entire React surface or account. Failed close remains retryable. */
188
+ export declare function closeAllContainers(): Promise<void>;
package/lib/index.js ADDED
@@ -0,0 +1,362 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import Native from './specs/NativeWeappContainer';
3
+ import Surface from './specs/WeappContainerNativeComponent';
4
+ export class HostError extends Error {
5
+ code;
6
+ retryable;
7
+ details;
8
+ constructor(code, message, retryable = false, details = {}) {
9
+ super(message);
10
+ this.code = code;
11
+ this.retryable = retryable;
12
+ this.details = details;
13
+ }
14
+ }
15
+ function encode(value) {
16
+ const ancestors = new Set();
17
+ const check = (item) => {
18
+ if (item === null || typeof item === 'string' || typeof item === 'boolean')
19
+ return;
20
+ if (typeof item === 'number' && Number.isFinite(item))
21
+ return;
22
+ if (typeof item !== 'object' || ancestors.has(item))
23
+ throw new TypeError('Expected finite, acyclic JSON data');
24
+ if (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null)
25
+ throw new TypeError('Expected plain JSON data');
26
+ ancestors.add(item);
27
+ for (const child of Object.values(item))
28
+ check(child);
29
+ ancestors.delete(item);
30
+ };
31
+ check(value);
32
+ return JSON.stringify(value);
33
+ }
34
+ const owners = new Map();
35
+ const lifecycle = globalThis;
36
+ let disposed = false;
37
+ let subscription;
38
+ /** Session owner. Keep it outside render; detach and close are separate operations. */
39
+ export class WeappContainerController {
40
+ sessionId;
41
+ handlers = new Map();
42
+ apiHandlers = new Map();
43
+ calls = new Map();
44
+ listeners = new Set();
45
+ cleanupHandlers = new Set();
46
+ cleanup;
47
+ cleanupTasks = new Set();
48
+ cleanupTail = Promise.resolve();
49
+ closing;
50
+ closeRequested = false;
51
+ closed = false;
52
+ constructor(sessionId) {
53
+ this.sessionId = sessionId;
54
+ }
55
+ static async create(configuration) {
56
+ await lifecycle.__weappContainerCleanup;
57
+ if (disposed)
58
+ throw new Error('React Native module was disposed');
59
+ if (!configuration?.storage || (!('memoryOnly' in configuration.storage) && !configuration.storage.key?.trim()))
60
+ throw new TypeError('Select memoryOnly or a stable nonblank storage key');
61
+ subscription ??= Native.onEvent(event => owners.get(event.sessionId)?.receive(event.type, event.payload));
62
+ const id = await Native.create(encode(configuration));
63
+ if (disposed) {
64
+ await Native.invoke(id, 'close', '{}');
65
+ throw new Error('React Native module was disposed during create');
66
+ }
67
+ const controller = new WeappContainerController(id);
68
+ owners.set(id, controller);
69
+ if (configuration.hostServices) {
70
+ try {
71
+ await controller.configureHostServices(configuration.hostServices);
72
+ }
73
+ catch (error) {
74
+ await controller.close();
75
+ throw error;
76
+ }
77
+ }
78
+ return controller;
79
+ }
80
+ async command(operation, payload = {}) {
81
+ if (this.closed || this.closeRequested)
82
+ throw new Error('Container is closing or closed');
83
+ return JSON.parse(await Native.invoke(this.sessionId, operation, encode(payload)));
84
+ }
85
+ async registerHostMethod(name, handler) {
86
+ if (!name.trim() || name.startsWith('wx.') || this.handlers.has(name))
87
+ throw new TypeError('Host method must be unique and must not use the wx. namespace');
88
+ this.handlers.set(name, handler);
89
+ try {
90
+ await this.command('registerHostMethod', { name });
91
+ }
92
+ catch (error) {
93
+ this.handlers.delete(name);
94
+ throw error;
95
+ }
96
+ }
97
+ async configureHostServices(configuration) { await this.command('configureHostServices', configuration); }
98
+ async registerApiHandler(name, handler) {
99
+ if (this.apiHandlers.has(name))
100
+ throw new TypeError('API handler is already registered');
101
+ this.apiHandlers.set(name, handler);
102
+ try {
103
+ await this.command('registerApiHandler', { name });
104
+ }
105
+ catch (error) {
106
+ this.apiHandlers.delete(name);
107
+ throw error;
108
+ }
109
+ }
110
+ /**
111
+ * Install the standard mini-program JSAPI payment boundary.
112
+ * The handler must call the configured official payment SDK and resolve only
113
+ * after its terminal callback; backend order confirmation remains the host's
114
+ * responsibility.
115
+ */
116
+ async installWxRequestPayment(handler) {
117
+ await this.registerApiHandler('wx.requestPayment', async (payload, context) => {
118
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
119
+ throw new HostError('invalid_request', 'wx.requestPayment options are required');
120
+ }
121
+ const value = payload;
122
+ const fields = ['timeStamp', 'nonceStr', 'package', 'signType', 'paySign'];
123
+ for (const field of fields) {
124
+ if (typeof value[field] !== 'string' || value[field].trim().length === 0) {
125
+ throw new HostError('invalid_request', `wx.requestPayment requires non-empty ${field}`);
126
+ }
127
+ }
128
+ if (!['MD5', 'HMAC-SHA256', 'RSA'].includes(value.signType)) {
129
+ throw new HostError('invalid_request', 'wx.requestPayment signType must be MD5, HMAC-SHA256, or RSA');
130
+ }
131
+ await handler({
132
+ timeStamp: value.timeStamp,
133
+ nonceStr: value.nonceStr,
134
+ package: value.package,
135
+ signType: value.signType,
136
+ paySign: value.paySign,
137
+ }, context);
138
+ return { errMsg: 'requestPayment:ok' };
139
+ });
140
+ }
141
+ /** Await custom resources before a new account owner can start. */
142
+ registerAccountCleanupHandler(handler) {
143
+ if (this.closed || this.closeRequested)
144
+ throw new Error('Container is closing or closed');
145
+ this.cleanupHandlers.add(handler);
146
+ return () => this.cleanupHandlers.delete(handler);
147
+ }
148
+ async installNativeDeviceApis(options = {}) {
149
+ await this.command('installNativeDeviceApis', {
150
+ bluetooth: options.bluetooth ?? true,
151
+ allowedNetworkOrigins: [...(options.allowedNetworkOrigins ?? [])],
152
+ allowLoopbackForDevelopment: options.allowLoopbackForDevelopment ?? false,
153
+ allowedMediaOrigins: [...(options.allowedMediaOrigins ?? [])],
154
+ dedicatedAudioSession: options.dedicatedAudioSession ?? false,
155
+ nfc: options.nfc ?? false,
156
+ enableWifi: options.enableWifi ?? false,
157
+ ...(options.wifiConfiguration === undefined ? {} : { wifiConfiguration: { ...options.wifiConfiguration } }),
158
+ ...(options.nfcConfiguration === undefined ? {} : { nfcConfiguration: { ...options.nfcConfiguration } }),
159
+ });
160
+ }
161
+ async retryAccountCleanup() { await this.command('retryAccountCleanup'); }
162
+ hostComponents() { return this.command('hostComponents'); }
163
+ async authorizeInstalledPack(application) { await this.command('authorizeInstalledPack', application); }
164
+ async migrateLegacyStorage(sourceKey) { await this.command('migrateLegacyStorage', { sourceKey }); }
165
+ deleteAccountData(principalId) { return this.command('deleteAccountData', { principalId }); }
166
+ async emitHostApiEvent(event) { await this.command('hostApiEvent', event); }
167
+ submitHostComponentFrame(frame) { return this.command('hostComponentFrame', frame); }
168
+ async emitHostComponentEvent(event) { await this.command('hostComponentEvent', event); }
169
+ async authorizePhoneButton(nodeId) { await this.command('authorizePhoneButton', { nodeId }); }
170
+ async prepareAccountHostServiceSnapshots(operationId, values) { await this.command('prepareAccountHostServiceSnapshots', { operationId, values }); }
171
+ /** Async producers must capture this native owner before starting their work. */
172
+ async updateHostServiceSnapshots(values, context) { await this.command('updateHostServiceSnapshots', { values, ...(context === undefined ? {} : { context: context }) }); }
173
+ switchAccount(account, launches = {}) { return this.command('switchAccount', { account: account, launches }); }
174
+ queryAccountSwitch(operationId) { return this.command('queryAccountSwitch', operationId ? { operationId } : {}); }
175
+ async updateAccountSwitchLaunch(options) { await this.command('updateAccountSwitchLaunch', { options }); }
176
+ async retryAccountSwitch(options = {}) { await this.command('retryAccountSwitch', { options }); }
177
+ async cancelAccountSwitch(operationId) { await this.command('cancelAccountSwitch', { operationId }); }
178
+ createHostBinary(bytes) { return this.command('createHostBinary', { bytes: Array.from(bytes) }); }
179
+ readHostBinary(id, offset, length) { return this.command('readHostBinary', { id, offset, length }); }
180
+ /** Read only the asset bound to an exact live API context; requires apiResourceChunks 1.0. */
181
+ readHostApiResource(context, offset, length) { return this.command('hostApiResource', { context: context, offset, length }); }
182
+ async retainHostBinary(id) { await this.command('retainHostBinary', { id }); }
183
+ async releaseHostBinary(id) { await this.command('releaseHostBinary', { id }); }
184
+ async load(source, options = {}) {
185
+ await this.command('load', { ...source, ...(options.route === undefined ? {} : { route: options.route }), options: options.options ?? {} });
186
+ }
187
+ async sendMessage(message) { await this.command('sendMessage', { message }); }
188
+ async navigate(route, query = {}, replace = false) { await this.command('navigate', { route, query, replace }); }
189
+ async back() { await this.command('back'); }
190
+ async setForeground(visible) { await this.command('setForeground', { visible }); }
191
+ async flushStorage() { await this.command('flushStorage'); }
192
+ state() { return this.command('state'); }
193
+ capabilities() { return this.command('capabilities'); }
194
+ subscribe(listener) {
195
+ if (this.closed)
196
+ throw new Error('Container is closed');
197
+ this.listeners.add(listener);
198
+ return () => this.listeners.delete(listener);
199
+ }
200
+ close() {
201
+ if (this.closed)
202
+ return Promise.resolve();
203
+ if (this.closing)
204
+ return this.closing;
205
+ this.closeRequested = true;
206
+ for (const call of this.calls.values())
207
+ call.abort();
208
+ this.calls.clear();
209
+ this.cleanup?.abort.abort();
210
+ this.cleanup = undefined;
211
+ this.closing = (async () => {
212
+ // Superseded account cleanup must finish before resources are retired again.
213
+ await Promise.allSettled([...this.cleanupTasks]);
214
+ const abort = new AbortController();
215
+ const results = await Promise.allSettled([...this.cleanupHandlers].map(handler => Promise.resolve().then(() => handler({ operationId: `close:${this.sessionId}`, signal: abort.signal }))));
216
+ const failures = results.filter((result) => result.status === 'rejected');
217
+ if (failures.length)
218
+ throw new AggregateError(failures.map(result => result.reason), 'Container resource cleanup failed');
219
+ await Native.invoke(this.sessionId, 'close', '{}');
220
+ this.closed = true;
221
+ owners.delete(this.sessionId);
222
+ this.listeners.clear();
223
+ this.handlers.clear();
224
+ this.apiHandlers.clear();
225
+ this.cleanupHandlers.clear();
226
+ })().catch(error => { this.closing = undefined; throw error; });
227
+ return this.closing;
228
+ }
229
+ receive(type, payloadJSON) {
230
+ const payload = JSON.parse(payloadJSON);
231
+ if (type === 'accountSwitch' && payload.receipt?.phase === 'revoking') {
232
+ this.cleanup?.abort.abort();
233
+ for (const call of this.calls.values())
234
+ call.abort();
235
+ this.calls.clear();
236
+ }
237
+ if (type === 'accountCleanupRequired') {
238
+ if (this.closed)
239
+ return;
240
+ const task = this.cleanupAccount(String(payload.operationId));
241
+ this.cleanupTasks.add(task);
242
+ void task.finally(() => this.cleanupTasks.delete(task));
243
+ return;
244
+ }
245
+ if (type === 'accountCleanupCancelled') {
246
+ if (this.cleanup?.operationId === String(payload.operationId))
247
+ this.cleanup.abort.abort();
248
+ return;
249
+ }
250
+ if (type === 'hostCallCancelled') {
251
+ const id = String(payload.callId);
252
+ this.calls.get(id)?.abort();
253
+ this.calls.delete(id);
254
+ return;
255
+ }
256
+ if (type === 'hostCall') {
257
+ void this.dispatchHostCall(payload);
258
+ return;
259
+ }
260
+ for (const listener of this.listeners) {
261
+ try {
262
+ listener({ type: type, payload });
263
+ }
264
+ catch (error) {
265
+ console.error('WeappContainer event listener failed', error);
266
+ }
267
+ }
268
+ }
269
+ cleanupAccount(operationId) {
270
+ this.cleanup?.abort.abort();
271
+ const current = { operationId, abort: new AbortController() };
272
+ this.cleanup = current;
273
+ const run = async () => {
274
+ let response = { operationId };
275
+ const retired = () => this.cleanup !== current || current.abort.signal.aborted || this.closed || this.closeRequested;
276
+ try {
277
+ if (!retired()) {
278
+ const results = await Promise.allSettled([...this.cleanupHandlers].map(handler => Promise.resolve().then(() => handler({ operationId, signal: current.abort.signal }))));
279
+ const failures = results.filter((result) => result.status === 'rejected');
280
+ if (failures.length)
281
+ throw new AggregateError(failures.map(result => result.reason), 'Account resource cleanup failed');
282
+ }
283
+ }
284
+ catch (error) {
285
+ response.error = { code: 'ERR_ACCOUNT_CLEANUP', message: error instanceof Error ? error.message : String(error) };
286
+ }
287
+ if (retired())
288
+ response = { operationId, retired: true };
289
+ // Even a revoked/closing owner must finish its exact transport waiter.
290
+ // Native treats retired as cancellation and never as permission to start.
291
+ try {
292
+ await Native.invoke(this.sessionId, 'completeAccountCleanup', encode(response));
293
+ }
294
+ catch (error) {
295
+ if (!this.closed && !this.closing)
296
+ console.error('WeappContainer account cleanup reply failed', error);
297
+ }
298
+ finally {
299
+ if (this.cleanup === current)
300
+ this.cleanup = undefined;
301
+ }
302
+ };
303
+ // Cancellation gates the old operation immediately, but only its actual
304
+ // handler terminals release devices/files for the next account or close.
305
+ const task = this.cleanupTail.then(run, run);
306
+ this.cleanupTail = task.then(() => { }, () => { });
307
+ return task;
308
+ }
309
+ async dispatchHostCall(payload) {
310
+ const id = String(payload.callId);
311
+ if (this.closeRequested || this.closed) {
312
+ try {
313
+ await Native.completeHostCall(this.sessionId, id, encode({ error: { code: 'cancelled', message: 'Container is closing', retryable: false } }));
314
+ }
315
+ catch { /* Native close may already have cancelled this call. */ }
316
+ return;
317
+ }
318
+ const abort = new AbortController();
319
+ this.calls.set(id, abort);
320
+ let response;
321
+ try {
322
+ const handler = this.apiHandlers.get(String(payload.method)) ?? this.handlers.get(String(payload.method));
323
+ if (!handler)
324
+ throw new HostError('unsupported', 'Host method is not registered');
325
+ const result = await handler(payload.payload ?? null, { signal: abort.signal, callId: id, method: String(payload.method), ...(payload.deadlineNs == null ? {} : { deadlineNs: String(payload.deadlineNs) }), ...(payload.cancelToken == null ? {} : { cancelToken: String(payload.cancelToken) }), ...(payload.context ? { apiContext: payload.context } : {}) });
326
+ encode(result);
327
+ response = { result };
328
+ }
329
+ catch (error) {
330
+ response = { error: { code: error instanceof HostError ? error.code : 'invalid_request', message: error instanceof Error ? error.message : String(error), retryable: error instanceof HostError && error.retryable, details: error instanceof HostError ? error.details : {} } };
331
+ }
332
+ if (this.calls.get(id) !== abort || abort.signal.aborted)
333
+ return;
334
+ if (!(payload.retainUntilCancelled === true && response !== null && typeof response === 'object' && 'result' in response))
335
+ this.calls.delete(id);
336
+ try {
337
+ await Native.completeHostCall(this.sessionId, id, encode(response));
338
+ }
339
+ catch (error) {
340
+ if (!this.closing && !this.closed)
341
+ console.error('WeappContainer host reply failed', error);
342
+ }
343
+ }
344
+ }
345
+ export function WeappContainerView({ controller, onSurfaceError, ...props }) {
346
+ return _jsx(Surface, { ...props, sessionId: controller.sessionId, onSurfaceError: onSurfaceError ? event => onSurfaceError(event.nativeEvent) : undefined });
347
+ }
348
+ /** Await before replacing an entire React surface or account. Failed close remains retryable. */
349
+ export async function closeAllContainers() {
350
+ const results = await Promise.allSettled([...owners.values()].map(owner => owner.close()));
351
+ const failures = results.filter((result) => result.status === 'rejected');
352
+ if (failures.length)
353
+ throw new AggregateError(failures.map(result => result.reason), 'Container cleanup failed');
354
+ }
355
+ if (typeof module !== 'undefined' && module.hot)
356
+ module.hot.dispose(() => {
357
+ disposed = true;
358
+ const cleanup = closeAllContainers().finally(() => { subscription?.remove(); subscription = undefined; });
359
+ lifecycle.__weappContainerCleanup = cleanup;
360
+ // Retain the rejection for the next create, and avoid an unhandled promise rejection meanwhile.
361
+ void cleanup.catch(error => console.error('WeappContainer Fast Refresh cleanup failed', error));
362
+ });
@@ -0,0 +1,14 @@
1
+ import type { TurboModule, CodegenTypes } from 'react-native';
2
+ export type NativeEvent = Readonly<{
3
+ sessionId: string;
4
+ type: string;
5
+ payload: string;
6
+ }>;
7
+ export interface Spec extends TurboModule {
8
+ create(configuration: string): Promise<string>;
9
+ invoke(sessionId: string, operation: string, payload: string): Promise<string>;
10
+ completeHostCall(sessionId: string, callId: string, response: string): Promise<void>;
11
+ readonly onEvent: CodegenTypes.EventEmitter<NativeEvent>;
12
+ }
13
+ declare const _default: Spec;
14
+ export default _default;
@@ -0,0 +1,2 @@
1
+ import { TurboModuleRegistry } from 'react-native';
2
+ export default TurboModuleRegistry.getEnforcing('WeappContainer');
@@ -0,0 +1,11 @@
1
+ import type { ViewProps, HostComponent, CodegenTypes } from 'react-native';
2
+ type SurfaceError = Readonly<{
3
+ code: string;
4
+ message: string;
5
+ }>;
6
+ export interface NativeProps extends ViewProps {
7
+ sessionId: string;
8
+ onSurfaceError?: CodegenTypes.DirectEventHandler<SurfaceError>;
9
+ }
10
+ declare const _default: HostComponent<NativeProps>;
11
+ export default _default;
@@ -0,0 +1,2 @@
1
+ import { codegenNativeComponent } from 'react-native';
2
+ export default codegenNativeComponent('WeappContainerNativeView');
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@weapp-container/react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-preview.7.1",
4
+ "description": "Native mini-program sessions for React Native Fabric and TurboModules",
5
+ "license": "Apache-2.0",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "react-native": "src/index.tsx",
9
+ "source": "src/index.tsx",
10
+ "files": [
11
+ "lib",
12
+ "src",
13
+ "ios",
14
+ "android",
15
+ "sdk-artifact.json",
16
+ "WeappContainerReactNative.podspec",
17
+ "react-native.config.js",
18
+ "README.md",
19
+ "README.en.md",
20
+ "LICENSE"
21
+ ],
22
+ "peerDependencies": {
23
+ "react": "^19.3.0",
24
+ "react-native": "0.88.0"
25
+ },
26
+ "codegenConfig": {
27
+ "name": "WeappContainerSpec",
28
+ "type": "all",
29
+ "jsSrcsDir": "src/specs",
30
+ "android": {
31
+ "javaPackageName": "com.sonofmagic.weapp.container.reactnative"
32
+ },
33
+ "ios": {
34
+ "modules": {
35
+ "WeappContainer": {
36
+ "className": "WCRNModule"
37
+ }
38
+ },
39
+ "componentProvider": {
40
+ "WeappContainerNativeView": "WCRNComponentView"
41
+ }
42
+ }
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/weapp-container/sdk-react-native.git"
47
+ },
48
+ "homepage": "https://github.com/weapp-container/sdk-react-native",
49
+ "publishConfig": {
50
+ "access": "public",
51
+ "registry": "https://registry.npmjs.org/",
52
+ "tag": "preview"
53
+ }
54
+ }
@@ -0,0 +1 @@
1
+ module.exports = {dependency: {platforms: {ios: {}, android: {sourceDir: 'android', packageImportPath: 'import com.sonofmagic.weapp.container.reactnative.WeappContainerPackage;', packageInstance: 'new WeappContainerPackage()'}}}};