@lemoncloud/chatic-apps-sdk 0.0.0-stage → 0.2.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/AGENTS.md ADDED
@@ -0,0 +1,56 @@
1
+ # Rules for an AI assistant writing a Chatic app
2
+
3
+ You are writing a web page that opens inside the DoU app, at `https://<name>.apps.chatic.io`, using
4
+ `@lemoncloud/chatic-apps-sdk`. Follow these rules. `GUIDE.md` in this package says how to set the
5
+ project up and what the bundle looks like; `README.md` is the reference for every call, limit and error
6
+ code. Read the part you need before you write code that depends on it.
7
+
8
+ ## The project
9
+
10
+ 1. **Static files only.** The output is a folder with `index.html` at its top and
11
+ `.well-known/chatic-app.json` beside it. No server code, no server-side rendering, no server routing.
12
+ With Vite, put the manifest at `public/.well-known/chatic-app.json`.
13
+ 2. **The page is always entered at `/`.** Do not route on the path and do not set a `base`. A shared
14
+ link carries its data in the query: read it from `location.search` when the page starts.
15
+ 3. **Install the mock in development only**, before `connect()`:
16
+ `if (import.meta.env.DEV) installChaticAppsMock({ permissions: [...] })`, imported from
17
+ `@lemoncloud/chatic-apps-sdk/mock`.
18
+
19
+ ## The calls
20
+
21
+ 4. Use `@lemoncloud/chatic-apps-sdk`. Call `await connect()` once at start, inside `try/catch`.
22
+ 5. Check `apps.inApp` and `apps.supports(capability)` before offering an app feature; never compare
23
+ version numbers.
24
+ 6. Every call can throw `ChaticAppsError`; branch on `error.code` only, never on `error.message`.
25
+ 7. Take the theme and language from `apps.context` and `apps.onContextChange`, not from the OS.
26
+ 8. Share links built with `apps.link({ ... })`, never the page's own address.
27
+ 9. Keep the page's state in `apps.storage` as it changes, and at the latest on `visibilitychange` to
28
+ `hidden`; never in `localStorage`. What must follow the user to another phone goes on your own server
29
+ under `apps.getUserKey()`.
30
+ 10. For screens and dialogs inside the page, keep a stack: while it holds more than one screen,
31
+ `apps.onBack(back)`; at the root, `apps.onBack(null)`, so Android back closes the page. iOS has no
32
+ back key, so draw a back button that calls the same `back()` whenever there is a screen to go back to.
33
+ Keep the stack in memory: a router that pushes browser history (hash routes, `pushState`) makes
34
+ Android back at the root walk that history instead of closing the page.
35
+ 11. Use `apps.onCloseRequest` only to protect unsaved work; return `true` to close.
36
+ 12. For the camera or microphone, call `apps.permissions.request(kind)` when the user reaches for the
37
+ feature, never at start, then `getUserMedia`. No manifest permission is needed. Do not time the
38
+ request out, and send `'blocked'` to `apps.openSettings()`. Treat the request's answer, not
39
+ `query`'s, as the truth: on Android `query` can read `'prompt'` for a blocked permission.
40
+
41
+ ## The page
42
+
43
+ 13. No `window.opener`, no popup logins, no file downloads.
44
+ 14. Never put the user's data in errors or in `reportError`.
45
+ 15. List the permissions the page needs (`clipboard`, `share`, `openUrl`, `userKey`) in
46
+ `/.well-known/chatic-app.json` — and nothing it does not use. A call that needs one fails with
47
+ `NOT_SUPPORTED` without it.
48
+ 16. Do not draw for the safe area: the page already lies inside it on every edge.
49
+ 17. The page has no title bar unless the manifest sets `"display": "standard"`: draw your own header and
50
+ title, and keep the top-right corner clear, where the app's close button floats.
51
+
52
+ ## Before you say it is done
53
+
54
+ Run the build, and check that `dist/index.html` and `dist/.well-known/chatic-app.json` exist. Say what
55
+ you could not check: a browser with the mock proves a page's logic and nothing about a phone — layout,
56
+ the keyboard and real haptics need the app.
package/GUIDE.md ADDED
@@ -0,0 +1,219 @@
1
+ # Building a page with chatic-apps-sdk
2
+
3
+ A Chatic app is a web page that opens inside the DoU app, over everything else, at
4
+ `https://<name>.apps.chatic.io`. You build it like any web page, and `@lemoncloud/chatic-apps-sdk`
5
+ connects it to the app: closing, the title, haptics, sharing, saving data on the device, and more.
6
+ This guide is how to set a project up and what comes out of it. The library's calls, limits and error
7
+ codes are in the package `README.md`; this guide does not repeat them.
8
+
9
+ ## What you are building
10
+
11
+ - **Static files.** The app loads your page from a web address like any browser. There is no server
12
+ of yours to run for the page itself, and no server-side rendering.
13
+ - **One page, entered at the root.** The app always opens `/`. A link carries data in its query
14
+ (`/?level=3`), never in a path, so a page does not route on the path.
15
+ - **In the phone's own web view.** The page runs in WKWebView on iOS and the Android System WebView
16
+ on Android, so it can use what those engines support. Check the oldest phones you mean to support.
17
+ - **Also in a browser, while you build.** The library falls back to what a browser can do, and ships a
18
+ stand-in for the app, so you can write and try the page without a phone.
19
+
20
+ ## Choose a toolchain
21
+
22
+ The library has no runtime dependencies and no opinion about the rest, so use what you know. Three
23
+ shapes work, from least to most tooling:
24
+
25
+ | Shape | Use it when | The library comes from |
26
+ | ------------------------------- | --------------------------------------------- | ---------------------------------------------------- |
27
+ | One `index.html`, no build | A small page, a prototype | A `<script>` tag that defines `window.ChaticAppsSDK` |
28
+ | Vite and plain TypeScript or JS | A page of its own with a few screens of logic | `npm install` |
29
+ | Vite and React, Vue or Svelte | You already build interfaces in one of these | `npm install` |
30
+
31
+ Anything that ends in static files is fine, with these limits:
32
+
33
+ - **No server rendering and no server routing.** A framework's static or single-page mode, not its
34
+ server mode. Next.js needs `output: 'export'`, Nuxt needs `ssr: false` or `nuxt generate`, and
35
+ SvelteKit needs the static adapter in single-page mode.
36
+ - **Do not depend on a path.** A client-side router must work with the page entered at `/`, and must
37
+ not be needed to reach a shared link: put what a link carries in the query.
38
+ - **Do not depend on `window.opener`, popups or file downloads.** A popup opens in the same view and
39
+ replaces the page, so a login that answers through `window.opener` cannot work, and a download is not
40
+ handled on iOS; the package `README.md` says what to do instead.
41
+
42
+ Vite is the shortest road, and the rest of this guide uses it.
43
+
44
+ ## Set up a project
45
+
46
+ ```bash
47
+ npm create vite@latest quiz -- --template vanilla-ts
48
+ cd quiz
49
+ npm install @lemoncloud/chatic-apps-sdk
50
+ ```
51
+
52
+ Pick `react-ts`, `vue-ts` or `svelte-ts` for the template instead if you want one; nothing below
53
+ depends on it. Replace `src/main.ts` with a page that connects:
54
+
55
+ ```ts
56
+ import { connect, ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
57
+ import { installChaticAppsMock } from '@lemoncloud/chatic-apps-sdk/mock';
58
+
59
+ // A stand-in for the app in the browser, in development only. Vite removes a branch that is always
60
+ // false, so it is not in the production bundle. The controller lets you play the user's side.
61
+ if (import.meta.env.DEV) {
62
+ const app = installChaticAppsMock({ permissions: ['share', 'userKey'] });
63
+ Object.assign(window, { app }); // then `app.pressBack()` in the browser console
64
+ }
65
+
66
+ async function start() {
67
+ try {
68
+ const apps = await connect();
69
+ document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
70
+ apps.onContextChange(context => (document.documentElement.dataset.theme = context.theme));
71
+ } catch (error) {
72
+ // `UNSUPPORTED_PROTOCOL` means the app is newer than this library: update the library.
73
+ const needsUpdate = error instanceof ChaticAppsError && error.code === 'UNSUPPORTED_PROTOCOL';
74
+ document.body.textContent = needsUpdate ? 'This page needs an update.' : 'This page could not start.';
75
+ }
76
+ }
77
+
78
+ void start();
79
+ ```
80
+
81
+ Then:
82
+
83
+ ```bash
84
+ npm run dev # the page in your browser, with the stand-in for the app
85
+ npm run build # the bundle, in dist/
86
+ ```
87
+
88
+ With React, Vue or Svelte, put the same lines where the application starts, before it renders.
89
+
90
+ ### Developing in a browser
91
+
92
+ `installChaticAppsMock` turns the tab into a fake app: it answers as the app does, logs every call, and
93
+ lets you play the user's side through the controller it returns — the Android back button, a close
94
+ request, a theme change (the example above puts it on `window`, so the browser console can reach it). It grants only the permissions you list, as the app grants only what the page's manifest holds.
95
+ It proves the page's logic and nothing about a phone: layout, the keyboard, the safe area and real
96
+ haptics need the app.
97
+
98
+ ## The bundle
99
+
100
+ What you hand over is a folder of static files. With Vite, that is `dist/`:
101
+
102
+ ```text
103
+ dist/
104
+ ├── index.html
105
+ ├── assets/
106
+ │ ├── index-3fa1c9.js
107
+ │ └── index-81b2d0.css
108
+ └── .well-known/
109
+ └── chatic-app.json
110
+ ```
111
+
112
+ - **`index.html` is at the top of the folder.** It is what `/` serves.
113
+ - **Assets are named by root-relative address** (`/assets/…`), which Vite does by default. The page is
114
+ always served from the root of its own address, so do not set a `base` path.
115
+ - **`.well-known/chatic-app.json` is the page's manifest.** The app reads it before it shows the page.
116
+ In Vite, put the file at `public/.well-known/chatic-app.json` and the build copies it as it is.
117
+ - **Nothing else is needed**: no server code, no `package.json`, no source files. Without a build, the
118
+ same layout holds: `index.html` and a `.well-known/chatic-app.json` beside it.
119
+
120
+ The manifest names the page and asks for what it needs:
121
+
122
+ ```json
123
+ {
124
+ "manifestVersion": 1,
125
+ "name": "Quiz",
126
+ "permissions": ["share", "userKey"],
127
+ "orientation": "portrait"
128
+ }
129
+ ```
130
+
131
+ A page has no bar by default: a small close button floats in the top-right corner, always, and the page
132
+ draws its own header. Add `"display": "standard"` to get the app's bar with the page's title and a
133
+ close button instead.
134
+
135
+ `manifestVersion` must be `1`; the app ignores a manifest it cannot read. Ask only for the permissions
136
+ the page uses — `clipboard`, `share`, `openUrl`, `userKey` — and see the
137
+ package `README.md` for what each one unlocks and for `display` and `orientation`. Without a manifest a
138
+ page still runs; it gets everything but those four.
139
+
140
+ ## How the page behaves in the app
141
+
142
+ These are the facts that most often surprise a page written first for a browser. The package `README.md`
143
+ has the detail on each.
144
+
145
+ - **The app can close the page at any time.** Save as you go, and when `document` turns `hidden`.
146
+ Keep the page's own data in `apps.storage`, not `localStorage`, which goes when the system clears
147
+ website data. What must follow the user to another phone goes on your own server, under
148
+ `apps.getUserKey()`.
149
+ - **The page lies inside the safe area on every edge.** There are no insets to handle.
150
+ - **Dark mode follows the app's theme**, from `apps.context.theme`, not the phone's.
151
+ - **Share `apps.link({ … })`**, not the page's address, and read what a link carries from
152
+ `location.search` when the page starts.
153
+ - **There is no title bar** unless the manifest asks for one, so the page draws its own header and title.
154
+ See [Screens and Back](#screens-and-back).
155
+ - **Android back** is yours only while you set `apps.onBack(handler)`; otherwise the app decides.
156
+ - **Errors**: every call can throw `ChaticAppsError`; branch on its `code`, never its `message`.
157
+
158
+ ## Screens and Back
159
+
160
+ A page with more than one screen — a menu, a game, a settings page — needs its own way back. There is
161
+ no bar and no back arrow to lean on: the only control the app gives is the small close button at the
162
+ top-right corner, which leaves the page. Android has a back key; iOS has none. So the page keeps a
163
+ stack of its screens, draws its own back button, and takes the Android back key only while there is a
164
+ screen to go back to:
165
+
166
+ ```ts
167
+ const screens = ['home'];
168
+
169
+ // Take Android back while a screen is stacked; give it back at the root, where the app closes the page.
170
+ const sync = () => apps.onBack(screens.length > 1 ? back : null);
171
+
172
+ function open(name: string) {
173
+ screens.push(name);
174
+ sync();
175
+ render();
176
+ }
177
+
178
+ function back() {
179
+ if (screens.length > 1) screens.pop();
180
+ sync();
181
+ render();
182
+ }
183
+
184
+ sync();
185
+ ```
186
+
187
+ Draw a back button in your header whenever `screens.length > 1` and have it call `back()`; at the root
188
+ draw none, since the close button is already there. In React, Vue or Svelte keep `screens` in state and
189
+ call `apps.onBack` from an effect that runs when its length changes. The same pattern closes a dialog:
190
+ treat an open dialog as a screen.
191
+
192
+ Three things to leave alone: do not set a handler at the root, so Android back still closes the page;
193
+ do not use `onCloseRequest` for navigation — it is for unsaved work; and keep the screens in memory, not
194
+ in the browser's history. A router that pushes entries (hash routes, `pushState`) gives the page a history,
195
+ and with a history Android back at the root walks it instead of closing the page. On iOS the edge swipe
196
+ only walks that history, so an in-memory stack needs the back button above either way.
197
+
198
+ Keep the top-right corner of every screen clear of your own controls: the close button floats there.
199
+
200
+ ## For an AI assistant in your project
201
+
202
+ The package ships `AGENTS.md`: rules for an assistant writing a Chatic app. Assistants read an
203
+ `AGENTS.md` at the top of the project, not one inside `node_modules`, so copy it there, or point your
204
+ assistant at `node_modules/@lemoncloud/chatic-apps-sdk/AGENTS.md`.
205
+
206
+ ## Before you hand it over
207
+
208
+ - [ ] `npm run build` produces `dist/` with `index.html` and `.well-known/chatic-app.json` at its top.
209
+ - [ ] Opened from a plain file server, the built page works at the root, with no path in the address.
210
+ - [ ] The page works in a browser with no app (`apps.inApp` is `false`) and with the stand-in.
211
+ - [ ] Every permission in the manifest is used, and every call that needs one is guarded with
212
+ `apps.supports(…)` or handles `NOT_SUPPORTED`.
213
+ - [ ] State is saved as the user goes, not only at a button.
214
+ - [ ] No `window.opener`, popup login, file download or server-side rendering.
215
+ - [ ] No user data in errors, in `reportError` or in the page's own logs.
216
+
217
+ ## Deploying
218
+
219
+ How a page is submitted, reviewed and deployed to its address is not part of this guide yet.
package/README.md CHANGED
@@ -1,3 +1,287 @@
1
- # Temporary Holding Version
1
+ # chatic-apps-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build pages that run inside the DoU app. A page on `https://<name>.apps.chatic.io` opens in the app
4
+ over everything else, and talks to the app through this library: close itself and hand back a result,
5
+ title the app's bar (when the page asks for one), play a haptic, share, copy, open a link outside, keep its own data on the device,
6
+ get a key to keep the user's data under on a server, take Android's back button, and ask before the
7
+ user closes it. Users reach it in the app only — a link to it never opens it in a browser — but the
8
+ same page runs in a plain browser tab too while you build it, where the library falls back to what the
9
+ browser can do.
10
+
11
+ Published as `@lemoncloud/chatic-apps-sdk`. No runtime dependencies. `GUIDE.md` in the package says how
12
+ to set up a project and what the bundle looks like; `AGENTS.md` holds the rules for an AI assistant
13
+ writing a page.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @lemoncloud/chatic-apps-sdk
19
+ ```
20
+
21
+ Or, with no bundler, one script that defines `window.ChaticAppsSDK` (pin the version; the mock below
22
+ is not in this file):
23
+
24
+ ```html
25
+ <script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.2.0/chatic-apps-sdk.global.js"></script>
26
+ ```
27
+
28
+ ## Start
29
+
30
+ ```ts
31
+ import { connect, ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
32
+
33
+ try {
34
+ const apps = await connect();
35
+ document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
36
+ } catch (error) {
37
+ // `UNSUPPORTED_PROTOCOL`: the app is newer than this library — update the library, and tell the
38
+ // user this page needs an update. `TIMEOUT`: the app did not answer (see "Rules worth knowing").
39
+ }
40
+ ```
41
+
42
+ Call `connect()` when the page starts. In the app it waits for the app's answer (a few
43
+ milliseconds); in a browser it returns at once. Calling it again returns the same connection, so any
44
+ part of the page may call it. Everything below is a method on what it returns.
45
+
46
+ ## A complete page
47
+
48
+ One file, no build step. Save it as `index.html`, open it in a browser, and it runs with the browser
49
+ stand-ins; deployed to your `apps.chatic.io` address, it runs in the app.
50
+
51
+ ```html
52
+ <!doctype html>
53
+ <html lang="ko">
54
+ <head>
55
+ <meta charset="utf-8" />
56
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
57
+ <title>Quiz</title>
58
+ <script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.2.0/chatic-apps-sdk.global.js"></script>
59
+ </head>
60
+ <body>
61
+ <h1 id="score">0</h1>
62
+ <button id="plus">+1</button>
63
+ <button id="share" hidden>Share</button>
64
+ <button id="done">Done</button>
65
+ <script type="module">
66
+ const { connect } = window.ChaticAppsSDK;
67
+ const apps = await connect();
68
+ let score = 0;
69
+
70
+ document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
71
+ apps.onContextChange(context => (document.documentElement.dataset.theme = context.theme));
72
+
73
+ document.getElementById('plus').onclick = () => {
74
+ score += 1;
75
+ document.getElementById('score').textContent = String(score);
76
+ apps.haptic('selection');
77
+ };
78
+
79
+ // Offer only what this app can do here.
80
+ const share = document.getElementById('share');
81
+ share.hidden = !(apps.supports('share') || !apps.inApp);
82
+ share.onclick = () => apps.share({ message: `I scored ${score}`, url: apps.link({ score }) });
83
+
84
+ document.getElementById('done').onclick = async () => {
85
+ if (apps.inApp) await apps.finish({ score });
86
+ };
87
+ </script>
88
+ </body>
89
+ </html>
90
+ ```
91
+
92
+ ## What a page can do
93
+
94
+ | Call | In the app | In a browser | Needs permission |
95
+ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ----------------------------------- | ---------------- |
96
+ | `finish(result?)` | Closes the view; `result` (JSON, ≤ 16 KiB) goes back to the opener | `NOT_IN_APP` | — |
97
+ | `setTitle(title)` | The app's bar shows it, if the page asked for the bar (1–100 characters) | `document.title` | — |
98
+ | `haptic(kind)` | `selection`, `impact`, `success`, `warning`, `error` | a short vibration, if any | — |
99
+ | `onBack(handler \| null)` | Android back calls `handler` and does nothing else | never called | — |
100
+ | `onCloseRequest(handler \| null)` | Asks before the user closes; return `true` to close | never called | — |
101
+ | `reportError(error)` | Into DoU's log, under your origin (20 per page load) | `console.error` | — |
102
+ | `copy(text)` | The clipboard | the browser's clipboard | `clipboard` |
103
+ | `share({ title, message, url })` | The share sheet; waits for the user (see below) | Web Share, else copies (`'copied'`) | `share` |
104
+ | `openUrl(url)` | The browser, mail, phone, SMS or a store | a new tab | `openUrl` |
105
+ | `getUserKey()` | 64 hex characters, the same for this device and site | `NOT_IN_APP` | `userKey` |
106
+ | `link(params?)` | A link that opens this page in the app (see below) | the page's own root | — |
107
+ | `storage.get(key)`, `.set(key, value)`, … | Your page's own storage on the device (see below) | `localStorage`, same limits | — |
108
+ | `permissions.query(kind)`, `.request(kind)`, `openSettings()` | Where the app stands with the OS for `'camera'` or `'microphone'`, and asking it (see below) | the browser's own permission | — |
109
+
110
+ Plus `apps.context` (the app's language, theme, platform and the `params` you were opened with),
111
+ `apps.onContextChange(listener)` for a theme or language change, `apps.supports(capability)`,
112
+ `apps.inApp`, and `apps.disconnect()`.
113
+
114
+ - **`share`** resolves `'shared'` or `'dismissed'` on iOS. On Android it resolves `'shared'` as soon as
115
+ the chooser opens, whatever the user then does. It needs a non-blank `message` or a `url`; `url` must
116
+ be `http(s)`; `title`, `message` and `url` are at most 100, 4,000 and 2,048 characters.
117
+ - **`link(params)`** takes what the link should carry as an object and gives
118
+ `https://app.chatic.io/apps/<app id>?level=3&seed=7` for `link({ level: 3, seed: 7 })`. A tap opens
119
+ your page in the app **at its root** with that query — read it from `location.search`; a link carries
120
+ no path and no fragment. Where the app is not installed, the tap offers the app's store page, never
121
+ your page in the browser. The app id is the one your page was registered under, which need not be its
122
+ subdomain, so never write the link by hand. In a browser, or an app before links to pages existed, it
123
+ gives your page's own root with the same query.
124
+ - **`storage`** keeps JSON on the device for your site alone: `get(key)`, `getMany(keys)`,
125
+ `set(key, value)`, `setMany(entries)` (all or none), `remove(key or keys)`, `keys()`, `clear()` and
126
+ `usage()`. It survives relaunches and sign-outs and goes with an uninstall; it does not follow the user
127
+ to another phone. Your site gets 1,048,576 characters in all (keys plus values as JSON) — past it a
128
+ write fails with `QUOTA_EXCEEDED` and changes nothing — keys of 1–200 characters (not `__proto__`),
129
+ and at most 64 KiB in one call (`TOO_LARGE`). A value is written in one call, so one value stays
130
+ under 64 KiB; split anything bigger across keys.
131
+ - **`permissions`** is for the camera and the microphone, which a page uses with the browser's own
132
+ `getUserMedia` — the OS asks the user the first time, under DoU's name, so the user's answer is for
133
+ every page, not yours alone. `query(kind)` reports `'granted'`, `'prompt'` (not asked, or refused and
134
+ may be asked again) or `'blocked'` (the OS will not ask again) without showing anything — on Android
135
+ it can read `'prompt'` for one the OS will no longer ask for, so trust what `request` answers;
136
+ `request(kind)` shows the prompt and resolves with the answer; `openSettings()` opens DoU's page in
137
+ the OS settings, the way back for `'blocked'`. Ask when the user reaches for the feature, not at
138
+ start, and do not time `request` out: it waits for the user. A page can skip all this and call
139
+ `getUserMedia`; it then meets the prompt in the middle of the capture. In a browser the same calls
140
+ read and ask the browser's own permission, and `openSettings()` is `NOT_IN_APP`.
141
+ - **Uncaught errors are reported for you.** `connect()` listens for `error` and `unhandledrejection` and
142
+ sends them to DoU's log. An `Error` sends its message and stack, a string itself, anything else only
143
+ its type. Pass `connect({ reportErrors: false })` to turn it off.
144
+
145
+ ## Permissions
146
+
147
+ The four calls marked above need a permission your page asks for in a file on its own site,
148
+ `/.well-known/chatic-app.json`:
149
+
150
+ ```json
151
+ {
152
+ "manifestVersion": 1,
153
+ "name": "Quiz",
154
+ "permissions": ["share", "userKey"],
155
+ "display": "standard",
156
+ "orientation": "portrait"
157
+ }
158
+ ```
159
+
160
+ You ask; an administrator grants them when your page is reviewed, and only what was granted is
161
+ deployed. Without the file your page gets everything else but not these four, which then fail with
162
+ `NOT_SUPPORTED`. A page has **no bar by default**: a small close button floats in the top-right corner
163
+ (keep it clear) and the page draws its own header. `display: "standard"` asks for the app's bar, with
164
+ the page's title and a close button; `orientation` is `any`, `portrait` or `landscape`. The app reads
165
+ the file before it shows your page, keeps it for the rest of its run, and fetches a fresh copy behind
166
+ each later open: a change to the file takes effect one open later.
167
+
168
+ ## Errors
169
+
170
+ Every failure is a `ChaticAppsError` with a `code`:
171
+
172
+ ```ts
173
+ import { ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
174
+
175
+ try {
176
+ const key = await apps.getUserKey();
177
+ } catch (error) {
178
+ if (error instanceof ChaticAppsError && (error.code === 'NOT_SUPPORTED' || error.code === 'NOT_IN_APP')) {
179
+ // A browser, an older app, or no `userKey` permission: sign in your own way.
180
+ }
181
+ }
182
+ ```
183
+
184
+ | Code | Means |
185
+ | ---------------------- | ----------------------------------------------------------------------------------------------------------------------- |
186
+ | `NOT_SUPPORTED` | Not available: an older app, a permission the page does not hold, or no browser clipboard or storage |
187
+ | `NOT_IN_APP` | The call needs the app, and the page is in a browser |
188
+ | `TIMEOUT` | The app did not answer in 10 seconds (time in the background does not count) |
189
+ | `INVALID` | A value is missing, of the wrong type, or too long |
190
+ | `TOO_LARGE` | One call's data is over 65,536 characters |
191
+ | `LINK_NOT_ALLOWED` | The link cannot be opened or shared from a page |
192
+ | `NOT_OPEN` | `finish` after the view has already closed |
193
+ | `UNAVAILABLE` | No device id to make a user key from, the page's storage could not be opened, or the device has no camera or microphone |
194
+ | `SETTINGS_ERROR` | `openSettings()`: the OS would not open the settings |
195
+ | `QUOTA_EXCEEDED` | A storage write would go past 1,048,576 characters; nothing was written |
196
+ | `DISCONNECTED` | The call was waiting when `disconnect()` closed the connection |
197
+ | `UNSUPPORTED_PROTOCOL` | `connect()` only: the app is newer than this library; update it |
198
+
199
+ Treat a code not in this table as that call failing, and nothing more.
200
+
201
+ ## Rules worth knowing
202
+
203
+ - **Decide what to offer with `apps.supports(...)`**, never with a version number. A share button
204
+ shows only if `apps.supports('share')`.
205
+ - **Save as you go.** The app or the web that opened the page can close it at any time without
206
+ asking. Listen to `document`'s `visibilitychange` and save when it turns `hidden` — the app sends no
207
+ "going to the background" signal.
208
+ - **Share `apps.link(params)`**, not your page's address: a tap on it opens the page in the app.
209
+ Put what a shared link needs in its query and read it from `location.search` at start; nothing
210
+ after your page's root survives a link.
211
+ - **The user key is not an account and proves nothing.** It stays the same on one device for your site,
212
+ and differs on every other site. Two people on one phone share it; anyone who learns one can send it.
213
+ Keep game progress under it, not money.
214
+ - **`onCloseRequest` is for something the user would lose.** A second close within three seconds always
215
+ closes, so a page cannot keep the user in.
216
+ - **Leaving your origin leaves the bridge.** A link to another site opens in the browser; a page on
217
+ another `apps.chatic.io` address loads in the view but gets no answers, so `connect()` there ends in
218
+ `TIMEOUT`.
219
+ - **You cannot see the error reports.** They go to DoU's log, read by the people who review pages.
220
+ Send errors to your own server too if you want to see them.
221
+
222
+ ## What this WebView is like
223
+
224
+ - **Use `apps.storage`, not the WebView's own**: `localStorage` and IndexedDB work, but go whenever the
225
+ system clears website data. Keep what must follow the user to another phone on your own server, under
226
+ `getUserKey()`.
227
+ - **No popups**: `window.open` and `target="_blank"` load in the same view, so a login that answers
228
+ through `window.opener` does not work. Use a redirect login.
229
+ - **Downloads**: a file download is not handled on iOS. Show the content instead.
230
+ - **Camera and microphone** work through the browser APIs, under DoU's name: the OS asks the user
231
+ "DoU would like to…". What your page uses is part of its review.
232
+ - **Your own server**: calls to it are ordinary cross-origin requests from `https://<name>.apps.chatic.io`;
233
+ allow that origin in its CORS settings.
234
+ - **Layout**: the page sits inside the safe area on every edge; there are no insets to handle. Use the
235
+ context's `theme`, not the OS's, for dark mode — the user can set DoU's theme apart from the phone's.
236
+
237
+ ## Try it without the app
238
+
239
+ `@lemoncloud/chatic-apps-sdk/mock` turns a browser tab into a stand-in for the app. Install it before
240
+ `connect()`, in development only:
241
+
242
+ ```ts
243
+ import { connect } from '@lemoncloud/chatic-apps-sdk';
244
+ import { installChaticAppsMock } from '@lemoncloud/chatic-apps-sdk/mock';
245
+
246
+ const app = import.meta.env.DEV ? installChaticAppsMock({ permissions: ['share', 'userKey'] }) : null;
247
+ const apps = await connect();
248
+
249
+ // Play the user's side from the console or a dev button:
250
+ app?.pressBack();
251
+ app?.requestClose();
252
+ app?.changeContext({ theme: 'dark' });
253
+ console.log(app?.closed); // { by: 'page', result } once the page finishes, { by: 'user' } on a close
254
+ console.log(app?.storage); // what the page has stored
255
+ ```
256
+
257
+ Pass `storage: { … }` to start with data already stored; the mock keeps it in memory only.
258
+
259
+ It answers as the app does — the base calls, plus the `permissions` you give it, and `NOT_SUPPORTED`
260
+ for the rest — checks what the app checks, and logs every call. It is a stand-in: the share sheet is
261
+ logged rather than shown, the user key is not the app's, and it proves nothing about a phone.
262
+
263
+ ## For an AI assistant writing a page
264
+
265
+ `AGENTS.md` in this package holds the rules for an assistant writing a page: the project, the calls
266
+ and the page. Copy it to the top of your project, where an assistant looks for it, or paste it into the
267
+ prompt along with what the page should do. `GUIDE.md` says how to set the project up.
268
+
269
+ ## For maintainers
270
+
271
+ This library lives in the DoU app's repository so it cannot drift from the app: its public types are
272
+ pinned to the app's message definitions by a type-level test, and a contract test in the app runs this
273
+ client against the app's real page host. The protocol it speaks is specified in
274
+ [sub-webview-protocol.md](https://github.com/lemoncloud-io/dou-app/blob/develop/apps/mobile/docs/webview/sub-webview-protocol.md).
275
+
276
+ ```bash
277
+ npx jest --config libs/chatic-apps-sdk/jest.config.js
278
+ npx tsc -b libs/chatic-apps-sdk/tsconfig.json
279
+ npx nx build @chatic/chatic-apps-sdk # dist/libs/chatic-apps-sdk, ready to publish
280
+ ```
281
+
282
+ The build writes `package.publish.json` as the published `package.json` (`publishConfig.access` is
283
+ `public`, so a scoped package is never published private by mistake). Publish from the build output:
284
+
285
+ ```bash
286
+ cd dist/libs/chatic-apps-sdk && npm publish --dry-run
287
+ ```
@@ -0,0 +1 @@
1
+ var ChaticAppsSDK=(function(y){"use strict";class u extends Error{code;constructor(t,r){super(r),this.name="ChaticAppsError",this.code=t}}const R="2.20.0",U=1e4,W=2e3;let q=0;const x=()=>`cas-${Date.now().toString(36)}-${(++q).toString(36)}`,P=()=>typeof document<"u"&&document.visibilityState==="hidden",G=(e,t=U)=>{const r=new Map,o=new Map;let c=!1;const h=(a,s)=>{s.remaining===null||P()||(s.startedAt=Date.now(),s.timer=setTimeout(()=>{r.delete(a),s.reject(new u("TIMEOUT","The app did not answer in time."))},s.remaining))},d=()=>{for(const[a,s]of r)s.remaining!==null&&(P()?(s.timer&&clearTimeout(s.timer),s.timer=null,s.remaining=Math.max(0,s.remaining-(Date.now()-s.startedAt))):s.timer||(s.remaining=Math.max(s.remaining,W),h(a,s)))};typeof document<"u"&&document.addEventListener("visibilitychange",d);const f=e.listen(a=>{let s;try{s=JSON.parse(a)}catch{return}if(!s||typeof s!="object"||typeof s.type!="string")return;const p=typeof s.refId=="string"?r.get(s.refId):void 0;if(p&&typeof s.refId=="string"){if(r.delete(s.refId),p.timer&&clearTimeout(p.timer),s.success===!0)p.resolve(s.data);else{const g=typeof s.error?.code=="string"?s.error.code:"INTERNAL_ERROR",v=typeof s.error?.message=="string"?s.error.message:g;p.reject(new u(g,v))}return}o.get(s.type)?.forEach(g=>{try{g(s.data)}catch{}})});return{request:(a,s={},p={})=>new Promise((g,v)=>{if(c){v(new u("DISCONNECTED","The connection to the app was closed."));return}const w=x(),n=p.timeoutMs===void 0?t:p.timeoutMs,i={resolve:g,reject:v,remaining:n,startedAt:Date.now(),timer:null};r.set(w,i),h(w,i),e.send(JSON.stringify({type:a,data:s,refId:w,version:R}))}),onPush:(a,s)=>{let p=o.get(a);return p||o.set(a,p=new Set),p.add(s),()=>p?.delete(s)},close:()=>{if(!c){c=!0,f(),typeof document<"u"&&document.removeEventListener("visibilitychange",d);for(const a of r.values())a.timer&&clearTimeout(a.timer),a.reject(new u("DISCONNECTED","The connection to the app was closed."));r.clear(),o.clear()}}}},T=e=>{try{return JSON.stringify(e)??null}catch{return null}},L=e=>{const t=r=>Object.values(r??{}).every(o=>T(o)!==null)?e.set(r).then(()=>{}):Promise.reject(new u("INVALID","Values must be JSON; remove a key rather than storing undefined."));return{get:r=>e.get([r]).then(o=>o.entries[r]),getMany:r=>e.get(r).then(o=>o.entries),set:(r,o)=>t({[r]:o}),setMany:t,remove:r=>e.remove(typeof r=="string"?[r]:r).then(()=>{}),keys:()=>e.info().then(r=>r.keys),clear:()=>e.clear().then(()=>{}),usage:()=>e.info().then(({used:r,limit:o})=>({used:r,limit:o}))}},k=1024*1024,$=200,K=64*1024,A=e=>typeof e=="string"&&e.length>=1&&e.length<=$&&e!=="__proto__",B=e=>{const t=()=>e.keys().reduce((o,c)=>o+c.length+(e.read(c)?.length??0),0),r=()=>({used:t(),limit:k});return{get(o){if(!Array.isArray(o)||!o.every(A))return{ok:!1,code:"INVALID"};const c={};for(const h of o){const d=e.read(h);if(d!==void 0)try{c[h]=JSON.parse(d)}catch{}}return{ok:!0,value:{entries:c}}},set(o){if(!o||typeof o!="object"||Array.isArray(o))return{ok:!1,code:"INVALID"};const c=[];let h=t();for(const[d,f]of Object.entries(o)){const a=T(f);if(!A(d)||a===null)return{ok:!1,code:"INVALID"};const s=e.read(d);h+=a.length-(s===void 0?-d.length:s.length),c.push([d,a])}return h>k?{ok:!1,code:"QUOTA_EXCEEDED"}:(c.forEach(([d,f])=>e.write(d,f)),{ok:!0,value:r()})},remove(o){return!Array.isArray(o)||!o.every(A)?{ok:!1,code:"INVALID"}:(o.forEach(c=>e.delete(c)),{ok:!0,value:r()})},clear(){return e.keys().forEach(o=>e.delete(o)),{ok:!0,value:{}}},info(){return{ok:!0,value:{keys:e.keys(),...r()}}}}},S="chatic-apps.storage:",F=e=>({read:t=>e.getItem(S+t)??void 0,write:(t,r)=>e.setItem(S+t,r),delete:t=>e.removeItem(S+t),keys:()=>{const t=[];for(let r=0;r<e.length;r++){const o=e.key(r);o?.startsWith(S)&&t.push(o.slice(S.length))}return t}}),J=()=>{const e=t=>{let r;try{r=t(B(F(window.localStorage)))}catch(o){return o?.name==="QuotaExceededError"?Promise.reject(new u("QUOTA_EXCEEDED","The browser's own storage is full.")):Promise.reject(new u("NOT_SUPPORTED","This browser refuses local storage."))}return r.ok?Promise.resolve(r.value):Promise.reject(new u(r.code,`The storage refused the call: ${r.code}.`))};return L({get:t=>e(r=>r.get(t)),set:t=>(T({entries:t})?.length??0)>K?Promise.reject(new u("TOO_LARGE","One call carries at most 65,536 characters.")):e(r=>r.set(t)),remove:t=>e(r=>r.remove(t)),clear:()=>e(t=>t.clear()),info:()=>e(t=>t.info())})},N=()=>typeof window<"u"&&!!window.ReactNativeWebView,Q=()=>({send:e=>window.ReactNativeWebView?.postMessage(e),listen:e=>{const t=r=>{const o=r.data;typeof o=="string"&&e(o)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),E={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage",permissions:"RequestSubWebViewPermission"},V=1,H=1e3,X=4e3,C=()=>typeof window<"u"&&window.ChaticSubWebView||null,z=()=>new Promise(e=>{if(typeof document>"u"||document.readyState==="complete"){e(C());return}window.addEventListener("load",()=>e(C()),{once:!0})}),Y=e=>{let t,r;try{e instanceof Error?(t=e.message||e.name,r=typeof e.stack=="string"?e.stack:void 0):typeof e=="string"?t=e:t=`A non-Error value was thrown: ${Object.prototype.toString.call(e)}`}catch{t="An error that could not be read was thrown"}return{message:(t||"Unknown error").slice(0,H),...r?{stack:r.slice(0,X)}:{}}},O=e=>new u("NOT_SUPPORTED",`${e} is not available here: an older app, or not granted.`),I=e=>Promise.reject(new u("NOT_IN_APP",`${e} needs the app; this page is in a browser.`)),_=(e={})=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new u("INVALID","link() takes an object of query params, such as { level: 3 }.");const t=new URLSearchParams;for(const[o,c]of Object.entries(e))t.append(o,String(c));const r=t.toString();return r?`?${r}`:""},D=e=>typeof location>"u"?`/${e}`:`${location.origin}/${e}`;let b=null;const Z=(e={})=>(b||(b=(N()?ee(Q(),e):Promise.resolve(oe())).catch(t=>{throw b=null,t})),b),ee=async(e,t={})=>{const r=G(e,t.timeoutMs);try{const o=await M(r,!0);return te(r,o,t)}catch(o){throw r.close(),o}},M=async(e,t)=>{const r=await e.request("WebAppReady",{}),o=r.subWebView??(t?await z():null);if(o&&o.protocolVersion!==V)throw new u("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(o.protocolVersion)}; this library speaks ${V}.`);return{supported:new Set(Array.isArray(r.supportedWebMessages)?r.supportedWebMessages:[]),context:o}},te=(e,t,r)=>{let o=null,c=null;const h=new Set,d=[],f=n=>t.supported.has(E[n]),a=(n,i,l,m)=>{const j=m??E[n];return t.supported.has(j)?e.request(j,i,l===void 0?{}:{timeoutMs:l}):Promise.reject(O(n))},s=(n,i)=>f("storage")?e.request(n,i):Promise.reject(O("storage")),p=n=>h.forEach(i=>{try{i(n)}catch(l){w.reportError(l)}}),g=()=>{f("back")&&e.request(E.back,{canGoBack:!!o}).catch(()=>{}),f("closeGuard")&&e.request(E.closeGuard,{enabled:!!c}).catch(()=>{})},v=n=>{if(!n.persisted){g();return}M(e,!1).then(i=>{const l=t.context;t.supported=i.supported,i.context&&(t.context=i.context),g();const m=t.context;m&&(m.theme!==l?.theme||m.locale!==l?.locale)&&p(m)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",v),d.push(()=>window.removeEventListener("pageshow",v))),d.push(e.onPush("OnBackPressed",()=>{try{o?.()}catch(n){w.reportError(n)}})),d.push(e.onPush("OnSubWebViewCloseRequested",n=>{const i=c;if(!i)return;const l=n?.trigger??"control";Promise.resolve().then(()=>i(l)).then(m=>m?w.finish():void 0).catch(m=>w.reportError(m))})),d.push(e.onPush("OnSubWebViewContextChanged",n=>{t.context&&(t.context={...t.context,...n},p(t.context))}));const w={inApp:!0,get context(){return t.context},supports:f,finish:n=>a("finish",n===void 0?{}:{result:n}).then(()=>{}),setTitle:n=>a("title",{title:n}).then(()=>{}),haptic:n=>{f("haptic")&&e.request(E.haptic,{kind:n}).catch(()=>{})},copy:n=>a("clipboard",{text:n}).then(()=>{}),openUrl:n=>a("openUrl",{url:n}).then(()=>{}),share:n=>a("share",n,null).then(i=>i?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>a("userKey").then(n=>n.key),permissions:{query:n=>a("permissions",{kind:n},void 0,"GetSubWebViewPermission").then(i=>i.state),request:n=>a("permissions",{kind:n},null).then(i=>i.state)},openSettings:()=>a("permissions",{},void 0,"OpenSettings").then(()=>{}),reportError:n=>f("errorReport")?e.request(E.errorReport,Y(n)).then(i=>!!i?.recorded).catch(()=>!1):Promise.resolve(!1),storage:L({get:n=>s("GetSubWebViewStorage",{keys:n}),set:n=>s("SetSubWebViewStorage",{entries:n}),remove:n=>s("RemoveSubWebViewStorage",{keys:n}),clear:()=>s("ClearSubWebViewStorage",{}),info:()=>s("GetSubWebViewStorageInfo",{})}),onBack:n=>{o=n,g()},onCloseRequest:n=>{c=n,g()},onContextChange:n=>(h.add(n),()=>h.delete(n)),link:n=>{const i=_(n),l=t.context?.appLink;return l?`${l}${i}`:D(i)},disconnect:()=>{d.forEach(n=>n()),e.close(),b=null}};if(r.reportErrors!==!1&&typeof window<"u"){const n=l=>{w.reportError(l.error??l.message)},i=l=>{w.reportError(l.reason)};window.addEventListener("error",n),window.addEventListener("unhandledrejection",i),d.push(()=>{window.removeEventListener("error",n),window.removeEventListener("unhandledrejection",i)})}return w},re=()=>{const e=async t=>{try{const r=await navigator.permissions.query({name:t});return r.state==="granted"?"granted":r.state==="denied"?"blocked":"prompt"}catch{return"prompt"}};return{query:e,request:async t=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new u("NOT_SUPPORTED",`This browser cannot capture the ${t}.`);try{return(await navigator.mediaDevices.getUserMedia(t==="camera"?{video:!0}:{audio:!0})).getTracks().forEach(o=>o.stop()),"granted"}catch(r){const o=r?.name;if(o==="NotFoundError"||o==="OverconstrainedError")throw new u("UNAVAILABLE",`This device has no ${t}.`);if(o==="NotReadableError"||o==="SecurityError"||o==="TypeError"||o==="AbortError")throw new u("INTERNAL_ERROR",`The ${t} could not be used: ${o}.`);return await e(t)==="blocked"?"blocked":"prompt"}}}},oe=()=>{const e=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(O("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>I("Finishing the view"),setTitle:async t=>{typeof document<"u"&&(document.title=t)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:e,openUrl:async t=>{typeof window<"u"&&window.open(t,"_blank","noopener,noreferrer")},share:async t=>{const r=[t.message,t.url].filter(Boolean).join(" ");if(!r)throw new u("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(t),"shared"}catch(o){if(o?.name==="AbortError")return"dismissed"}return await e(r),"copied"},getUserKey:()=>I("A user key"),permissions:re(),openSettings:()=>I("Opening the settings"),reportError:async t=>(console.error(t),!1),storage:J(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>D(_(t)),disconnect:()=>{b=null}}};return y.ChaticAppsError=u,y.SDK_BRIDGE_VERSION=R,y.connect=Z,y.isInApp=N,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
package/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./storage-yeS4HWKZ.cjs"),O="2.20.0",V=1e4,N=2e3;let x=0;const q=()=>`cas-${Date.now().toString(36)}-${(++x).toString(36)}`,T=()=>typeof document<"u"&&document.visibilityState==="hidden",W=(r,t=V)=>{const n=new Map,s=new Map;let f=!1;const v=(a,o)=>{o.remaining===null||T()||(o.startedAt=Date.now(),o.timer=setTimeout(()=>{n.delete(a),o.reject(new p.ChaticAppsError("TIMEOUT","The app did not answer in time."))},o.remaining))},w=()=>{for(const[a,o]of n)o.remaining!==null&&(T()?(o.timer&&clearTimeout(o.timer),o.timer=null,o.remaining=Math.max(0,o.remaining-(Date.now()-o.startedAt))):o.timer||(o.remaining=Math.max(o.remaining,N),v(a,o)))};typeof document<"u"&&document.addEventListener("visibilitychange",w);const g=r.listen(a=>{let o;try{o=JSON.parse(a)}catch{return}if(!o||typeof o!="object"||typeof o.type!="string")return;const d=typeof o.refId=="string"?n.get(o.refId):void 0;if(d&&typeof o.refId=="string"){if(n.delete(o.refId),d.timer&&clearTimeout(d.timer),o.success===!0)d.resolve(o.data);else{const u=typeof o.error?.code=="string"?o.error.code:"INTERNAL_ERROR",m=typeof o.error?.message=="string"?o.error.message:u;d.reject(new p.ChaticAppsError(u,m))}return}s.get(o.type)?.forEach(u=>{try{u(o.data)}catch{}})});return{request:(a,o={},d={})=>new Promise((u,m)=>{if(f){m(new p.ChaticAppsError("DISCONNECTED","The connection to the app was closed."));return}const l=q(),e=d.timeoutMs===void 0?t:d.timeoutMs,i={resolve:u,reject:m,remaining:e,startedAt:Date.now(),timer:null};n.set(l,i),v(l,i),r.send(JSON.stringify({type:a,data:o,refId:l,version:O}))}),onPush:(a,o)=>{let d=s.get(a);return d||s.set(a,d=new Set),d.add(o),()=>d?.delete(o)},close:()=>{if(!f){f=!0,g(),typeof document<"u"&&document.removeEventListener("visibilitychange",w);for(const a of n.values())a.timer&&clearTimeout(a.timer),a.reject(new p.ChaticAppsError("DISCONNECTED","The connection to the app was closed."));n.clear(),s.clear()}}}},I=()=>typeof window<"u"&&!!window.ReactNativeWebView,U=()=>({send:r=>window.ReactNativeWebView?.postMessage(r),listen:r=>{const t=n=>{const s=n.data;typeof s=="string"&&r(s)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),b={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage",permissions:"RequestSubWebViewPermission"},R=1,M=1e3,_=4e3,C=()=>typeof window<"u"&&window.ChaticSubWebView||null,D=()=>new Promise(r=>{if(typeof document>"u"||document.readyState==="complete"){r(C());return}window.addEventListener("load",()=>r(C()),{once:!0})}),$=r=>{let t,n;try{r instanceof Error?(t=r.message||r.name,n=typeof r.stack=="string"?r.stack:void 0):typeof r=="string"?t=r:t=`A non-Error value was thrown: ${Object.prototype.toString.call(r)}`}catch{t="An error that could not be read was thrown"}return{message:(t||"Unknown error").slice(0,M),...n?{stack:n.slice(0,_)}:{}}},S=r=>new p.ChaticAppsError("NOT_SUPPORTED",`${r} is not available here: an older app, or not granted.`),y=r=>Promise.reject(new p.ChaticAppsError("NOT_IN_APP",`${r} needs the app; this page is in a browser.`)),P=(r={})=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new p.ChaticAppsError("INVALID","link() takes an object of query params, such as { level: 3 }.");const t=new URLSearchParams;for(const[s,f]of Object.entries(r))t.append(s,String(f));const n=t.toString();return n?`?${n}`:""},L=r=>typeof location>"u"?`/${r}`:`${location.origin}/${r}`;let E=null;const j=(r={})=>(E||(E=(I()?G(U(),r):Promise.resolve(F())).catch(t=>{throw E=null,t})),E),G=async(r,t={})=>{const n=W(r,t.timeoutMs);try{const s=await k(n,!0);return B(n,s,t)}catch(s){throw n.close(),s}},k=async(r,t)=>{const n=await r.request("WebAppReady",{}),s=n.subWebView??(t?await D():null);if(s&&s.protocolVersion!==R)throw new p.ChaticAppsError("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(s.protocolVersion)}; this library speaks ${R}.`);return{supported:new Set(Array.isArray(n.supportedWebMessages)?n.supportedWebMessages:[]),context:s}},B=(r,t,n)=>{let s=null,f=null;const v=new Set,w=[],g=e=>t.supported.has(b[e]),a=(e,i,c,h)=>{const A=h??b[e];return t.supported.has(A)?r.request(A,i,c===void 0?{}:{timeoutMs:c}):Promise.reject(S(e))},o=(e,i)=>g("storage")?r.request(e,i):Promise.reject(S("storage")),d=e=>v.forEach(i=>{try{i(e)}catch(c){l.reportError(c)}}),u=()=>{g("back")&&r.request(b.back,{canGoBack:!!s}).catch(()=>{}),g("closeGuard")&&r.request(b.closeGuard,{enabled:!!f}).catch(()=>{})},m=e=>{if(!e.persisted){u();return}k(r,!1).then(i=>{const c=t.context;t.supported=i.supported,i.context&&(t.context=i.context),u();const h=t.context;h&&(h.theme!==c?.theme||h.locale!==c?.locale)&&d(h)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",m),w.push(()=>window.removeEventListener("pageshow",m))),w.push(r.onPush("OnBackPressed",()=>{try{s?.()}catch(e){l.reportError(e)}})),w.push(r.onPush("OnSubWebViewCloseRequested",e=>{const i=f;if(!i)return;const c=e?.trigger??"control";Promise.resolve().then(()=>i(c)).then(h=>h?l.finish():void 0).catch(h=>l.reportError(h))})),w.push(r.onPush("OnSubWebViewContextChanged",e=>{t.context&&(t.context={...t.context,...e},d(t.context))}));const l={inApp:!0,get context(){return t.context},supports:g,finish:e=>a("finish",e===void 0?{}:{result:e}).then(()=>{}),setTitle:e=>a("title",{title:e}).then(()=>{}),haptic:e=>{g("haptic")&&r.request(b.haptic,{kind:e}).catch(()=>{})},copy:e=>a("clipboard",{text:e}).then(()=>{}),openUrl:e=>a("openUrl",{url:e}).then(()=>{}),share:e=>a("share",e,null).then(i=>i?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>a("userKey").then(e=>e.key),permissions:{query:e=>a("permissions",{kind:e},void 0,"GetSubWebViewPermission").then(i=>i.state),request:e=>a("permissions",{kind:e},null).then(i=>i.state)},openSettings:()=>a("permissions",{},void 0,"OpenSettings").then(()=>{}),reportError:e=>g("errorReport")?r.request(b.errorReport,$(e)).then(i=>!!i?.recorded).catch(()=>!1):Promise.resolve(!1),storage:p.storageOver({get:e=>o("GetSubWebViewStorage",{keys:e}),set:e=>o("SetSubWebViewStorage",{entries:e}),remove:e=>o("RemoveSubWebViewStorage",{keys:e}),clear:()=>o("ClearSubWebViewStorage",{}),info:()=>o("GetSubWebViewStorageInfo",{})}),onBack:e=>{s=e,u()},onCloseRequest:e=>{f=e,u()},onContextChange:e=>(v.add(e),()=>v.delete(e)),link:e=>{const i=P(e),c=t.context?.appLink;return c?`${c}${i}`:L(i)},disconnect:()=>{w.forEach(e=>e()),r.close(),E=null}};if(n.reportErrors!==!1&&typeof window<"u"){const e=c=>{l.reportError(c.error??c.message)},i=c=>{l.reportError(c.reason)};window.addEventListener("error",e),window.addEventListener("unhandledrejection",i),w.push(()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",i)})}return l},K=()=>{const r=async t=>{try{const n=await navigator.permissions.query({name:t});return n.state==="granted"?"granted":n.state==="denied"?"blocked":"prompt"}catch{return"prompt"}};return{query:r,request:async t=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new p.ChaticAppsError("NOT_SUPPORTED",`This browser cannot capture the ${t}.`);try{return(await navigator.mediaDevices.getUserMedia(t==="camera"?{video:!0}:{audio:!0})).getTracks().forEach(s=>s.stop()),"granted"}catch(n){const s=n?.name;if(s==="NotFoundError"||s==="OverconstrainedError")throw new p.ChaticAppsError("UNAVAILABLE",`This device has no ${t}.`);if(s==="NotReadableError"||s==="SecurityError"||s==="TypeError"||s==="AbortError")throw new p.ChaticAppsError("INTERNAL_ERROR",`The ${t} could not be used: ${s}.`);return await r(t)==="blocked"?"blocked":"prompt"}}}},F=()=>{const r=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(S("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>y("Finishing the view"),setTitle:async t=>{typeof document<"u"&&(document.title=t)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:r,openUrl:async t=>{typeof window<"u"&&window.open(t,"_blank","noopener,noreferrer")},share:async t=>{const n=[t.message,t.url].filter(Boolean).join(" ");if(!n)throw new p.ChaticAppsError("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(t),"shared"}catch(s){if(s?.name==="AbortError")return"dismissed"}return await r(n),"copied"},getUserKey:()=>y("A user key"),permissions:K(),openSettings:()=>y("Opening the settings"),reportError:async t=>(console.error(t),!1),storage:p.browserStorage(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>L(P(t)),disconnect:()=>{E=null}}};exports.ChaticAppsError=p.ChaticAppsError;exports.SDK_BRIDGE_VERSION=O;exports.connect=j;exports.isInApp=I;