@frontera-sdk/core 0.1.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 +202 -0
- package/README.md +42 -0
- package/package.json +91 -0
- package/src/app-state.ts +109 -0
- package/src/bridge-client.ts +152 -0
- package/src/bridge-protocol.ts +95 -0
- package/src/client.ts +29 -0
- package/src/config.ts +86 -0
- package/src/create-frontera-app.tsx +220 -0
- package/src/errors.ts +52 -0
- package/src/theme.ts +69 -0
- package/src/transport.ts +96 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Sebati
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# @frontera-sdk/core
|
|
2
|
+
|
|
3
|
+
The runtime a Frontera app mounts on: the postMessage bridge to the platform
|
|
4
|
+
host, the app bootstrap, and a typed platform client.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
bun add @frontera-sdk/core react react-dom @tanstack/react-query
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```tsx
|
|
11
|
+
import { createFronteraApp } from '@frontera-sdk/core/create-frontera-app'
|
|
12
|
+
|
|
13
|
+
import App from './App'
|
|
14
|
+
|
|
15
|
+
createFronteraApp(<App />)
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`createFronteraApp` completes the handshake, adopts the host's palette,
|
|
19
|
+
installs the error boundary that reports crashes back to the platform, and only
|
|
20
|
+
then mounts. An app has no data scope until the host says who it is — which is
|
|
21
|
+
why opening the app's own origin directly renders a refusal panel rather than
|
|
22
|
+
the app.
|
|
23
|
+
|
|
24
|
+
## Entry points
|
|
25
|
+
|
|
26
|
+
| Import | What it is |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `@frontera-sdk/core/create-frontera-app` | app bootstrap and `useFronteraApp` |
|
|
29
|
+
| `@frontera-sdk/core/client` | the typed platform client |
|
|
30
|
+
| `@frontera-sdk/core/config` | credential and origin resolution |
|
|
31
|
+
| `@frontera-sdk/core/bridge-client` | the host handshake, if you need it directly |
|
|
32
|
+
| `@frontera-sdk/core/bridge-protocol` | the message types both sides speak |
|
|
33
|
+
| `@frontera-sdk/core/app-state` | shared, validated app state |
|
|
34
|
+
| `@frontera-sdk/core/theme` | applying the host's design tokens |
|
|
35
|
+
| `@frontera-sdk/core/errors` | the error taxonomy, `code` mirroring the service |
|
|
36
|
+
|
|
37
|
+
Published as TypeScript source. Every consumer is a bundler or `tsc`, so a
|
|
38
|
+
build step would emit output the consumer immediately re-transpiles.
|
|
39
|
+
|
|
40
|
+
## License
|
|
41
|
+
|
|
42
|
+
Apache-2.0. See [LICENSE](./LICENSE).
|
package/package.json
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@frontera-sdk/core",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Frontera app runtime: the platform bridge client, app bootstrap and typed platform client.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"frontera",
|
|
7
|
+
"sdk",
|
|
8
|
+
"iframe",
|
|
9
|
+
"bridge"
|
|
10
|
+
],
|
|
11
|
+
"license": "Apache-2.0",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"!src/__tests__",
|
|
16
|
+
"!src/**/*.test.ts",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
"./errors": {
|
|
25
|
+
"types": "./src/errors.ts",
|
|
26
|
+
"import": "./src/errors.ts"
|
|
27
|
+
},
|
|
28
|
+
"./config": {
|
|
29
|
+
"types": "./src/config.ts",
|
|
30
|
+
"import": "./src/config.ts"
|
|
31
|
+
},
|
|
32
|
+
"./transport": {
|
|
33
|
+
"types": "./src/transport.ts",
|
|
34
|
+
"import": "./src/transport.ts"
|
|
35
|
+
},
|
|
36
|
+
"./client": {
|
|
37
|
+
"types": "./src/client.ts",
|
|
38
|
+
"import": "./src/client.ts"
|
|
39
|
+
},
|
|
40
|
+
"./theme": {
|
|
41
|
+
"types": "./src/theme.ts",
|
|
42
|
+
"import": "./src/theme.ts"
|
|
43
|
+
},
|
|
44
|
+
"./bridge-client": {
|
|
45
|
+
"types": "./src/bridge-client.ts",
|
|
46
|
+
"import": "./src/bridge-client.ts"
|
|
47
|
+
},
|
|
48
|
+
"./bridge-protocol": {
|
|
49
|
+
"types": "./src/bridge-protocol.ts",
|
|
50
|
+
"import": "./src/bridge-protocol.ts"
|
|
51
|
+
},
|
|
52
|
+
"./app-state": {
|
|
53
|
+
"types": "./src/app-state.ts",
|
|
54
|
+
"import": "./src/app-state.ts"
|
|
55
|
+
},
|
|
56
|
+
"./create-frontera-app": {
|
|
57
|
+
"types": "./src/create-frontera-app.tsx",
|
|
58
|
+
"import": "./src/create-frontera-app.tsx"
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"test": "bun test",
|
|
63
|
+
"typecheck": "bunx tsc --noEmit"
|
|
64
|
+
},
|
|
65
|
+
"peerDependencies": {
|
|
66
|
+
"@tanstack/react-query": "^5.90.21",
|
|
67
|
+
"react": "^19.0.0",
|
|
68
|
+
"react-dom": "^19.0.0"
|
|
69
|
+
},
|
|
70
|
+
"peerDependenciesMeta": {
|
|
71
|
+
"@tanstack/react-query": {
|
|
72
|
+
"optional": true
|
|
73
|
+
},
|
|
74
|
+
"react": {
|
|
75
|
+
"optional": true
|
|
76
|
+
},
|
|
77
|
+
"react-dom": {
|
|
78
|
+
"optional": true
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
"devDependencies": {
|
|
82
|
+
"@happy-dom/global-registrator": "^20.11.1",
|
|
83
|
+
"@tanstack/react-query": "^5.90.21",
|
|
84
|
+
"@types/bun": "latest",
|
|
85
|
+
"@types/react": "^19",
|
|
86
|
+
"@types/react-dom": "^19",
|
|
87
|
+
"react": "19.2.5",
|
|
88
|
+
"react-dom": "19.2.5",
|
|
89
|
+
"typescript": "^5.9.3"
|
|
90
|
+
}
|
|
91
|
+
}
|
package/src/app-state.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared app state: typed, validated, and legible to a mounted agent.
|
|
3
|
+
*
|
|
4
|
+
* Free-form JSON was explicitly rejected. It types as `any`, so a typo compiles,
|
|
5
|
+
* and a write from a stale app version or a guessing agent can put a string
|
|
6
|
+
* where the app expects an object and take the render down — worse than V1,
|
|
7
|
+
* where a schema made invalid state unrepresentable.
|
|
8
|
+
*
|
|
9
|
+
* One declaration does three jobs: it types `useAppState` via inference, it
|
|
10
|
+
* validates every read and write at runtime, and the build emits it as JSON
|
|
11
|
+
* Schema so the agent receives a typed tool rather than a free-form object.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Minimal structural type for a Zod-like schema, so this file has no Zod dependency. */
|
|
15
|
+
export interface StandardSchema<T> {
|
|
16
|
+
safeParse(value: unknown): { success: true; data: T } | { success: false; error: unknown }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface AppStateDefinition<T extends Record<string, unknown>> {
|
|
20
|
+
schema: StandardSchema<T>
|
|
21
|
+
defaults: T
|
|
22
|
+
/** Per-key schemas, when available, enable per-key recovery. */
|
|
23
|
+
shape?: Record<string, StandardSchema<unknown>>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface DefineAppStateInput<T extends Record<string, unknown>> {
|
|
27
|
+
schema: StandardSchema<T> & { shape?: Record<string, StandardSchema<unknown>> }
|
|
28
|
+
defaults: T
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function defineAppState<T extends Record<string, unknown>>(
|
|
32
|
+
input: DefineAppStateInput<T>,
|
|
33
|
+
): AppStateDefinition<T> {
|
|
34
|
+
return {
|
|
35
|
+
schema: input.schema,
|
|
36
|
+
defaults: input.defaults,
|
|
37
|
+
shape: (input.schema as { shape?: Record<string, StandardSchema<unknown>> }).shape,
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface RecoveryResult<T> {
|
|
42
|
+
state: T
|
|
43
|
+
/** Keys that failed validation and were reset to their default. */
|
|
44
|
+
repaired: string[]
|
|
45
|
+
/** Keys present in storage but absent from the schema — hidden, not dropped. */
|
|
46
|
+
unknown: string[]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Parse a stored state document into something the app can render.
|
|
51
|
+
*
|
|
52
|
+
* **Invariant: this never throws.** Recovery is per key — a malformed or
|
|
53
|
+
* missing key resets to its default while valid keys survive — so the app
|
|
54
|
+
* always receives a well-formed, correctly-typed object. Unknown keys (written
|
|
55
|
+
* by a newer version, or invented by an agent) are hidden from the app but
|
|
56
|
+
* PRESERVED by the caller in storage, so a rollback does not lose them.
|
|
57
|
+
*
|
|
58
|
+
* Whole-document validation is tried first because it is the common path and
|
|
59
|
+
* cheap; per-key recovery is the fallback that keeps a single bad field from
|
|
60
|
+
* blanking everything else.
|
|
61
|
+
*/
|
|
62
|
+
export function parseAppState<T extends Record<string, unknown>>(
|
|
63
|
+
definition: AppStateDefinition<T>,
|
|
64
|
+
stored: unknown,
|
|
65
|
+
): RecoveryResult<T> {
|
|
66
|
+
const document = (typeof stored === 'object' && stored !== null ? stored : {}) as Record<string, unknown>
|
|
67
|
+
|
|
68
|
+
const whole = definition.schema.safeParse(document)
|
|
69
|
+
if (whole.success) {
|
|
70
|
+
// Project onto known keys explicitly rather than trusting the schema to
|
|
71
|
+
// strip: a `.passthrough()` (or any hand-rolled) schema would otherwise
|
|
72
|
+
// hand the app a key it has no type for.
|
|
73
|
+
const projected = {} as Record<string, unknown>
|
|
74
|
+
for (const key of Object.keys(definition.defaults)) {
|
|
75
|
+
projected[key] = (whole.data as Record<string, unknown>)[key] ?? definition.defaults[key]
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
state: projected as T,
|
|
79
|
+
repaired: [],
|
|
80
|
+
unknown: Object.keys(document).filter((k) => !(k in definition.defaults)),
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const state = { ...definition.defaults } as Record<string, unknown>
|
|
85
|
+
const repaired: string[] = []
|
|
86
|
+
const unknownKeys: string[] = []
|
|
87
|
+
|
|
88
|
+
for (const key of Object.keys(document)) {
|
|
89
|
+
if (!(key in definition.defaults)) {
|
|
90
|
+
unknownKeys.push(key)
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
const keySchema = definition.shape?.[key]
|
|
94
|
+
if (!keySchema) {
|
|
95
|
+
// No per-key schema available: accept only if it matches the default's
|
|
96
|
+
// primitive shape, otherwise fall back. Cheap, and better than trusting it.
|
|
97
|
+
const sameShape = typeof document[key] === typeof definition.defaults[key]
|
|
98
|
+
if (sameShape) state[key] = document[key]
|
|
99
|
+
else repaired.push(key)
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
const parsed = keySchema.safeParse(document[key])
|
|
103
|
+
if (parsed.success) state[key] = parsed.data
|
|
104
|
+
else repaired.push(key)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Keys the document omitted entirely already hold their default.
|
|
108
|
+
return { state: state as T, repaired, unknown: unknownKeys }
|
|
109
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { isHostMessage, type BridgeInit, type AppMessage } from './bridge-protocol'
|
|
2
|
+
import { readRuntimeGlobal } from './config'
|
|
3
|
+
import type { HostTheme } from './theme'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* App side of the bridge.
|
|
7
|
+
*
|
|
8
|
+
* The app announces itself with `frontera:ready` and waits for `frontera:init`,
|
|
9
|
+
* which carries the API credential. It does NOT read the credential from its
|
|
10
|
+
* own URL — the only thing there is the narrow asset token, and treating that
|
|
11
|
+
* as a data credential would turn a loggable URL into data access.
|
|
12
|
+
*
|
|
13
|
+
* `event.origin` is checked against the parent's origin on every message.
|
|
14
|
+
*/
|
|
15
|
+
export interface BridgeSession {
|
|
16
|
+
init: BridgeInit
|
|
17
|
+
/** Send a message to the host. */
|
|
18
|
+
send(message: AppMessage): void
|
|
19
|
+
/** Subscribe to shared-state updates pushed by the host. */
|
|
20
|
+
onState(handler: (state: Record<string, unknown>) => void): () => void
|
|
21
|
+
/** Subscribe to credential refreshes. */
|
|
22
|
+
onToken(handler: (token: string) => void): () => void
|
|
23
|
+
/** Subscribe to host palette / colour-scheme changes. */
|
|
24
|
+
onTheme(handler: (theme: HostTheme) => void): () => void
|
|
25
|
+
dispose(): void
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ConnectOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Origin of the embedding platform. Defaults to the injected runtime config,
|
|
31
|
+
* then `document.referrer`.
|
|
32
|
+
*/
|
|
33
|
+
parentOrigin?: string
|
|
34
|
+
timeoutMs?: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Who is framing us.
|
|
39
|
+
*
|
|
40
|
+
* The injected runtime config comes FIRST and `document.referrer` is only a
|
|
41
|
+
* fallback, which is the opposite of the original order and the reason the
|
|
42
|
+
* handshake could not complete in production: app responses are served with
|
|
43
|
+
* `referrer-policy: no-referrer`, so the referrer is empty exactly where it
|
|
44
|
+
* mattered. `platformOrigin` exists in the injected config for this purpose.
|
|
45
|
+
*/
|
|
46
|
+
function resolveParentOrigin(explicit?: string): string | null {
|
|
47
|
+
if (explicit) return explicit
|
|
48
|
+
const injected = readRuntimeGlobal().platformOrigin
|
|
49
|
+
if (injected) return injected
|
|
50
|
+
if (typeof document === 'undefined') return null
|
|
51
|
+
try {
|
|
52
|
+
return document.referrer ? new URL(document.referrer).origin : null
|
|
53
|
+
} catch {
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Complete the handshake.
|
|
60
|
+
*
|
|
61
|
+
* Rejects rather than hanging if the host never answers: a frame that waits
|
|
62
|
+
* forever looks identical to a slow network, and an author debugging a broken
|
|
63
|
+
* mount deserves a real error.
|
|
64
|
+
*/
|
|
65
|
+
export function connectToHost(options: ConnectOptions = {}): Promise<BridgeSession> {
|
|
66
|
+
const parentOrigin = resolveParentOrigin(options.parentOrigin)
|
|
67
|
+
const timeoutMs = options.timeoutMs ?? 10_000
|
|
68
|
+
|
|
69
|
+
if (typeof window === 'undefined' || window.parent === window) {
|
|
70
|
+
return Promise.reject(
|
|
71
|
+
new Error('Not running inside a Frontera host frame — connectToHost() needs a parent window.'),
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
if (!parentOrigin) {
|
|
75
|
+
return Promise.reject(
|
|
76
|
+
new Error('Could not determine the host origin; pass parentOrigin explicitly.'),
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const stateHandlers = new Set<(s: Record<string, unknown>) => void>()
|
|
81
|
+
const tokenHandlers = new Set<(t: string) => void>()
|
|
82
|
+
const themeHandlers = new Set<(t: HostTheme) => void>()
|
|
83
|
+
|
|
84
|
+
return new Promise<BridgeSession>((resolve, reject) => {
|
|
85
|
+
let settled = false
|
|
86
|
+
|
|
87
|
+
const send = (message: AppMessage) => window.parent.postMessage(message, parentOrigin)
|
|
88
|
+
|
|
89
|
+
const onMessage = (event: MessageEvent) => {
|
|
90
|
+
if (event.origin !== parentOrigin) return
|
|
91
|
+
if (!isHostMessage(event.data)) return
|
|
92
|
+
const message = event.data
|
|
93
|
+
|
|
94
|
+
switch (message.type) {
|
|
95
|
+
case 'frontera:init':
|
|
96
|
+
if (settled) return
|
|
97
|
+
settled = true
|
|
98
|
+
clearTimeout(timer)
|
|
99
|
+
resolve({
|
|
100
|
+
init: message,
|
|
101
|
+
send,
|
|
102
|
+
onState(handler) {
|
|
103
|
+
stateHandlers.add(handler)
|
|
104
|
+
return () => stateHandlers.delete(handler)
|
|
105
|
+
},
|
|
106
|
+
onToken(handler) {
|
|
107
|
+
tokenHandlers.add(handler)
|
|
108
|
+
return () => tokenHandlers.delete(handler)
|
|
109
|
+
},
|
|
110
|
+
onTheme(handler) {
|
|
111
|
+
themeHandlers.add(handler)
|
|
112
|
+
return () => themeHandlers.delete(handler)
|
|
113
|
+
},
|
|
114
|
+
dispose() {
|
|
115
|
+
window.removeEventListener('message', onMessage)
|
|
116
|
+
stateHandlers.clear()
|
|
117
|
+
tokenHandlers.clear()
|
|
118
|
+
themeHandlers.clear()
|
|
119
|
+
},
|
|
120
|
+
})
|
|
121
|
+
break
|
|
122
|
+
case 'frontera:state':
|
|
123
|
+
for (const handler of stateHandlers) handler(message.state)
|
|
124
|
+
break
|
|
125
|
+
case 'frontera:token':
|
|
126
|
+
for (const handler of tokenHandlers) handler(message.token)
|
|
127
|
+
break
|
|
128
|
+
// The host pushes this on every platform theme change — a system
|
|
129
|
+
// dark-mode switch, a surface that forces its own scheme. Without a
|
|
130
|
+
// handler the message was received and dropped, so an app followed the
|
|
131
|
+
// palette it was mounted with and then never again.
|
|
132
|
+
case 'frontera:theme':
|
|
133
|
+
for (const handler of themeHandlers) {
|
|
134
|
+
handler({ tokens: message.tokens, colorScheme: message.colorScheme })
|
|
135
|
+
}
|
|
136
|
+
break
|
|
137
|
+
default:
|
|
138
|
+
break
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const timer = setTimeout(() => {
|
|
143
|
+
if (settled) return
|
|
144
|
+
settled = true
|
|
145
|
+
window.removeEventListener('message', onMessage)
|
|
146
|
+
reject(new Error(`Frontera host did not respond within ${timeoutMs}ms`))
|
|
147
|
+
}, timeoutMs)
|
|
148
|
+
|
|
149
|
+
window.addEventListener('message', onMessage)
|
|
150
|
+
send({ type: 'frontera:ready' })
|
|
151
|
+
})
|
|
152
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* postMessage protocol between the platform host and an app iframe.
|
|
3
|
+
*
|
|
4
|
+
* The app runs on its own origin (`<appId>.apps.<domain>`), so postMessage is
|
|
5
|
+
* the ONLY channel. Both sides validate `event.origin` on every message: Luigi,
|
|
6
|
+
* a mature framework with this same architecture, carries an open issue for
|
|
7
|
+
* omitting exactly that check, and the consequence is any page being able to
|
|
8
|
+
* drive an embedded app.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface BridgeInit {
|
|
12
|
+
type: 'frontera:init'
|
|
13
|
+
/** Scoped API credential. Arrives here, never in a URL. */
|
|
14
|
+
token: string
|
|
15
|
+
apiBaseUrl: string
|
|
16
|
+
appId: string
|
|
17
|
+
version: string
|
|
18
|
+
orgId: string | null
|
|
19
|
+
workspaceId: string | null
|
|
20
|
+
/**
|
|
21
|
+
* The host's palette and light/dark state.
|
|
22
|
+
*
|
|
23
|
+
* Defaults, not a house style: `applyHostTheme` writes them behind the app's
|
|
24
|
+
* own stylesheets so a customer's brand still wins.
|
|
25
|
+
*/
|
|
26
|
+
theme: { tokens: Record<string, string>; colorScheme?: 'light' | 'dark'; fontCss?: string }
|
|
27
|
+
/** Current shared app state, already validated by the host. */
|
|
28
|
+
state: Record<string, unknown>
|
|
29
|
+
/**
|
|
30
|
+
* Where the app should open, taken from the platform URL.
|
|
31
|
+
*
|
|
32
|
+
* The counterpart to `frontera:navigate`: without it a shared link to
|
|
33
|
+
* `/apps/<slug>/shipments` mounts the app at its home page, and the address
|
|
34
|
+
* bar describes a view the user is not looking at. Absent means the app's
|
|
35
|
+
* own default.
|
|
36
|
+
*/
|
|
37
|
+
path?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type HostMessage =
|
|
41
|
+
| BridgeInit
|
|
42
|
+
| { type: 'frontera:state'; state: Record<string, unknown> }
|
|
43
|
+
| {
|
|
44
|
+
type: 'frontera:theme'
|
|
45
|
+
tokens: Record<string, string>
|
|
46
|
+
colorScheme?: 'light' | 'dark'
|
|
47
|
+
fontCss?: string
|
|
48
|
+
}
|
|
49
|
+
| { type: 'frontera:token'; token: string }
|
|
50
|
+
|
|
51
|
+
export type AppMessage =
|
|
52
|
+
| { type: 'frontera:ready' }
|
|
53
|
+
| { type: 'frontera:navigate'; path: string }
|
|
54
|
+
| { type: 'frontera:resize'; height: number }
|
|
55
|
+
| { type: 'frontera:state-write'; patch: Record<string, unknown> }
|
|
56
|
+
| { type: 'frontera:error'; message: string; stack?: string }
|
|
57
|
+
| { type: 'frontera:state-repair'; keys: string[] }
|
|
58
|
+
|
|
59
|
+
export function isHostMessage(data: unknown): data is HostMessage {
|
|
60
|
+
if (!data || typeof data !== 'object') return false
|
|
61
|
+
const m = data as Record<string, unknown>
|
|
62
|
+
switch (m.type) {
|
|
63
|
+
case 'frontera:init':
|
|
64
|
+
return typeof m.token === 'string' && typeof m.apiBaseUrl === 'string' && typeof m.appId === 'string'
|
|
65
|
+
case 'frontera:state':
|
|
66
|
+
return typeof m.state === 'object' && m.state !== null
|
|
67
|
+
case 'frontera:theme':
|
|
68
|
+
return typeof m.tokens === 'object' && m.tokens !== null
|
|
69
|
+
case 'frontera:token':
|
|
70
|
+
return typeof m.token === 'string'
|
|
71
|
+
default:
|
|
72
|
+
return false
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function isAppMessage(data: unknown): data is AppMessage {
|
|
77
|
+
if (!data || typeof data !== 'object') return false
|
|
78
|
+
const m = data as Record<string, unknown>
|
|
79
|
+
switch (m.type) {
|
|
80
|
+
case 'frontera:ready':
|
|
81
|
+
return true
|
|
82
|
+
case 'frontera:navigate':
|
|
83
|
+
return typeof m.path === 'string'
|
|
84
|
+
case 'frontera:resize':
|
|
85
|
+
return typeof m.height === 'number' && Number.isFinite(m.height)
|
|
86
|
+
case 'frontera:state-write':
|
|
87
|
+
return typeof m.patch === 'object' && m.patch !== null
|
|
88
|
+
case 'frontera:error':
|
|
89
|
+
return typeof m.message === 'string'
|
|
90
|
+
case 'frontera:state-repair':
|
|
91
|
+
return Array.isArray(m.keys)
|
|
92
|
+
default:
|
|
93
|
+
return false
|
|
94
|
+
}
|
|
95
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { resolveConfig, type FronteraConfig, type FronteraCredential } from './config'
|
|
2
|
+
import { httpRequest, type RequestOptions } from './transport'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The transport-level entry point. Domain clients (`@frontera-sdk/blueprint`, and
|
|
6
|
+
* later chat and automation) take one of these rather than reimplementing
|
|
7
|
+
* auth, URL building, or error mapping.
|
|
8
|
+
*
|
|
9
|
+
* `withCredential` exists because a bridge-hosted app receives a refreshed
|
|
10
|
+
* token mid-session: swapping produces a new client rather than mutating one
|
|
11
|
+
* that in-flight requests may still hold.
|
|
12
|
+
*/
|
|
13
|
+
export class FronteraClient {
|
|
14
|
+
readonly config: FronteraConfig
|
|
15
|
+
private readonly fetchImpl: typeof fetch
|
|
16
|
+
|
|
17
|
+
constructor(config: Partial<FronteraConfig>, fetchImpl: typeof fetch = fetch) {
|
|
18
|
+
this.config = resolveConfig(config)
|
|
19
|
+
this.fetchImpl = fetchImpl
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
|
23
|
+
return httpRequest<T>(this.config, path, options, this.fetchImpl)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
withCredential(credential: FronteraCredential): FronteraClient {
|
|
27
|
+
return new FronteraClient({ ...this.config, credential }, this.fetchImpl)
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { FronteraError } from './errors'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* How a caller proves who it is.
|
|
5
|
+
*
|
|
6
|
+
* `apiKey` is a long-lived `sk-ws-` workspace key, used by servers and CLIs.
|
|
7
|
+
* `token` is a short-lived credential minted by the platform and handed to an
|
|
8
|
+
* app at bridge handshake. Both travel as `Authorization: Bearer`; they are
|
|
9
|
+
* distinct variants because refresh behaviour differs and callers branch on it.
|
|
10
|
+
*/
|
|
11
|
+
export type FronteraCredential =
|
|
12
|
+
| { kind: 'apiKey'; key: string }
|
|
13
|
+
| { kind: 'token'; token: string }
|
|
14
|
+
|
|
15
|
+
export interface FronteraConfig {
|
|
16
|
+
/** Origin of the Frontera API, without a trailing slash. */
|
|
17
|
+
apiBaseUrl: string
|
|
18
|
+
orgId?: string
|
|
19
|
+
workspaceId?: string
|
|
20
|
+
credential: FronteraCredential
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Shape the app runtime injects into the page at serve time.
|
|
25
|
+
*
|
|
26
|
+
* This mirrors `RuntimeConfig` on the serving side, in full. It was previously
|
|
27
|
+
* narrowed to the three fields `resolveConfig` reads, which made the other two
|
|
28
|
+
* invisible to every caller — and `platformOrigin` is the one an app cannot do
|
|
29
|
+
* without: responses carry `referrer-policy: no-referrer`, so `document.referrer`
|
|
30
|
+
* is empty and this is the ONLY way to learn who is framing you.
|
|
31
|
+
*/
|
|
32
|
+
export interface FronteraRuntimeGlobal {
|
|
33
|
+
apiBaseUrl?: string
|
|
34
|
+
orgId?: string
|
|
35
|
+
workspaceId?: string
|
|
36
|
+
appId?: string
|
|
37
|
+
version?: string
|
|
38
|
+
platformOrigin?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function readRuntimeGlobal(): FronteraRuntimeGlobal {
|
|
42
|
+
const injected = (globalThis as { __FRONTERA_CONFIG__?: FronteraRuntimeGlobal })
|
|
43
|
+
.__FRONTERA_CONFIG__
|
|
44
|
+
return injected ?? {}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function readGlobal(): FronteraRuntimeGlobal {
|
|
48
|
+
return readRuntimeGlobal()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function missing(field: string): never {
|
|
52
|
+
throw new FronteraError(
|
|
53
|
+
`Frontera SDK is not configured: ${field} is missing. Pass it explicitly, or set the matching FRONTERA_* environment variable.`,
|
|
54
|
+
{ code: 'CONFIG_MISSING' },
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Resolve configuration from, in order of precedence: explicit argument, the
|
|
60
|
+
* runtime global injected into an app page, then environment variables.
|
|
61
|
+
*
|
|
62
|
+
* `env` is a parameter rather than a direct `process.env` read so tests never
|
|
63
|
+
* mutate global state, and so this works unchanged in a browser bundle where
|
|
64
|
+
* `process` does not exist.
|
|
65
|
+
*/
|
|
66
|
+
export function resolveConfig(
|
|
67
|
+
explicit?: Partial<FronteraConfig>,
|
|
68
|
+
env: Record<string, string | undefined> = typeof process === 'undefined' ? {} : process.env,
|
|
69
|
+
): FronteraConfig {
|
|
70
|
+
const injected = readGlobal()
|
|
71
|
+
|
|
72
|
+
const rawBaseUrl = explicit?.apiBaseUrl ?? injected.apiBaseUrl ?? env.FRONTERA_API_URL
|
|
73
|
+
if (!rawBaseUrl) missing('apiBaseUrl')
|
|
74
|
+
|
|
75
|
+
const credential: FronteraCredential | undefined =
|
|
76
|
+
explicit?.credential ??
|
|
77
|
+
(env.FRONTERA_TOKEN ? { kind: 'apiKey', key: env.FRONTERA_TOKEN } : undefined)
|
|
78
|
+
if (!credential) missing('credential')
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
apiBaseUrl: rawBaseUrl.replace(/\/+$/, ''),
|
|
82
|
+
orgId: explicit?.orgId ?? injected.orgId ?? env.FRONTERA_ORG_ID,
|
|
83
|
+
workspaceId: explicit?.workspaceId ?? injected.workspaceId ?? env.FRONTERA_WORKSPACE_ID,
|
|
84
|
+
credential,
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Component,
|
|
3
|
+
StrictMode,
|
|
4
|
+
createContext,
|
|
5
|
+
useContext,
|
|
6
|
+
useEffect,
|
|
7
|
+
useState,
|
|
8
|
+
type ErrorInfo,
|
|
9
|
+
type ReactNode,
|
|
10
|
+
} from 'react'
|
|
11
|
+
import { createRoot } from 'react-dom/client'
|
|
12
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
13
|
+
|
|
14
|
+
import { connectToHost, type BridgeSession } from './bridge-client'
|
|
15
|
+
import type { BridgeInit } from './bridge-protocol'
|
|
16
|
+
import { FronteraClient } from './client'
|
|
17
|
+
import { applyHostTheme } from './theme'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The entry point every app shares.
|
|
21
|
+
*
|
|
22
|
+
* Before this existed, the quickstart asked each author to hand-write the same
|
|
23
|
+
* thirty-five lines: find the parent origin, postMessage `frontera:ready`,
|
|
24
|
+
* listen for `frontera:init`, build a client from the token that arrives, and
|
|
25
|
+
* only then mount. Copied boilerplate is where the origin check gets dropped —
|
|
26
|
+
* and a missing origin check is the whole vulnerability class this architecture
|
|
27
|
+
* exists to close. So it is written once, here.
|
|
28
|
+
*
|
|
29
|
+
* Mounting is DEFERRED until the handshake completes. An app has no data scope
|
|
30
|
+
* until the host tells it who it is, so rendering earlier only produces a flash
|
|
31
|
+
* of unauthorized requests, and every hook would need a "not ready yet" branch.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
export interface FronteraAppValue {
|
|
35
|
+
/** Everything the host said at handshake, including `path`. */
|
|
36
|
+
init: BridgeInit
|
|
37
|
+
client: FronteraClient
|
|
38
|
+
/** Ask the platform to change its URL — the counterpart to `init.path`. */
|
|
39
|
+
navigate(path: string): void
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const FronteraAppReactContext = createContext<FronteraAppValue | null>(null)
|
|
43
|
+
|
|
44
|
+
export function useFronteraApp(): FronteraAppValue {
|
|
45
|
+
const value = useContext(FronteraAppReactContext)
|
|
46
|
+
if (!value) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
'useFronteraApp() outside a Frontera app — createFronteraApp() installs this provider.',
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
return value
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A wrapper contributed by a domain package.
|
|
56
|
+
*
|
|
57
|
+
* This is a callback rather than `createFronteraApp` importing the domain
|
|
58
|
+
* clients directly, because `@frontera-sdk/blueprint` already depends on
|
|
59
|
+
* `@frontera-sdk/core` — reaching back the other way would make the two
|
|
60
|
+
* packages mutually dependent. `blueprintProvider` from
|
|
61
|
+
* `@frontera-sdk/blueprint/provider` is one of these.
|
|
62
|
+
*/
|
|
63
|
+
export type FronteraProvider = (value: FronteraAppValue, children: ReactNode) => ReactNode
|
|
64
|
+
|
|
65
|
+
export interface CreateFronteraAppOptions {
|
|
66
|
+
/** Element id to mount into. Defaults to `root`. */
|
|
67
|
+
rootId?: string
|
|
68
|
+
providers?: FronteraProvider[]
|
|
69
|
+
queryClient?: QueryClient
|
|
70
|
+
/** How long to wait for the host before reporting a failed mount. */
|
|
71
|
+
timeoutMs?: number
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface BoundaryProps {
|
|
75
|
+
onError: (error: Error, info: ErrorInfo) => void
|
|
76
|
+
children: ReactNode
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Report a render crash to the host instead of leaving a blank frame.
|
|
81
|
+
*
|
|
82
|
+
* The platform listens for `frontera:error` and surfaces it next to the app, so
|
|
83
|
+
* the author sees the message rather than an empty rectangle they have to open
|
|
84
|
+
* devtools to explain.
|
|
85
|
+
*/
|
|
86
|
+
class AppErrorBoundary extends Component<BoundaryProps, { error: Error | null }> {
|
|
87
|
+
state: { error: Error | null } = { error: null }
|
|
88
|
+
|
|
89
|
+
static getDerivedStateFromError(error: Error) {
|
|
90
|
+
return { error }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
componentDidCatch(error: Error, info: ErrorInfo) {
|
|
94
|
+
this.props.onError(error, info)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
render() {
|
|
98
|
+
if (!this.state.error) return this.props.children
|
|
99
|
+
return diagnostic('This app stopped rendering', this.state.error.message)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function diagnostic(title: string, detail: string): ReactNode {
|
|
104
|
+
return (
|
|
105
|
+
<div
|
|
106
|
+
role="alert"
|
|
107
|
+
style={{
|
|
108
|
+
fontFamily: 'var(--font-sans, system-ui, sans-serif)',
|
|
109
|
+
color: 'var(--foreground, #111)',
|
|
110
|
+
padding: 24,
|
|
111
|
+
lineHeight: 1.5,
|
|
112
|
+
}}
|
|
113
|
+
>
|
|
114
|
+
<strong>{title}</strong>
|
|
115
|
+
<div style={{ marginTop: 4, opacity: 0.75, fontSize: 14 }}>{detail}</div>
|
|
116
|
+
</div>
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Holds what the host can change underneath a running app.
|
|
122
|
+
*
|
|
123
|
+
* The credential is state rather than a captured constant because the host
|
|
124
|
+
* rotates it mid-session; `withCredential` returns a NEW client so requests
|
|
125
|
+
* already in flight keep the one they started with.
|
|
126
|
+
*/
|
|
127
|
+
function FronteraRoot({
|
|
128
|
+
session,
|
|
129
|
+
app,
|
|
130
|
+
providers,
|
|
131
|
+
}: {
|
|
132
|
+
session: BridgeSession
|
|
133
|
+
app: ReactNode
|
|
134
|
+
providers: FronteraProvider[]
|
|
135
|
+
}) {
|
|
136
|
+
const { init } = session
|
|
137
|
+
const [client, setClient] = useState(
|
|
138
|
+
() =>
|
|
139
|
+
new FronteraClient({
|
|
140
|
+
apiBaseUrl: init.apiBaseUrl,
|
|
141
|
+
orgId: init.orgId ?? undefined,
|
|
142
|
+
workspaceId: init.workspaceId ?? undefined,
|
|
143
|
+
credential: { kind: 'apiKey', key: init.token },
|
|
144
|
+
}),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
useEffect(
|
|
148
|
+
() => session.onToken((token) => setClient((c) => c.withCredential({ kind: 'apiKey', key: token }))),
|
|
149
|
+
[session],
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
useEffect(() => session.onTheme((theme) => applyHostTheme(theme)), [session])
|
|
153
|
+
|
|
154
|
+
const value: FronteraAppValue = {
|
|
155
|
+
init,
|
|
156
|
+
client,
|
|
157
|
+
navigate: (path) => session.send({ type: 'frontera:navigate', path }),
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
let tree: ReactNode = app
|
|
161
|
+
// Applied in reverse so the FIRST provider listed ends up outermost, which is
|
|
162
|
+
// the order a reader expects from the array.
|
|
163
|
+
for (const provider of [...providers].reverse()) tree = provider(value, tree)
|
|
164
|
+
|
|
165
|
+
return (
|
|
166
|
+
<FronteraAppReactContext.Provider value={value}>
|
|
167
|
+
<AppErrorBoundary
|
|
168
|
+
onError={(error) =>
|
|
169
|
+
session.send({ type: 'frontera:error', message: error.message, stack: error.stack })
|
|
170
|
+
}
|
|
171
|
+
>
|
|
172
|
+
{tree}
|
|
173
|
+
</AppErrorBoundary>
|
|
174
|
+
</FronteraAppReactContext.Provider>
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function createFronteraApp(
|
|
179
|
+
app: ReactNode,
|
|
180
|
+
options: CreateFronteraAppOptions = {},
|
|
181
|
+
): Promise<void> {
|
|
182
|
+
const rootId = options.rootId ?? 'root'
|
|
183
|
+
const element = document.getElementById(rootId)
|
|
184
|
+
if (!element) {
|
|
185
|
+
throw new Error(`createFronteraApp: no #${rootId} element — check index.html.`)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const root = createRoot(element)
|
|
189
|
+
|
|
190
|
+
let session: BridgeSession
|
|
191
|
+
try {
|
|
192
|
+
session = await connectToHost({ timeoutMs: options.timeoutMs })
|
|
193
|
+
} catch (err) {
|
|
194
|
+
// NOT a thrown rejection. This is the everyday outcome of running `vite`
|
|
195
|
+
// directly, and an unhandled rejection in the console reads as a crash in
|
|
196
|
+
// the app's own code. A visible panel says what actually happened.
|
|
197
|
+
const detail = err instanceof Error ? err.message : String(err)
|
|
198
|
+
root.render(diagnostic('This app runs inside Frontera', detail))
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Before the first paint, so the app never renders in the wrong palette.
|
|
203
|
+
applyHostTheme(session.init.theme)
|
|
204
|
+
|
|
205
|
+
const queryClient =
|
|
206
|
+
options.queryClient ??
|
|
207
|
+
new QueryClient({
|
|
208
|
+
// Platform data is read-only here and a mounted app is usually one
|
|
209
|
+
// screen; refetching on every focus change is noise, not freshness.
|
|
210
|
+
defaultOptions: { queries: { refetchOnWindowFocus: false, retry: 1 } },
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
root.render(
|
|
214
|
+
<StrictMode>
|
|
215
|
+
<QueryClientProvider client={queryClient}>
|
|
216
|
+
<FronteraRoot session={session} app={app} providers={options.providers ?? []} />
|
|
217
|
+
</QueryClientProvider>
|
|
218
|
+
</StrictMode>,
|
|
219
|
+
)
|
|
220
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error taxonomy for the Frontera SDK.
|
|
3
|
+
*
|
|
4
|
+
* `code` mirrors the service's `ErrorCode` enum
|
|
5
|
+
* (packages/service/src/lib/errors.ts) so callers branch on the same strings
|
|
6
|
+
* the API emits. Codes are deliberately not enumerated here — the service adds
|
|
7
|
+
* new ones, and an SDK that rejected unknown codes would need a release every
|
|
8
|
+
* time it did.
|
|
9
|
+
*/
|
|
10
|
+
export class FronteraError extends Error {
|
|
11
|
+
readonly code: string
|
|
12
|
+
readonly status?: number
|
|
13
|
+
readonly details?: unknown
|
|
14
|
+
|
|
15
|
+
constructor(message: string, opts: { code: string; status?: number; details?: unknown }) {
|
|
16
|
+
super(message)
|
|
17
|
+
this.name = 'FronteraError'
|
|
18
|
+
this.code = opts.code
|
|
19
|
+
this.status = opts.status
|
|
20
|
+
this.details = opts.details
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Codes used when the response body carries no envelope of its own. */
|
|
25
|
+
const STATUS_FALLBACK: Record<number, string> = {
|
|
26
|
+
400: 'BAD_REQUEST',
|
|
27
|
+
401: 'UNAUTHORIZED',
|
|
28
|
+
403: 'FORBIDDEN',
|
|
29
|
+
404: 'NOT_FOUND',
|
|
30
|
+
409: 'CONFLICT',
|
|
31
|
+
429: 'RATE_LIMITED',
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isErrorEnvelope(body: unknown): body is { error: true; code?: string; message?: string } {
|
|
35
|
+
return typeof body === 'object' && body !== null && (body as { error?: unknown }).error === true
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Turn a non-2xx response body into a `FronteraError`. */
|
|
39
|
+
export function errorFromResponse(status: number, body: unknown): FronteraError {
|
|
40
|
+
if (isErrorEnvelope(body)) {
|
|
41
|
+
return new FronteraError(body.message ?? `request failed with ${status}`, {
|
|
42
|
+
code: body.code ?? STATUS_FALLBACK[status] ?? 'INTERNAL_ERROR',
|
|
43
|
+
status,
|
|
44
|
+
details: body,
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
return new FronteraError(`request failed with ${status}`, {
|
|
48
|
+
code: STATUS_FALLBACK[status] ?? 'INTERNAL_ERROR',
|
|
49
|
+
status,
|
|
50
|
+
details: body ?? undefined,
|
|
51
|
+
})
|
|
52
|
+
}
|
package/src/theme.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applying the host's palette inside an app.
|
|
3
|
+
*
|
|
4
|
+
* The point is that an app sitting in the platform should not look pasted in —
|
|
5
|
+
* it follows the deployment's colours and its light/dark state without the
|
|
6
|
+
* author wiring anything.
|
|
7
|
+
*
|
|
8
|
+
* The hard part is precedence. An app that has defined its own brand must keep
|
|
9
|
+
* it; the host is supplying DEFAULTS, not a house style. So host tokens are
|
|
10
|
+
* written into a stylesheet inserted as the FIRST child of `<head>`, before the
|
|
11
|
+
* app's own imports. Same `:root` specificity, earlier in the cascade — the
|
|
12
|
+
* app's `brand.css` still wins every token it names, and inherits the rest.
|
|
13
|
+
*
|
|
14
|
+
* Inline styles on the root element would have been simpler and wrong: they
|
|
15
|
+
* beat every stylesheet, so the host would silently overwrite the customer's
|
|
16
|
+
* brand the moment it was mounted.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const STYLE_ID = 'frontera-host-theme'
|
|
20
|
+
|
|
21
|
+
export interface HostTheme {
|
|
22
|
+
tokens: Record<string, string>
|
|
23
|
+
colorScheme?: 'light' | 'dark'
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** CSS custom properties only — never arbitrary declarations from the host. */
|
|
27
|
+
function isTokenName(name: string): boolean {
|
|
28
|
+
return /^--[a-zA-Z0-9_-]+$/.test(name)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A token value the host sent.
|
|
33
|
+
*
|
|
34
|
+
* Restricted because this string is interpolated into a stylesheet: `}` would
|
|
35
|
+
* close the rule and let anything after it become a new one. The host is
|
|
36
|
+
* trusted, but a value that escapes its rule is a bug class worth closing at
|
|
37
|
+
* the boundary rather than reasoning about.
|
|
38
|
+
*/
|
|
39
|
+
function isTokenValue(value: string): boolean {
|
|
40
|
+
return typeof value === 'string' && value.length < 200 && !/[{}<>;]/.test(value)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function applyHostTheme(theme: HostTheme | undefined): void {
|
|
44
|
+
if (typeof document === 'undefined' || !theme) return
|
|
45
|
+
|
|
46
|
+
const declarations = Object.entries(theme.tokens ?? {})
|
|
47
|
+
.filter(([name, value]) => isTokenName(name) && isTokenValue(value))
|
|
48
|
+
.map(([name, value]) => `${name}: ${value};`)
|
|
49
|
+
.join('\n ')
|
|
50
|
+
|
|
51
|
+
if (declarations) {
|
|
52
|
+
let style = document.getElementById(STYLE_ID) as HTMLStyleElement | null
|
|
53
|
+
if (!style) {
|
|
54
|
+
style = document.createElement('style')
|
|
55
|
+
style.id = STYLE_ID
|
|
56
|
+
// First in <head>, so every app stylesheet that follows can override.
|
|
57
|
+
document.head.prepend(style)
|
|
58
|
+
}
|
|
59
|
+
style.textContent = `:root {\n ${declarations}\n}`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (theme.colorScheme) {
|
|
63
|
+
const dark = theme.colorScheme === 'dark'
|
|
64
|
+
document.documentElement.classList.toggle('dark', dark)
|
|
65
|
+
// Tells the browser to pick the matching form controls and scrollbars,
|
|
66
|
+
// which no amount of custom properties can do.
|
|
67
|
+
document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
|
|
68
|
+
}
|
|
69
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { FronteraConfig } from './config'
|
|
2
|
+
import { errorFromResponse } from './errors'
|
|
3
|
+
|
|
4
|
+
export interface RequestOptions {
|
|
5
|
+
// PATCH is included because the platform uses it for partial writes —
|
|
6
|
+
// staging an agent draft is one. The transport already passes any method
|
|
7
|
+
// straight to fetch, so its absence here was a type narrower than the
|
|
8
|
+
// runtime, which type-checks a correct call as an error.
|
|
9
|
+
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
|
|
10
|
+
body?: unknown
|
|
11
|
+
query?: Record<string, string | number | boolean | undefined>
|
|
12
|
+
signal?: AbortSignal
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Auth and scope headers for one request.
|
|
17
|
+
*
|
|
18
|
+
* Both credential kinds travel as `Authorization: Bearer`. `x-org-id` and
|
|
19
|
+
* `x-workspace-id` mirror what the web app sends and are what the service's
|
|
20
|
+
* auth middleware reads to scope a session request. A workspace key ignores
|
|
21
|
+
* them and resolves its own scope from the key row, so they can never widen
|
|
22
|
+
* access beyond what the credential already allows.
|
|
23
|
+
*/
|
|
24
|
+
export function authHeaders(config: FronteraConfig): Record<string, string> {
|
|
25
|
+
const token =
|
|
26
|
+
config.credential.kind === 'apiKey' ? config.credential.key : config.credential.token
|
|
27
|
+
const headers: Record<string, string> = { authorization: `Bearer ${token}` }
|
|
28
|
+
if (config.orgId) headers['x-org-id'] = config.orgId
|
|
29
|
+
if (config.workspaceId) headers['x-workspace-id'] = config.workspaceId
|
|
30
|
+
return headers
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Unwrap the service response envelope when present.
|
|
35
|
+
*
|
|
36
|
+
* `ok()` returns `{ data, message, error: false }`, but several routers — the
|
|
37
|
+
* Blueprint query router among them — return their payload raw. Detect the
|
|
38
|
+
* envelope rather than assuming it.
|
|
39
|
+
*/
|
|
40
|
+
export function unwrap<T>(body: unknown): T {
|
|
41
|
+
if (
|
|
42
|
+
typeof body === 'object' &&
|
|
43
|
+
body !== null &&
|
|
44
|
+
!Array.isArray(body) &&
|
|
45
|
+
(body as { error?: unknown }).error === false &&
|
|
46
|
+
'data' in body
|
|
47
|
+
) {
|
|
48
|
+
return (body as { data: T }).data
|
|
49
|
+
}
|
|
50
|
+
return body as T
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function buildUrl(config: FronteraConfig, path: string, query?: RequestOptions['query']): string {
|
|
54
|
+
const url = new URL(`${config.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`)
|
|
55
|
+
if (query) {
|
|
56
|
+
for (const [key, value] of Object.entries(query)) {
|
|
57
|
+
if (value === undefined) continue
|
|
58
|
+
url.searchParams.set(key, String(value))
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return url.toString()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* `fetchImpl` is injectable so tests never touch the network. Production
|
|
66
|
+
* callers omit it and get the platform `fetch`.
|
|
67
|
+
*/
|
|
68
|
+
export async function httpRequest<T>(
|
|
69
|
+
config: FronteraConfig,
|
|
70
|
+
path: string,
|
|
71
|
+
options: RequestOptions = {},
|
|
72
|
+
fetchImpl: typeof fetch = fetch,
|
|
73
|
+
): Promise<T> {
|
|
74
|
+
const headers: Record<string, string> = { ...authHeaders(config), accept: 'application/json' }
|
|
75
|
+
if (options.body !== undefined) headers['content-type'] = 'application/json'
|
|
76
|
+
|
|
77
|
+
const response = await fetchImpl(buildUrl(config, path, options.query), {
|
|
78
|
+
method: options.method ?? 'GET',
|
|
79
|
+
headers,
|
|
80
|
+
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
81
|
+
signal: options.signal,
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
const text = await response.text()
|
|
85
|
+
let parsed: unknown = null
|
|
86
|
+
if (text.length > 0) {
|
|
87
|
+
try {
|
|
88
|
+
parsed = JSON.parse(text)
|
|
89
|
+
} catch {
|
|
90
|
+
parsed = text
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!response.ok) throw errorFromResponse(response.status, parsed)
|
|
95
|
+
return unwrap<T>(parsed)
|
|
96
|
+
}
|