@opendesignai/shell-sdk 0.0.0-stage → 0.1.0-alpha.0
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/LICENSE +201 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.js +108 -0
- package/dist/invoke-DBtKZU28.js +16 -0
- package/dist/react.d.ts +183 -0
- package/dist/react.js +435 -0
- package/package.json +63 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@opendesignai/shell-sdk`: what product apps use to talk to the shell.
|
|
3
|
+
*
|
|
4
|
+
* A typed layer over the four host bridge methods. Each capability is a group of methods
|
|
5
|
+
* (`sdk.session.getAccount()`) plus `on(event, callback)` for its events. Every method
|
|
6
|
+
* resolves to a `HostInvokeResult`; nothing here throws, even when the bridge misbehaves.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* export async function mount(el: HTMLElement, ctx: MountContext) {
|
|
10
|
+
* const sdk = await connectShell(ctx.bridge);
|
|
11
|
+
* const account = await sdk.session.getAccount();
|
|
12
|
+
* if (sdk.models) { … } // optional capability: undefined when the shell lacks it
|
|
13
|
+
* }
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
import { CapabilityId, CapabilityId as CapabilityId$1, CapabilityRegistry, CapabilitySpec, HostCapabilityDescriptor, HostInvokeResult, HostInvokeResult as HostInvokeResult$1, InvokeOptions, KnownCapabilityId, MountContext, MountHandle, ProductManifest, ProductMount, UniversalHostBridge } from "@opendesignai/contracts";
|
|
17
|
+
type Params<S extends CapabilitySpec, M extends keyof S["methods"]> = S["methods"][M]["params"];
|
|
18
|
+
type Result<S extends CapabilitySpec, M extends keyof S["methods"]> = Promise<HostInvokeResult$1<S["methods"][M]["result"]>>;
|
|
19
|
+
/** Typed methods of one capability; params are optional when every field is. */
|
|
20
|
+
export type MethodClient<S extends CapabilitySpec> = { readonly [M in keyof S["methods"]]: {} extends Params<S, M> ? (params?: Params<S, M>) => Result<S, M> : (params: Params<S, M>) => Result<S, M>; };
|
|
21
|
+
export type EventClient<S extends CapabilitySpec> = {
|
|
22
|
+
/** Subscribes to one of the capability's events; returns the unsubscribe function. */
|
|
23
|
+
on<E extends keyof S["events"] & string>(event: E, callback: (payload: S["events"][E]) => void): () => void;
|
|
24
|
+
};
|
|
25
|
+
/** One capability as a group: its methods plus `on` (so no capability may name a method `on`). */
|
|
26
|
+
export type CapabilityClient<Id extends KnownCapabilityId> = MethodClient<CapabilityRegistry[Id]> & EventClient<CapabilityRegistry[Id]>;
|
|
27
|
+
export interface ShellSdk {
|
|
28
|
+
bridge: UniversalHostBridge;
|
|
29
|
+
/** True when the shell offers the capability with status `available` or `degraded`. */
|
|
30
|
+
available(id: CapabilityId$1): boolean;
|
|
31
|
+
session: CapabilityClient<"session@1">;
|
|
32
|
+
billing: CapabilityClient<"billing@1">;
|
|
33
|
+
tracking: CapabilityClient<"tracking@1">;
|
|
34
|
+
i18n: CapabilityClient<"i18n@1">;
|
|
35
|
+
storage: CapabilityClient<"storage@1">;
|
|
36
|
+
projects: CapabilityClient<"projects@1">;
|
|
37
|
+
chrome: CapabilityClient<"chrome@1">;
|
|
38
|
+
/** Publish with `events.publish({ topic, payload })`; subscribe with `events.on(topic, …)`. */
|
|
39
|
+
events: CapabilityClient<"events@1">;
|
|
40
|
+
/** Optional capability: undefined when the shell does not offer `models@1`. */
|
|
41
|
+
models: CapabilityClient<"models@1"> | undefined;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Builds the SDK from a bridge and the shell's capability list (`await bridge.capabilities()`).
|
|
45
|
+
* Groups for capabilities the shell lacks still exist and resolve to `UNSUPPORTED`, except
|
|
46
|
+
* optional ones (`models`), which are `undefined`; check `available()` for the rest.
|
|
47
|
+
*/
|
|
48
|
+
export declare function createShellSdk(bridge: UniversalHostBridge, capabilities: readonly HostCapabilityDescriptor[]): ShellSdk;
|
|
49
|
+
export declare function withInvokeOptions(sdk: ShellSdk, options: InvokeOptions): ShellSdk;
|
|
50
|
+
export declare function confirmLeave(sdk: ShellSdk, requestId: string): Promise<HostInvokeResult$1<null>>;
|
|
51
|
+
/**
|
|
52
|
+
* Asks the shell for its capabilities, then builds the SDK. Never rejects: if the shell cannot
|
|
53
|
+
* list them (`capabilities()` throws, rejects or returns something other than a list), the SDK
|
|
54
|
+
* offers none, so `available()` is false and `models` undefined, while the core groups still
|
|
55
|
+
* call the bridge.
|
|
56
|
+
*/
|
|
57
|
+
export declare function connectShell(bridge: UniversalHostBridge): Promise<ShellSdk>;
|
|
58
|
+
export type { CapabilityId, HostInvokeResult, MountContext, MountHandle, ProductManifest, ProductMount };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { CHROME_V1, capabilityDefinition, hostErr, toCapabilityId } from "@opendesignai/contracts";
|
|
2
|
+
import { n as invokeLeaveConfirmation, t as invoke } from "./invoke-DBtKZU28.js";
|
|
3
|
+
// src/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* `@opendesignai/shell-sdk`: what product apps use to talk to the shell.
|
|
6
|
+
*
|
|
7
|
+
* A typed layer over the four host bridge methods. Each capability is a group of methods
|
|
8
|
+
* (`sdk.session.getAccount()`) plus `on(event, callback)` for its events. Every method
|
|
9
|
+
* resolves to a `HostInvokeResult`; nothing here throws, even when the bridge misbehaves.
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* export async function mount(el: HTMLElement, ctx: MountContext) {
|
|
13
|
+
* const sdk = await connectShell(ctx.bridge);
|
|
14
|
+
* const account = await sdk.session.getAccount();
|
|
15
|
+
* if (sdk.models) { … } // optional capability: undefined when the shell lacks it
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Builds the SDK from a bridge and the shell's capability list (`await bridge.capabilities()`).
|
|
21
|
+
* Groups for capabilities the shell lacks still exist and resolve to `UNSUPPORTED`, except
|
|
22
|
+
* optional ones (`models`), which are `undefined`; check `available()` for the rest.
|
|
23
|
+
*/
|
|
24
|
+
function createShellSdk(bridge, capabilities) {
|
|
25
|
+
const offered = /* @__PURE__ */ new Set();
|
|
26
|
+
const chromeMethods = /* @__PURE__ */ new Set();
|
|
27
|
+
for (const descriptor of capabilities) {
|
|
28
|
+
if (typeof descriptor !== "object" || descriptor === null) continue;
|
|
29
|
+
const { name, version, status } = descriptor;
|
|
30
|
+
const id = toCapabilityId(name, version);
|
|
31
|
+
if (!id || status === "unavailable") continue;
|
|
32
|
+
offered.add(id);
|
|
33
|
+
if (id === "chrome@1") {
|
|
34
|
+
const { methods } = descriptor;
|
|
35
|
+
if (Array.isArray(methods)) {
|
|
36
|
+
for (const method of CHROME_V1.optionalMethods ?? []) if (methods.includes(method)) chromeMethods.add(method);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return sdkForBridge(bridge, (id) => offered.has(id), offered.has("models@1"), [...chromeMethods]);
|
|
41
|
+
}
|
|
42
|
+
function withInvokeOptions(sdk, options) {
|
|
43
|
+
const original = sdk.bridge;
|
|
44
|
+
const defaults = { ...options };
|
|
45
|
+
const bridge = {
|
|
46
|
+
info: () => original.info(),
|
|
47
|
+
capabilities: () => original.capabilities(),
|
|
48
|
+
invoke: (capability, method, params, overrides) => original.invoke(capability, method, params, {
|
|
49
|
+
...defaults,
|
|
50
|
+
...overrides
|
|
51
|
+
}),
|
|
52
|
+
subscribe: (capability, event, callback) => original.subscribe(capability, event, callback)
|
|
53
|
+
};
|
|
54
|
+
const chromeMethods = (CHROME_V1.optionalMethods ?? []).filter((method) => Object.hasOwn(sdk.chrome, method));
|
|
55
|
+
return sdkForBridge(bridge, (id) => sdk.available(id), sdk.models !== void 0, chromeMethods);
|
|
56
|
+
}
|
|
57
|
+
async function confirmLeave(sdk, requestId) {
|
|
58
|
+
if (sdk.chrome.confirmLeave === void 0) return hostErr("UNSUPPORTED", "the shell did not advertise chrome@1 confirmLeave");
|
|
59
|
+
return invokeLeaveConfirmation(sdk.bridge, requestId);
|
|
60
|
+
}
|
|
61
|
+
function sdkForBridge(bridge, available, includeModels, chromeMethods) {
|
|
62
|
+
return Object.freeze({
|
|
63
|
+
bridge,
|
|
64
|
+
available,
|
|
65
|
+
session: client(bridge, "session@1"),
|
|
66
|
+
billing: client(bridge, "billing@1"),
|
|
67
|
+
tracking: client(bridge, "tracking@1"),
|
|
68
|
+
i18n: client(bridge, "i18n@1"),
|
|
69
|
+
storage: client(bridge, "storage@1"),
|
|
70
|
+
projects: client(bridge, "projects@1"),
|
|
71
|
+
chrome: client(bridge, "chrome@1", chromeMethods),
|
|
72
|
+
events: client(bridge, "events@1"),
|
|
73
|
+
models: includeModels ? client(bridge, "models@1") : void 0
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Asks the shell for its capabilities, then builds the SDK. Never rejects: if the shell cannot
|
|
78
|
+
* list them (`capabilities()` throws, rejects or returns something other than a list), the SDK
|
|
79
|
+
* offers none, so `available()` is false and `models` undefined, while the core groups still
|
|
80
|
+
* call the bridge.
|
|
81
|
+
*/
|
|
82
|
+
async function connectShell(bridge) {
|
|
83
|
+
let capabilities = [];
|
|
84
|
+
try {
|
|
85
|
+
const listed = await bridge.capabilities();
|
|
86
|
+
if (Array.isArray(listed)) capabilities = listed;
|
|
87
|
+
} catch {}
|
|
88
|
+
return createShellSdk(bridge, capabilities);
|
|
89
|
+
}
|
|
90
|
+
function client(bridge, id, optionalMethods = []) {
|
|
91
|
+
const group = {};
|
|
92
|
+
for (const method of [...capabilityDefinition(id)?.methods ?? [], ...optionalMethods]) group[method] = (params) => invoke(bridge, id, method, params);
|
|
93
|
+
group.on = (event, callback) => subscribe(bridge, id, event, callback);
|
|
94
|
+
return Object.freeze(group);
|
|
95
|
+
}
|
|
96
|
+
function subscribe(bridge, id, event, callback) {
|
|
97
|
+
try {
|
|
98
|
+
const unsubscribe = bridge.subscribe(id, event, callback);
|
|
99
|
+
return () => {
|
|
100
|
+
try {
|
|
101
|
+
unsubscribe();
|
|
102
|
+
} catch {}
|
|
103
|
+
};
|
|
104
|
+
} catch {
|
|
105
|
+
return () => {};
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export { confirmLeave, connectShell, createShellSdk, withInvokeOptions };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { hostErr, hostOk, isHostInvokeResult } from "@opendesignai/contracts";
|
|
2
|
+
// src/invoke.ts
|
|
3
|
+
async function invoke(bridge, id, method, params) {
|
|
4
|
+
try {
|
|
5
|
+
const result = await bridge.invoke(id, method, params);
|
|
6
|
+
return isHostInvokeResult(result) ? result : hostErr("INTERNAL_ERROR", `the shell returned a malformed result for ${id} ${method}`);
|
|
7
|
+
} catch (error) {
|
|
8
|
+
return hostErr("INTERNAL_ERROR", error instanceof Error ? error.message : String(error));
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
async function invokeLeaveConfirmation(bridge, requestId) {
|
|
12
|
+
const result = await invoke(bridge, "chrome@1", "confirmLeave", { requestId });
|
|
13
|
+
if (!result.ok) return result;
|
|
14
|
+
return result.data === null ? hostOk(null) : hostErr("INTERNAL_ERROR", "chrome@1 confirmLeave returned non-null data");
|
|
15
|
+
}
|
|
16
|
+
export { invokeLeaveConfirmation as n, invoke as t };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@opendesignai/shell-sdk/react`: React adapters over the shell SDK, for products moving off
|
|
3
|
+
* the shell's own modules. They keep the signatures product code already calls, so moving is a
|
|
4
|
+
* change of import path. One exception: `Tracker.track` and `Tracker.send` take `Events[E]`, so a
|
|
5
|
+
* parameter they are passed to as values must be typed with the same event map, not with a type
|
|
6
|
+
* derived per event some other way (docs/contract.md §8 links the migration guide).
|
|
7
|
+
*
|
|
8
|
+
* Every adapter reaches the shell through `MountContext.bridge` and the core SDK; none imports
|
|
9
|
+
* shell code or writes to the document. React is a peer dependency. Components read the SDK,
|
|
10
|
+
* with the shell's capability list, through `useShellSdk()`.
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* export async function mount(el: HTMLElement, ctx: MountContext): Promise<MountHandle> {
|
|
14
|
+
* const sdk = await connectShell(ctx.bridge);
|
|
15
|
+
* const disconnect = tracker.connect(ctx);
|
|
16
|
+
* const root = createRoot(el);
|
|
17
|
+
* root.render(createElement(ShellProvider, { context: ctx, sdk }, createElement(App)));
|
|
18
|
+
* return { unmount: () => { root.unmount(); disconnect(); } };
|
|
19
|
+
* }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
import { ChromeV1, HostInvokeResult, MountContext } from "@opendesignai/contracts";
|
|
23
|
+
import { JSX, ReactNode } from "react";
|
|
24
|
+
import { ShellSdk } from "@opendesignai/shell-sdk";
|
|
25
|
+
interface ShellProviderProps {
|
|
26
|
+
/** The context the shell passed to `mount(el, ctx)`. */
|
|
27
|
+
context: MountContext;
|
|
28
|
+
/**
|
|
29
|
+
* The mount's SDK, from `await connectShell(ctx.bridge)` in `mount()`; it must be connected to
|
|
30
|
+
* `context.bridge`, or the provider throws. With it, `useShellSdk()` returns it from the first
|
|
31
|
+
* render. Without it, the provider asks the shell for its capabilities itself when it mounts,
|
|
32
|
+
* and `useShellSdk()` returns null until they arrive.
|
|
33
|
+
*/
|
|
34
|
+
sdk?: ShellSdk;
|
|
35
|
+
children?: ReactNode;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Gives the components below it the product's mount context. Render it at the product's root,
|
|
39
|
+
* from `mount()`, with the context the shell passed and the SDK connected to its bridge:
|
|
40
|
+
*
|
|
41
|
+
* ```ts
|
|
42
|
+
* const sdk = await connectShell(ctx.bridge);
|
|
43
|
+
* root.render(createElement(ShellProvider, { context: ctx, sdk }, createElement(App)));
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export declare function ShellProvider({ context, children }: ShellProviderProps): JSX.Element;
|
|
47
|
+
/**
|
|
48
|
+
* The mount's SDK, with the shell's capability list: `available()` and `models` say what the
|
|
49
|
+
* shell offers. It is the `sdk` given to the nearest `ShellProvider`, or the SDK the provider
|
|
50
|
+
* connected itself. Null outside a `ShellProvider` and, when the provider got no `sdk`, until
|
|
51
|
+
* the shell has answered `capabilities()`; the component renders again when it has. If the
|
|
52
|
+
* shell cannot list its capabilities, the SDK offers none (as from `connectShell`).
|
|
53
|
+
*/
|
|
54
|
+
export declare function useShellSdk(): ShellSdk | null;
|
|
55
|
+
/** One locale a product has messages for: `{ locale: "zh-CN", label: "简体中文" }`. */
|
|
56
|
+
type LanguageOption = {
|
|
57
|
+
readonly locale: string;
|
|
58
|
+
readonly label: string;
|
|
59
|
+
};
|
|
60
|
+
/** The locales of a `languages` list, as a union: `"en" | "zh-CN" | …`. */
|
|
61
|
+
type LocaleOf<Languages extends readonly LanguageOption[]> = Languages[number]["locale"];
|
|
62
|
+
/** Interpolation values for `t()`, as the product's `translate` takes them. */
|
|
63
|
+
type MessageValues = Record<string, string | number>;
|
|
64
|
+
/** The product's own messages, passed to `createI18n` once. */
|
|
65
|
+
interface MessageCatalog<Languages extends readonly LanguageOption[], Values> {
|
|
66
|
+
/** Locales the product has messages for, in menu order. `languages` returns it as is. */
|
|
67
|
+
languages: Languages;
|
|
68
|
+
/** Translates `message` (the source text or key) into `locale`. */
|
|
69
|
+
translate: (locale: LocaleOf<Languages>, message: string, values?: Values, context?: string) => string;
|
|
70
|
+
/** Maps translated text back to its source message; `sourceMessage` uses it when present. */
|
|
71
|
+
sourceMessage?: (message: string, locale?: LocaleOf<Languages>) => string;
|
|
72
|
+
/** Whether `locale`'s messages are loaded; without it every locale counts as loaded. */
|
|
73
|
+
isLocaleLoaded?: (locale: LocaleOf<Languages>) => boolean;
|
|
74
|
+
/** Loads `locale`'s messages; the current locale stays on screen until they arrive. */
|
|
75
|
+
ensureLocaleLoaded?: (locale: LocaleOf<Languages>) => Promise<void>;
|
|
76
|
+
/** Locale for when the shell's is not in `languages`; defaults to the first entry. */
|
|
77
|
+
fallbackLocale?: LocaleOf<Languages>;
|
|
78
|
+
}
|
|
79
|
+
/** What `useI18n()` returns. */
|
|
80
|
+
interface I18nTools<Locale extends string, Values> {
|
|
81
|
+
locale: Locale;
|
|
82
|
+
t: (message: string, values?: Values, context?: string) => string;
|
|
83
|
+
formatDate: (date: number | Date, options?: Intl.DateTimeFormatOptions) => string;
|
|
84
|
+
formatNumber: (number: number, options?: Intl.NumberFormatOptions) => string;
|
|
85
|
+
/** Asks the shell to switch the whole app's language; ignores locales not in `languages`. */
|
|
86
|
+
setLocale: (locale: Locale) => void;
|
|
87
|
+
}
|
|
88
|
+
interface I18nProviderProps<Locale extends string> {
|
|
89
|
+
children: ReactNode;
|
|
90
|
+
/**
|
|
91
|
+
* The locale without a `ShellProvider` (tests, standalone use). Ignored inside one: the
|
|
92
|
+
* shell's locale applies, resolved as for `localeChanged`.
|
|
93
|
+
*/
|
|
94
|
+
initialLocale?: Locale;
|
|
95
|
+
}
|
|
96
|
+
/** The adapters `createI18n` returns, bound to one product's catalog. */
|
|
97
|
+
interface I18nAdapters<Languages extends readonly LanguageOption[], Values> {
|
|
98
|
+
I18nProvider: (props: I18nProviderProps<LocaleOf<Languages>>) => JSX.Element;
|
|
99
|
+
useI18n: () => I18nTools<LocaleOf<Languages>, Values>;
|
|
100
|
+
languages: Languages;
|
|
101
|
+
/** The catalog's `sourceMessage`; returns `message` unchanged when the catalog has none. */
|
|
102
|
+
sourceMessage: (message: string, locale?: LocaleOf<Languages>) => string;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Binds the i18n adapters to the product's message catalog. Call it once per product and export
|
|
106
|
+
* the results under the names the product's code imports:
|
|
107
|
+
*
|
|
108
|
+
* ```ts
|
|
109
|
+
* export const { I18nProvider, useI18n, languages, sourceMessage } = createI18n(messages);
|
|
110
|
+
* ```
|
|
111
|
+
*
|
|
112
|
+
* `I18nProvider` follows the shell's locale when it is inside a `ShellProvider`. A component
|
|
113
|
+
* outside any `I18nProvider` gets the fallback locale and a `setLocale` that does nothing.
|
|
114
|
+
*/
|
|
115
|
+
export declare function createI18n<const Languages extends readonly LanguageOption[], Values = MessageValues>(catalog: MessageCatalog<Languages, Values>): I18nAdapters<Languages, Values>;
|
|
116
|
+
/**
|
|
117
|
+
* Shows `title` as the page title while the calling component is mounted, through `chrome@1`
|
|
118
|
+
* `setTitle`. Titles stack: the most recently set one shows, and when its component unmounts
|
|
119
|
+
* the one below it shows again; with none left the shell's default title returns
|
|
120
|
+
* (`setTitle({ title: null })`). An empty, null or undefined title sets nothing.
|
|
121
|
+
*
|
|
122
|
+
* Never writes `document.title` itself; outside a `ShellProvider` it does nothing.
|
|
123
|
+
*/
|
|
124
|
+
export declare function useRouteDocumentTitle(title: string | null | undefined): void;
|
|
125
|
+
export declare function useLeaveGuard(message: string | null | undefined, options: {
|
|
126
|
+
onLeave: (request: ChromeV1["events"]["leaveRequested"]) => void | Promise<void>;
|
|
127
|
+
}): (requestId: string) => Promise<HostInvokeResult<null>>;
|
|
128
|
+
/**
|
|
129
|
+
* How `track` ended:
|
|
130
|
+
*
|
|
131
|
+
* - `queued`: the shell accepted the event.
|
|
132
|
+
* - `disabled`: tracking is off (consent, Do Not Track); not an error.
|
|
133
|
+
* - `invalid`: the shell refused the event (`INVALID_PARAMS`), e.g. properties that are not JSON.
|
|
134
|
+
* - `duplicate`: the shell already had this event (`CONFLICT`).
|
|
135
|
+
* - `full`: the shell is busy or its queue is full (`BUSY`, `QUOTA_EXCEEDED`).
|
|
136
|
+
* - `config_unavailable`: no shell to send to: the tracker is not connected, mounts with
|
|
137
|
+
* different bridges are connected to it at once (see `Tracker.connect`), the shell lacks
|
|
138
|
+
* `tracking@1`, or the call failed.
|
|
139
|
+
*/
|
|
140
|
+
type TrackReceipt = "config_unavailable" | "disabled" | "invalid" | "duplicate" | "full" | "queued";
|
|
141
|
+
/**
|
|
142
|
+
* How `flush` ended: `accepted` (sent), `retry` (the shell is busy or timed out), `drop` (the
|
|
143
|
+
* call failed), `disabled` (no shell, mounts with different bridges connected at once, or the
|
|
144
|
+
* shell lacks `tracking@1`). `empty` is never returned through the bridge; it stays in the type
|
|
145
|
+
* for code written against older receipts.
|
|
146
|
+
*/
|
|
147
|
+
type FlushReceipt = "accepted" | "retry" | "drop" | "disabled" | "empty";
|
|
148
|
+
/** A product's events: event name → its properties. */
|
|
149
|
+
type TrackedEvents = Record<string, object>;
|
|
150
|
+
interface Tracker<Events extends TrackedEvents> {
|
|
151
|
+
/**
|
|
152
|
+
* Sends events from now on through this mount's bridge; call it in `mount()` and the returned
|
|
153
|
+
* function in `unmount()`. Before that, `track` resolves to `config_unavailable`.
|
|
154
|
+
*
|
|
155
|
+
* Each mount gets its own connection, and disconnecting one never affects another. While
|
|
156
|
+
* every connected mount has the same bridge, calls go to it. Mounts with different bridges at
|
|
157
|
+
* once (an overlapping remount, several instances of the product) leave a call no way to say
|
|
158
|
+
* which mount it comes from, so the tracker sends nothing (`config_unavailable`, `disabled`)
|
|
159
|
+
* and reports it with `console.error` until one bridge is left. A product that runs several
|
|
160
|
+
* mounts at once creates one tracker per mount.
|
|
161
|
+
*/
|
|
162
|
+
connect: (context: Pick<MountContext, "bridge">) => () => void;
|
|
163
|
+
/** Sends an event; never rejects. */
|
|
164
|
+
track: <E extends keyof Events>(event: E, properties: Events[E]) => Promise<TrackReceipt>;
|
|
165
|
+
/** Sends an event and returns nothing: reporting never interrupts the page. */
|
|
166
|
+
send: <E extends keyof Events>(event: E, properties: Events[E]) => void;
|
|
167
|
+
/** Asks the shell to send queued events now, e.g. before navigating away; never rejects. */
|
|
168
|
+
flush: () => Promise<FlushReceipt>;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Creates the product's tracker. Create it once, connect it in `mount()`, and export its
|
|
172
|
+
* methods under the names the product's code imports:
|
|
173
|
+
*
|
|
174
|
+
* ```ts
|
|
175
|
+
* export const tracker = createTracker<ProductEvents>();
|
|
176
|
+
* export const { track, send, flush } = tracker;
|
|
177
|
+
* ```
|
|
178
|
+
*
|
|
179
|
+
* The exported functions know no mount: they serve whichever mounts are connected, as long as
|
|
180
|
+
* those share one bridge (see `connect`).
|
|
181
|
+
*/
|
|
182
|
+
export declare function createTracker<Events extends TrackedEvents>(): Tracker<Events>;
|
|
183
|
+
export type { FlushReceipt, I18nAdapters, I18nProviderProps, I18nTools, LanguageOption, LocaleOf, MessageCatalog, MessageValues, ShellProviderProps, TrackReceipt, TrackedEvents, Tracker };
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { createContext, createElement, useCallback, useContext, useEffect, useEffectEvent, useId, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { confirmLeave, connectShell, createShellSdk } from "@opendesignai/shell-sdk";
|
|
3
|
+
import { LEAVE_GUARD_TIMEOUT_MS, hostErr, negotiateLocale } from "@opendesignai/contracts";
|
|
4
|
+
import { n as invokeLeaveConfirmation } from "./invoke-DBtKZU28.js";
|
|
5
|
+
// src/react/binding.ts
|
|
6
|
+
const ShellContext = createContext(null);
|
|
7
|
+
/** The binding of the nearest `ShellProvider`, or null outside one (tests, standalone use). */
|
|
8
|
+
function useShellBinding() {
|
|
9
|
+
return useContext(ShellContext);
|
|
10
|
+
}
|
|
11
|
+
/** A title stack that shows its top title through `chrome`, and null when it is empty. */
|
|
12
|
+
function titleStack(chrome) {
|
|
13
|
+
const entries = [];
|
|
14
|
+
let shown = null;
|
|
15
|
+
let scheduled = false;
|
|
16
|
+
const sync = () => {
|
|
17
|
+
if (scheduled) return;
|
|
18
|
+
scheduled = true;
|
|
19
|
+
queueMicrotask(() => {
|
|
20
|
+
scheduled = false;
|
|
21
|
+
const top = entries.at(-1)?.title ?? null;
|
|
22
|
+
if (top === shown) return;
|
|
23
|
+
shown = top;
|
|
24
|
+
chrome.setTitle({ title: top });
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
return { push(title) {
|
|
28
|
+
const entry = { title };
|
|
29
|
+
entries.push(entry);
|
|
30
|
+
sync();
|
|
31
|
+
return () => {
|
|
32
|
+
const index = entries.lastIndexOf(entry);
|
|
33
|
+
if (index !== -1) entries.splice(index, 1);
|
|
34
|
+
sync();
|
|
35
|
+
};
|
|
36
|
+
} };
|
|
37
|
+
}
|
|
38
|
+
// src/react/core-clients.ts
|
|
39
|
+
/**
|
|
40
|
+
* The core groups for `bridge`, before or without the shell's capability list. The SDK builds
|
|
41
|
+
* them whatever the list says (a capability the shell lacks answers `UNSUPPORTED`); only
|
|
42
|
+
* `available()` and `models` depend on the list. Built from no list those two would say the
|
|
43
|
+
* shell offers nothing, so they are left out here and never reach a product.
|
|
44
|
+
*/
|
|
45
|
+
function coreClients(bridge) {
|
|
46
|
+
const { i18n, chrome, tracking } = createShellSdk(bridge, []);
|
|
47
|
+
return {
|
|
48
|
+
i18n,
|
|
49
|
+
chrome,
|
|
50
|
+
tracking
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// src/react/leave-guards.ts
|
|
54
|
+
function createLeaveGuards(chrome, bridge, aggregateId) {
|
|
55
|
+
const guards = /* @__PURE__ */ new Map();
|
|
56
|
+
const removed = /* @__PURE__ */ new Set();
|
|
57
|
+
const aggregate = /* @__PURE__ */ new Map();
|
|
58
|
+
let aggregateMessage = null;
|
|
59
|
+
let slots = false;
|
|
60
|
+
let connectedSdk = null;
|
|
61
|
+
let unsubscribe;
|
|
62
|
+
let requests = 0;
|
|
63
|
+
const write = (id, message) => {
|
|
64
|
+
chrome.setLeaveGuard({
|
|
65
|
+
id,
|
|
66
|
+
guard: message === null ? null : { message }
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
const set = (id, message) => {
|
|
70
|
+
if (slots) {
|
|
71
|
+
write(id, message);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (message === null) aggregate.delete(id);
|
|
75
|
+
else aggregate.set(id, message);
|
|
76
|
+
const next = aggregate.values().next().value ?? null;
|
|
77
|
+
if (next === aggregateMessage) return;
|
|
78
|
+
aggregateMessage = next;
|
|
79
|
+
write(aggregateId, next);
|
|
80
|
+
};
|
|
81
|
+
const clear = (id) => set(id, null);
|
|
82
|
+
const confirm = (requestId) => connectedSdk ? confirmLeave(connectedSdk, requestId) : invokeLeaveConfirmation(bridge, requestId);
|
|
83
|
+
async function leave(request) {
|
|
84
|
+
const current = [...guards];
|
|
85
|
+
requests += 1;
|
|
86
|
+
let finished = false;
|
|
87
|
+
const finish = () => {
|
|
88
|
+
if (finished) return;
|
|
89
|
+
finished = true;
|
|
90
|
+
clearTimeout(timeout);
|
|
91
|
+
requests -= 1;
|
|
92
|
+
if (requests === 0) {
|
|
93
|
+
for (const id of removed) clear(id);
|
|
94
|
+
removed.clear();
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const timeout = setTimeout(finish, LEAVE_GUARD_TIMEOUT_MS);
|
|
98
|
+
try {
|
|
99
|
+
let failed = false;
|
|
100
|
+
const saves = [];
|
|
101
|
+
for (const [, { onLeave }] of current) try {
|
|
102
|
+
const save = onLeave(request);
|
|
103
|
+
if (save) saves.push(save);
|
|
104
|
+
} catch {
|
|
105
|
+
failed = true;
|
|
106
|
+
}
|
|
107
|
+
if (saves.length > 0) {
|
|
108
|
+
const results = await Promise.allSettled(saves);
|
|
109
|
+
failed ||= results.some(({ status }) => status === "rejected");
|
|
110
|
+
}
|
|
111
|
+
if (failed || finished) return;
|
|
112
|
+
if (request.requestId !== void 0) {
|
|
113
|
+
const result = await confirm(request.requestId);
|
|
114
|
+
if (result.ok || result.error.code !== "UNSUPPORTED" || finished) return;
|
|
115
|
+
}
|
|
116
|
+
for (const [id, guard] of current) if (guards.get(id) === guard) clear(id);
|
|
117
|
+
} finally {
|
|
118
|
+
finish();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
setSdk(sdk) {
|
|
123
|
+
connectedSdk = sdk;
|
|
124
|
+
if (slots || sdk?.chrome.confirmLeave === void 0) return;
|
|
125
|
+
slots = true;
|
|
126
|
+
for (const [id, message] of aggregate) write(id, message);
|
|
127
|
+
if (aggregateMessage !== null) write(aggregateId, null);
|
|
128
|
+
aggregate.clear();
|
|
129
|
+
},
|
|
130
|
+
register(id, message, onLeave) {
|
|
131
|
+
guards.set(id, { onLeave });
|
|
132
|
+
removed.delete(id);
|
|
133
|
+
unsubscribe ??= chrome.on("leaveRequested", (request) => void leave(request));
|
|
134
|
+
set(id, message);
|
|
135
|
+
return () => {
|
|
136
|
+
guards.delete(id);
|
|
137
|
+
if (requests > 0) removed.add(id);
|
|
138
|
+
else clear(id);
|
|
139
|
+
if (guards.size === 0) {
|
|
140
|
+
unsubscribe?.();
|
|
141
|
+
unsubscribe = void 0;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
},
|
|
145
|
+
confirm
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// src/react/shell-provider.ts
|
|
149
|
+
function ShellProvider(props) {
|
|
150
|
+
const { context, sdk, children } = props;
|
|
151
|
+
const { bridge } = context;
|
|
152
|
+
if (sdk !== void 0 && sdk.bridge !== bridge) throw new Error("ShellProvider: `sdk` is connected to another bridge than `context.bridge`; pass the SDK that connectShell(ctx.bridge) returned for this mount");
|
|
153
|
+
const [connected, setConnected] = useState(null);
|
|
154
|
+
useEffect(() => {
|
|
155
|
+
if (sdk !== void 0) return void 0;
|
|
156
|
+
let live = true;
|
|
157
|
+
connectShell(bridge).then((next) => {
|
|
158
|
+
if (live) setConnected(next);
|
|
159
|
+
});
|
|
160
|
+
return () => {
|
|
161
|
+
live = false;
|
|
162
|
+
};
|
|
163
|
+
}, [bridge, sdk]);
|
|
164
|
+
const current = sdk ?? (connected?.bridge === bridge ? connected : null);
|
|
165
|
+
const core = useMemo(() => sdk ?? coreClients(bridge), [sdk, bridge]);
|
|
166
|
+
const titles = useMemo(() => titleStack(core.chrome), [core]);
|
|
167
|
+
const aggregateId = useId();
|
|
168
|
+
const guards = useMemo(() => createLeaveGuards(core.chrome, bridge, aggregateId), [
|
|
169
|
+
core,
|
|
170
|
+
bridge,
|
|
171
|
+
aggregateId
|
|
172
|
+
]);
|
|
173
|
+
useEffect(() => {
|
|
174
|
+
guards.setSdk(current);
|
|
175
|
+
}, [current, guards]);
|
|
176
|
+
const binding = useMemo(() => ({
|
|
177
|
+
context,
|
|
178
|
+
sdk: current,
|
|
179
|
+
core,
|
|
180
|
+
titles,
|
|
181
|
+
guards
|
|
182
|
+
}), [
|
|
183
|
+
context,
|
|
184
|
+
current,
|
|
185
|
+
core,
|
|
186
|
+
titles,
|
|
187
|
+
guards
|
|
188
|
+
]);
|
|
189
|
+
return createElement(ShellContext, { value: binding }, children);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* The mount's SDK, with the shell's capability list: `available()` and `models` say what the
|
|
193
|
+
* shell offers. It is the `sdk` given to the nearest `ShellProvider`, or the SDK the provider
|
|
194
|
+
* connected itself. Null outside a `ShellProvider` and, when the provider got no `sdk`, until
|
|
195
|
+
* the shell has answered `capabilities()`; the component renders again when it has. If the
|
|
196
|
+
* shell cannot list its capabilities, the SDK offers none (as from `connectShell`).
|
|
197
|
+
*/
|
|
198
|
+
function useShellSdk() {
|
|
199
|
+
return useShellBinding()?.sdk ?? null;
|
|
200
|
+
}
|
|
201
|
+
// src/react/i18n.ts
|
|
202
|
+
/**
|
|
203
|
+
* React i18n adapters with the signatures products used with the shell's i18n module:
|
|
204
|
+
* `I18nProvider`, `useI18n`, `languages` and `sourceMessage`.
|
|
205
|
+
*
|
|
206
|
+
* The shell owns the language: the locale comes from `ctx.locale` and `i18n@1`
|
|
207
|
+
* `localeChanged`, and `setLocale` asks the shell through `i18n@1` `setLocale`. The product
|
|
208
|
+
* owns its messages: it passes its catalog (its locales and its `translate`) to `createI18n`
|
|
209
|
+
* once, and the adapters translate with it. Nothing here writes `<html lang>`, the title,
|
|
210
|
+
* `<meta>` tags or storage (docs/contract.md §4).
|
|
211
|
+
*/
|
|
212
|
+
/**
|
|
213
|
+
* Binds the i18n adapters to the product's message catalog. Call it once per product and export
|
|
214
|
+
* the results under the names the product's code imports:
|
|
215
|
+
*
|
|
216
|
+
* ```ts
|
|
217
|
+
* export const { I18nProvider, useI18n, languages, sourceMessage } = createI18n(messages);
|
|
218
|
+
* ```
|
|
219
|
+
*
|
|
220
|
+
* `I18nProvider` follows the shell's locale when it is inside a `ShellProvider`. A component
|
|
221
|
+
* outside any `I18nProvider` gets the fallback locale and a `setLocale` that does nothing.
|
|
222
|
+
*/
|
|
223
|
+
function createI18n(catalog) {
|
|
224
|
+
const locales = catalog.languages.map((language) => language.locale);
|
|
225
|
+
const first = catalog.fallbackLocale ?? locales[0];
|
|
226
|
+
if (first === void 0) throw new Error("createI18n: the catalog lists no languages");
|
|
227
|
+
const fallback = first;
|
|
228
|
+
const resolve = (tag) => negotiateLocale(tag, locales);
|
|
229
|
+
const loads = /* @__PURE__ */ new Map();
|
|
230
|
+
const load = (locale) => {
|
|
231
|
+
if (!catalog.ensureLocaleLoaded || catalog.isLocaleLoaded?.(locale)) return void 0;
|
|
232
|
+
const pending = loads.get(locale);
|
|
233
|
+
if (pending) return pending;
|
|
234
|
+
const next = Promise.resolve().then(() => catalog.ensureLocaleLoaded?.(locale));
|
|
235
|
+
loads.set(locale, next);
|
|
236
|
+
next.then(() => {
|
|
237
|
+
if (catalog.isLocaleLoaded) loads.delete(locale);
|
|
238
|
+
}, () => loads.delete(locale));
|
|
239
|
+
return next;
|
|
240
|
+
};
|
|
241
|
+
const tools = (locale, setLocale) => ({
|
|
242
|
+
locale,
|
|
243
|
+
t: (message, values, context) => catalog.translate(locale, message, values, context),
|
|
244
|
+
formatDate: (date, options) => new Intl.DateTimeFormat(locale, options).format(date),
|
|
245
|
+
formatNumber: (number, options) => new Intl.NumberFormat(locale, options).format(number),
|
|
246
|
+
setLocale
|
|
247
|
+
});
|
|
248
|
+
const I18nContext = createContext(tools(fallback, () => {}));
|
|
249
|
+
function I18nProvider({ children, initialLocale }) {
|
|
250
|
+
const shell = useShellBinding();
|
|
251
|
+
const i18n = shell?.core.i18n;
|
|
252
|
+
const initial = shell ? resolve(shell.context.locale) ?? fallback : initialLocale ?? fallback;
|
|
253
|
+
const [shown, setShown] = useState(() => ({
|
|
254
|
+
locale: initial,
|
|
255
|
+
loaded: 0
|
|
256
|
+
}));
|
|
257
|
+
const revision = useRef({
|
|
258
|
+
locale: 0,
|
|
259
|
+
event: 0,
|
|
260
|
+
command: 0
|
|
261
|
+
});
|
|
262
|
+
const apply = useCallback((next) => {
|
|
263
|
+
const sequence = ++revision.current.locale;
|
|
264
|
+
const pending = load(next);
|
|
265
|
+
if (!pending) {
|
|
266
|
+
setShown((current) => current.locale === next ? current : {
|
|
267
|
+
...current,
|
|
268
|
+
locale: next
|
|
269
|
+
});
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
pending.then(() => {
|
|
273
|
+
if (revision.current.locale === sequence) setShown((current) => ({
|
|
274
|
+
locale: next,
|
|
275
|
+
loaded: current.loaded + 1
|
|
276
|
+
}));
|
|
277
|
+
}, () => {});
|
|
278
|
+
}, []);
|
|
279
|
+
const applyInitial = useEffectEvent(() => apply(initial));
|
|
280
|
+
const onLocaleChanged = useEffectEvent(({ locale }) => {
|
|
281
|
+
revision.current.event += 1;
|
|
282
|
+
apply(resolve(locale) ?? fallback);
|
|
283
|
+
});
|
|
284
|
+
useEffect(() => {
|
|
285
|
+
applyInitial();
|
|
286
|
+
const current = revision.current;
|
|
287
|
+
const sequence = current.locale;
|
|
288
|
+
const unsubscribe = i18n?.on("localeChanged", (payload) => onLocaleChanged(payload));
|
|
289
|
+
i18n?.getLocale().then((result) => {
|
|
290
|
+
if (current.locale === sequence && result.ok) apply(resolve(result.data.locale) ?? fallback);
|
|
291
|
+
});
|
|
292
|
+
return () => {
|
|
293
|
+
current.locale += 1;
|
|
294
|
+
current.command += 1;
|
|
295
|
+
unsubscribe?.();
|
|
296
|
+
};
|
|
297
|
+
}, [i18n, apply]);
|
|
298
|
+
const setLocale = useCallback((next) => {
|
|
299
|
+
if (!locales.includes(next)) return;
|
|
300
|
+
if (!i18n) {
|
|
301
|
+
apply(next);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const command = ++revision.current.command;
|
|
305
|
+
const event = revision.current.event;
|
|
306
|
+
i18n.setLocale({ locale: next }).then((result) => {
|
|
307
|
+
if (revision.current.command === command && revision.current.event === event && result.ok) apply(resolve(result.data.locale) ?? next);
|
|
308
|
+
});
|
|
309
|
+
}, [i18n, apply]);
|
|
310
|
+
const value = useMemo(() => tools(shown.locale, setLocale), [shown, setLocale]);
|
|
311
|
+
return createElement(I18nContext, { value }, children);
|
|
312
|
+
}
|
|
313
|
+
function useI18n() {
|
|
314
|
+
return useContext(I18nContext);
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
I18nProvider,
|
|
318
|
+
useI18n,
|
|
319
|
+
languages: catalog.languages,
|
|
320
|
+
sourceMessage: (message, locale) => catalog.sourceMessage === void 0 ? message : catalog.sourceMessage(message, locale)
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
// src/react/document-title.ts
|
|
324
|
+
/**
|
|
325
|
+
* Shows `title` as the page title while the calling component is mounted, through `chrome@1`
|
|
326
|
+
* `setTitle`. Titles stack: the most recently set one shows, and when its component unmounts
|
|
327
|
+
* the one below it shows again; with none left the shell's default title returns
|
|
328
|
+
* (`setTitle({ title: null })`). An empty, null or undefined title sets nothing.
|
|
329
|
+
*
|
|
330
|
+
* Never writes `document.title` itself; outside a `ShellProvider` it does nothing.
|
|
331
|
+
*/
|
|
332
|
+
function useRouteDocumentTitle(title) {
|
|
333
|
+
const titles = useShellBinding()?.titles;
|
|
334
|
+
useEffect(() => {
|
|
335
|
+
if (!title || !titles) return void 0;
|
|
336
|
+
return titles.push(title);
|
|
337
|
+
}, [title, titles]);
|
|
338
|
+
}
|
|
339
|
+
// src/react/leave-guard.ts
|
|
340
|
+
const noShell = async () => hostErr("UNSUPPORTED", "useLeaveGuard requires a ShellProvider to confirm a leave request");
|
|
341
|
+
function useLeaveGuard(message, options) {
|
|
342
|
+
const guards = useShellBinding()?.guards;
|
|
343
|
+
const id = useId();
|
|
344
|
+
const onLeave = useEffectEvent(options.onLeave);
|
|
345
|
+
useEffect(() => {
|
|
346
|
+
if (!guards || !message) return void 0;
|
|
347
|
+
return guards.register(id, message, (request) => onLeave(request));
|
|
348
|
+
}, [
|
|
349
|
+
guards,
|
|
350
|
+
id,
|
|
351
|
+
message
|
|
352
|
+
]);
|
|
353
|
+
return guards?.confirm ?? noShell;
|
|
354
|
+
}
|
|
355
|
+
// src/react/tracker.ts
|
|
356
|
+
/**
|
|
357
|
+
* Creates the product's tracker. Create it once, connect it in `mount()`, and export its
|
|
358
|
+
* methods under the names the product's code imports:
|
|
359
|
+
*
|
|
360
|
+
* ```ts
|
|
361
|
+
* export const tracker = createTracker<ProductEvents>();
|
|
362
|
+
* export const { track, send, flush } = tracker;
|
|
363
|
+
* ```
|
|
364
|
+
*
|
|
365
|
+
* The exported functions know no mount: they serve whichever mounts are connected, as long as
|
|
366
|
+
* those share one bridge (see `connect`).
|
|
367
|
+
*/
|
|
368
|
+
function createTracker() {
|
|
369
|
+
/** The connected mounts, oldest first. */
|
|
370
|
+
const connections = [];
|
|
371
|
+
/** Whether the current conflict between bridges has been reported. */
|
|
372
|
+
let reported = false;
|
|
373
|
+
const bridges = () => new Set(connections.map((connection) => connection.bridge)).size;
|
|
374
|
+
/**
|
|
375
|
+
* The client a call goes through: the one bridge every connected mount shares. Null when no
|
|
376
|
+
* mount is connected, or when mounts with different bridges are, which is reported once.
|
|
377
|
+
*/
|
|
378
|
+
const target = (call) => {
|
|
379
|
+
const count = bridges();
|
|
380
|
+
if (count <= 1) return connections.at(-1)?.tracking ?? null;
|
|
381
|
+
if (!reported) {
|
|
382
|
+
reported = true;
|
|
383
|
+
console.error(`createTracker: ${call} was not sent: ${count} mounts with different bridges are connected to one tracker, and a call cannot say which mount it comes from. Nothing is sent until one bridge is left; a product that runs several mounts at once creates one tracker per mount.`);
|
|
384
|
+
}
|
|
385
|
+
return null;
|
|
386
|
+
};
|
|
387
|
+
const track = async (event, properties) => {
|
|
388
|
+
const tracking = target(`track("${String(event)}")`);
|
|
389
|
+
if (!tracking) return "config_unavailable";
|
|
390
|
+
const result = await tracking.track({
|
|
391
|
+
event: String(event),
|
|
392
|
+
properties
|
|
393
|
+
});
|
|
394
|
+
if (result.ok) return result.data.accepted ? "queued" : "disabled";
|
|
395
|
+
switch (result.error.code) {
|
|
396
|
+
case "INVALID_PARAMS": return "invalid";
|
|
397
|
+
case "CONFLICT": return "duplicate";
|
|
398
|
+
case "BUSY":
|
|
399
|
+
case "QUOTA_EXCEEDED": return "full";
|
|
400
|
+
default: return "config_unavailable";
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
return Object.freeze({
|
|
404
|
+
connect: ({ bridge }) => {
|
|
405
|
+
const connection = {
|
|
406
|
+
bridge,
|
|
407
|
+
tracking: coreClients(bridge).tracking
|
|
408
|
+
};
|
|
409
|
+
connections.push(connection);
|
|
410
|
+
return () => {
|
|
411
|
+
const index = connections.indexOf(connection);
|
|
412
|
+
if (index === -1) return;
|
|
413
|
+
connections.splice(index, 1);
|
|
414
|
+
if (bridges() <= 1) reported = false;
|
|
415
|
+
};
|
|
416
|
+
},
|
|
417
|
+
track,
|
|
418
|
+
send: (event, properties) => {
|
|
419
|
+
track(event, properties);
|
|
420
|
+
},
|
|
421
|
+
flush: async () => {
|
|
422
|
+
const tracking = target("flush()");
|
|
423
|
+
if (!tracking) return "disabled";
|
|
424
|
+
const result = await tracking.flush();
|
|
425
|
+
if (result.ok) return "accepted";
|
|
426
|
+
switch (result.error.code) {
|
|
427
|
+
case "UNSUPPORTED": return "disabled";
|
|
428
|
+
case "BUSY":
|
|
429
|
+
case "TIMEOUT": return "retry";
|
|
430
|
+
default: return "drop";
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
export { ShellProvider, createI18n, createTracker, useLeaveGuard, useRouteDocumentTitle, useShellSdk };
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opendesignai/shell-sdk",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Typed SDK product apps use to call OpenDesign shell capabilities over the host bridge.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/nexu-io/od-platform.git",
|
|
9
|
+
"directory": "packages/shell-sdk"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./react": {
|
|
22
|
+
"types": "./dist/react.d.ts",
|
|
23
|
+
"default": "./dist/react.js"
|
|
24
|
+
},
|
|
25
|
+
"./package.json": "./package.json"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public",
|
|
29
|
+
"provenance": true,
|
|
30
|
+
"tag": "alpha"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@opendesignai/contracts": "0.1.0-alpha.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@arethetypeswrong/core": "0.18.5",
|
|
37
|
+
"@types/react": "19.2.7",
|
|
38
|
+
"@types/react-dom": "19.2.3",
|
|
39
|
+
"happy-dom": "21.0.4",
|
|
40
|
+
"publint": "0.3.25",
|
|
41
|
+
"react": "19.2.9",
|
|
42
|
+
"react-dom": "19.2.9",
|
|
43
|
+
"tsdown": "0.23.8",
|
|
44
|
+
"typescript": "7.0.2"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@types/react": "^19.2.0",
|
|
48
|
+
"react": "^19.2.0",
|
|
49
|
+
"react-dom": "^19.2.0"
|
|
50
|
+
},
|
|
51
|
+
"peerDependenciesMeta": {
|
|
52
|
+
"@types/react": {
|
|
53
|
+
"optional": true
|
|
54
|
+
},
|
|
55
|
+
"react": {
|
|
56
|
+
"optional": true
|
|
57
|
+
},
|
|
58
|
+
"react-dom": {
|
|
59
|
+
"optional": true
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsdown",
|
|
64
|
+
"typecheck": "tsc -p ."
|
|
65
|
+
}
|
|
6
66
|
}
|
package/README.md
DELETED