Compare commits

..
Author SHA1 Message Date
Nariman Jelveh 9675ddee7b Remove the embeddable toolbar, keeping the standalone app browser
Drop /embed/toolbar, its page and host helper, their styles, strings and
tests, and the dashboard's ?upgrade=1 deep link that only the toolbar's
Upgrade button used. /embed/apps no longer allows the GUI origin to frame
it with a wildcard over deployment subdomains, which existed only for the
toolbar's nested app browser, and its bootstrap config no longer carries
the domain the toolbar read.
2026-11-05 17:11:31 -07:00
Nariman Jelveh 6330a069be Restore the license header on the new embed and toolbar files
TabApps.js lost its AGPL header when its code moved to AppBrowser.js,
and the new embed, toolbar, and host-helper modules were added without
one; every other GUI source file carries it.
2026-11-05 16:54:42 -07:00
Nariman Jelveh 3869ab646d Point comments at AppBrowser.js, where the Apps tab code now lives
The constants and methods these comments name moved out of TabApps.js
when the app browser became shared.
2026-11-05 16:54:09 -07:00
Nariman Jelveh 23afd07db8 Reuse isOrgSeat for the toolbar's Upgrade check
The toolbar re-implemented the dashboard's organization-seat test
inline. Use the shared helper so both surfaces agree on who sees an
upgrade offer.
2026-11-05 16:53:51 -07:00
Nariman Jelveh 01c1b45cd0 Keep the toolbar's slot following the host layout while a menu is open
The helper reserved the toolbar's space with a span frozen at the
frame's resolved size and margins, so a host that right-aligns it with
margin-left: auto (or sizes it in percentages or media queries) left the
open menu anchored to a stale spot, overflowing the header, after a
resize or rotation. Reserve it with an empty clone of the frame instead,
which the page's own rules keep laying out; if they target
data-puter-toolbar, which the clone drops so hosts still find one frame,
hold the frame's measured size.
2026-11-05 16:53:41 -07:00
Nariman Jelveh df1d017958 Let the toolbar sign out of a session that already ended
When the session was ended elsewhere (revoked, or signed out in another
tab), the anti-CSRF and logout requests answer 401 and sign-out failed
on every retry, stranding the stale token. Treat 401 as already signed
out and finish clearing it locally, as the desktop does; other failures
still keep the session and show the error.
2026-11-05 16:51:08 -07:00
Nariman Jelveh faea082180 Keep the toolbar's apps icon legible on hosts in the other theme
The toolbar follows the OS theme but draws on the host page, so in dark
mode on a light host its icon was #d4d4d4 on white (and the reverse on a
dark host). Give the apps toggle a surface of its own, like the avatar
beside it, and the session-unavailable notice one too.
2026-11-05 16:49:57 -07:00
Nariman Jelveh efd5098125 Keep the toolbar's Upgrade button legible in dark mode
Upgrade was filled with the link color, which dark mode lightens to
#6b8cff: 3.1:1 under white text. Use the dashboard's primary-button fill
(4.6:1 in both themes) and its hover color, and drop the button classes
nothing styles on this page.
2026-11-05 16:48:59 -07:00
Nariman Jelveh b2646930b3 Merge origin/main into feat/embedded-puter-toolbar
Port main's dashboard Apps tab changes into the shared AppBrowser and the
i18n replacement fix into i18nCore. Use main's app browser strings in place
of the duplicate app_browser_* keys.
2026-11-05 16:25:22 -07:00
jelveh 3b3c3750b0 Drop the dashboard's hamburger clearance from the embedded app browser
At narrow widths the dashboard pads the search 60px down to clear its fixed
menu button. The embeds have no such button, so the toolbar's app panel
lost 90px of a ~500px frame to empty space above the search.
2026-10-01 22:29:15 -07:00
jelveh 26f7e8eb2e Use the dashboard danger color for the toolbar sign-out confirmation
The hardcoded red had 3:1 contrast on the dark panel, below WCAG AA for
14px text. The dashboard's danger token is 4.8:1 in light and 6:1 in dark.
2026-10-01 22:27:13 -07:00
jelveh 62ce691ac9 Stop user-hosted sites from framing the toolbar and app browser embeds
frame-ancestors allowed every *.<domain> subdomain, which on the default
self-hosted layout includes user sites (*.site.<domain>) and private apps
(*.app.<domain>), letting any hosted page clickjack sign-out and account
switching. The policy now names the embedding page exactly, from the
request's referrer, and refuses the user-content hosting domains.
2026-10-01 22:26:03 -07:00
jelveh 654cee36c3 Omit the empty email line in the toolbar account menu
Temporary accounts and saved accounts without an email rendered an empty
element, adding a stray gap under the username.
2026-10-01 22:21:09 -07:00
jelveh c328283fa7 Close toolbar menus when the empty part of the expanded frame is pressed
While a menu is open the toolbar frame covers host content beside the
buttons; presses there reached neither the host nor the toolbar's outside
click handling, so the menu stayed open. They now close it.
2026-10-01 22:19:45 -07:00
jelveh fa6e76254b Don't pull focus back into the toolbar when the host page closes its menu
Clicking a host text field while a toolbar menu was open closed the menu and
then refocused the toolbar button, so the host field lost focus and typing
went nowhere. Focus is now restored only while the toolbar document has it.
2026-10-01 22:19:44 -07:00
jelveh ed32c212d3 Keep toolbar buttons in place when a menu opens near the viewport edge
On phones the expanded frame was clamped to an 8px viewport margin, which
moved the whole toolbar row (by the header padding minus 8px) under the
user's finger. The frame now shrinks to fit beside and below the collapsed
toolbar, and only falls back to shifting when there isn't enough room.
2026-10-01 22:17:18 -07:00
jelveh a338c8db46 Load only the preferred language in the toolbar and app browser embeds
Importing i18n.js pulled every translation into each embed, making the
toolbar bundle 1.1 MB. The embeds now bundle English and fetch the user's
language on demand (toolbar 1.12 MB -> 179 KB, app browser 1.18 MB -> 237 KB).
The desktop bundle keeps all translations.
2026-10-01 22:06:12 -07:00
jelveh ffa6b176d0 Stop double-encoding translated toolbar labels
i18n() already HTML-encodes its result, so wrapping it in escape() again
turned accented labels into literal entities (e.g. "Schlie&szlig;en") for
screen readers, and .text() did the same for the error message.
2026-10-01 22:03:03 -07:00
jelveh f1008559ca Prevent embedded toolbar from scrolling when menus open 2026-10-01 21:48:27 -07:00
jelveh 4ee1360779 Add embeddable Puter toolbar and shared app browser
Provide deployment-scoped iframe routes, a responsive host helper, read-only app browsing, saved-account switching, and new-tab account and upgrade links. Validate account sessions before switching and keep credentials inside the GUI origin.

Verified with 182 targeted tests, production GUI build, backend type checking, lint, and a real-backend browser smoke test. Translation checker could not run because tools/check-translations.js is missing.
2026-10-01 21:30:51 -07:00
382 changed files with 6329 additions and 23073 deletions

No files matched your search

@@ -53,7 +53,7 @@ jobs:
# step above fails; the tests skip themselves without the key.
- name: Run live realtime conversation tests
if: ${{ !cancelled() }}
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/realtimeLive.test.ts
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/convoLive.test.ts
env:
CI: 'true'
PUTER_TEST_AI_OPENAI_API_KEY: ${{ secrets.PUTER_TEST_AI_OPENAI_API_KEY }}
+2 -6
View File
@@ -176,10 +176,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v7
# Missing when the PR leg failed; `coverage (pr)` already reports that.
- name: Download PR coverage
id: pr-coverage
continue-on-error: true
uses: actions/download-artifact@v8
with:
name: puterjs-coverage-pr
@@ -189,7 +186,6 @@ jobs:
# base run) — then report without the comparison column.
- name: Download base coverage
id: base-coverage
if: steps.pr-coverage.outcome == 'success'
continue-on-error: true
uses: actions/download-artifact@v8
with:
@@ -197,7 +193,7 @@ jobs:
path: coverage-base
- name: Report coverage on PR
if: steps.pr-coverage.outcome == 'success' && steps.base-coverage.outcome == 'success'
if: steps.base-coverage.outcome == 'success'
uses: davelosert/vitest-coverage-report-action@v2
with:
name: puter.js SDK
@@ -206,7 +202,7 @@ jobs:
json-summary-compare-path: coverage-base/coverage-summary.json
- name: Report coverage on PR (no base comparison)
if: steps.pr-coverage.outcome == 'success' && steps.base-coverage.outcome != 'success'
if: steps.base-coverage.outcome != 'success'
uses: davelosert/vitest-coverage-report-action@v2
with:
name: puter.js SDK
+1 -4
View File
@@ -159,9 +159,7 @@ The reference has two kinds of page:
An overview page answers "what is this API and is it what I need?", and a function page answers "how exactly does this call behave?". A change to one function usually only touches that function's page, so a new `kv.list()` option goes in `KV/list.md` without a matching update to `KV.md`. Don't copy a function's options, limits, or edge cases onto the overview page for completeness. Where a detail goes is a judgment call, not a hard rule: update the overview when a change affects how someone would describe the API as a whole.
When you add a page, add it to [src/docs/src/sidebar.js](src/docs/src/sidebar.js) under its area, or it won't show up in the navigation.
**Sidebar order.** Order the API areas in the sidebar by how often developers use them, most common first. Overview stays first and Objects stays last. Inside an area, order the pages by use too, and keep pages that make up one feature next to each other, such as `share()`, `unshare()`, `listShared()`, and `listSharedByMe()`. A group goes where its most-used page would go. A helper that only supports another function, such as `listModels()` for `chat()`, goes by its own use. Put create, list, get, update, and delete in that order, and constants such as `MAX_KEY_SIZE` last. The function list on the area's overview page uses the sidebar's order. When you add a runnable example, add its HTML to `src/docs/src/playground/examples/<slug>.html`, register the slug in [src/docs/src/examples.js](src/docs/src/examples.js), and link the code block to it by putting the slug after the language with a semicolon (` ```html;kv-set `).
When you add a page, add it to [src/docs/src/sidebar.js](src/docs/src/sidebar.js) under its area, or it won't show up in the navigation. When you add a runnable example, add its HTML to `src/docs/src/playground/examples/<slug>.html`, register the slug in [src/docs/src/examples.js](src/docs/src/examples.js), and link the code block to it by putting the slug after the language with a semicolon (` ```html;kv-set `).
### Function page layout
@@ -202,7 +200,6 @@ These apply to reference pages and recipes alike.
- **Describe behavior directly.** No quoted inner-voice phrases. Write "`isNew` is `true` when the person did not have access before", not "this tells 'I just gave this to someone' from 'they already had it'".
- **Keep references easy to follow.** Name what a list or code block belongs to in the sentence directly above it. Name a thing once and keep that name. Introduce an actor as "a user" before giving them a role: "A user can create a team. The user who creates the team becomes its owner."
- **Sentence mechanics.** Never start a sentence with inline code: write "To store data, use the [`set()`](/KV/set/) method." Link every inline mention of an API to its page, every time. No em dashes, and no colons or semicolons mid-sentence; a colon that introduces a code block is fine.
- **No `##` or `###` headings inside tabs.** The table of contents lists every `##` and `###` heading on the page, including the ones in a hidden tab (an `example-content` block switched by the `example-group` pills), so its links lead to content the reader can't see. Put the heading above the tabs, or use `####` inside a tab, which the table of contents skips.
- **Show the correct way.** No "don't" and no wrong-way-first examples, in recipes and playground examples alike. Mention a wrong approach only when developers already hit it in practice, and state how it fails as a fact: "`add()` reads a plain object as a path map, so the call rejects with …".
### Recipes
+1 -1
View File
@@ -1 +1 @@
FOLLOW @AGENTS.md
FOLLOW ./AGENTS.md
+28 -237
View File
@@ -6,58 +6,25 @@ as the dashboard's Apps tab, without the desktop or dashboard navigation.
It supports search, paging, saved folders, and saved ordering. It uses the same
installed-app and recommendation data as the dashboard, including the user's
removed recommendations. Editing, adding, reordering, renaming, and uninstalling
are disabled. Selecting an app opens it in a new browser tab at its own URL, the
same way the dashboard does, and the host page stays open. The app's token isn't
put in the URL: the app's SDK asks the embed for it once the tab loads, so the
embed must still be open then. If the iframe is removed first, the app falls back
to its normal sign-in. Apps that need the desktop (built-in and godmode apps,
private apps the user can't open, or a failed token request) open `/app/<name>`
on the GUI origin, cut off from the embed. Website shortcuts open their external
destination with no opener.
The embed follows the OS's light or dark setting. A host with a fixed theme adds
`theme=dark` or `theme=light` to the fragment (`#user=<uuid>&theme=dark`), since
Chromium doesn't pass an iframe's `color-scheme` on to the page inside it.
Apps opened from the embed carry `utm_source=puter.com&utm_medium=referral&utm_campaign=app_browser_embed`;
the desktop and dashboard send `utm_campaign=desktop` and `utm_campaign=dashboard`.
are disabled. Selecting an app opens a new browser tab with no opener; the host
page stays open. Normal apps use `/app/<name>` on the GUI origin, and website
shortcuts use their external destination.
## Session and framing
The embed shows the GUI session only to the user the host page is signed in as.
The host names that user's `uuid` (from `puter.auth.getUser()`) in the iframe
URL's fragment, as `/embed/apps#user=<uuid>`. The embed reads the session, asks
`/whoami` which user it belongs to, and shows the signed-out view unless the two
match. So a host that names no user, a malformed one, or a user other than the
session's, gets the signed-out view, and so does a session the API refuses. A
failed `/whoami` check shows the error state. The fragment never reaches the
server and can only narrow what the embed shows: naming the session's own user
gives the same view as a direct visit to the GUI. Changing the fragment of a
loaded embed reloads it.
The embed reads the existing GUI session from local storage on its own origin.
If that storage holds no session, the embed gets the session from the GUI origin's session cookie through
`/get-gui-token`. This matters in Safari, which gives a framed origin separate
local storage under each top-level origin, so even a sibling subdomain's iframe
can't see the GUI's stored token. The session cookie is still sent, because the
host is on the same site. The embed doesn't write that token back to storage. It
does not create accounts, show a login dialog, or accept a token from its parent.
Being signed in on a subdomain alone does not create a session on the main GUI
origin.
Without a session it can show, the embed shows the recommended apps (`RecommendedAppsService`)
that the server put in the page, and nothing else: no installed apps, folders, or
saved order, and no puter.js. Selecting one opens it at the same URL a signed-in
launch uses, with no opener and no token on offer, so the app signs in on its own.
Apps that need the desktop open `/app/<name>`. If the page carries no recommended
apps, or a load fails, the embed displays an unavailable/error state.
Only show the iframe after the user has signed in. The embed reads the existing
GUI session from local storage on its own origin. It does not create accounts,
show a login dialog, or accept a token from its parent. A missing session or
failed load displays an unavailable/error state. Being signed in on a subdomain
alone does not populate the main GUI origin's storage; the main GUI session must
already exist.
The route's `Content-Security-Policy: frame-ancestors` allows the GUI origin and
the embedding page's origin when it is exactly one label under `config.domain`
with the scheme and port from `config.origin`. Subdomains the server answers
itself (`api`, `dav`, `js`, `www`, the native-app hosts, and the host of
`api_base_url`) and the user-content hosting domains (`static_hosting_domain`,
`private_app_hosting_domain`, and their `_alt` variants) are refused. For
example, `https://puter.com` permits `https://spreadsheet.puter.com` but not
`https://api.puter.com`, and `http://puter.localhost:4100` permits
the embedding page's origin when it is a subdomain of `config.domain` with the
scheme and port from `config.origin`, and not under one of the user-content
hosting domains (`static_hosting_domain`, `private_app_hosting_domain`, and their
`_alt` variants). For example, `https://puter.com` permits
`https://spreadsheet.puter.com`, and `http://puter.localhost:4100` permits
`http://spreadsheet.puter.localhost:4100` but not
`http://someone.site.puter.localhost:4100`. The embedding page is read from the
iframe request's referrer, so the host must not suppress it (the browser default
@@ -72,22 +39,14 @@ and popups to escape the sandbox.
## Host integration
A first-party app that signs in with puter.js can place `<puter-user-menu>` from
the SDK in its header instead (see `src/puter-js/src/ui/components.md`). It opens
this embed with the signed-in user named and closes it when the app's sign-in
changes. The rest of this section is for a host that builds the iframe itself.
The iframe can be shown whether or not the user is signed in. Create it when
“More apps” is opened, naming the signed-in user in its fragment, and remove it
on close so reopening loads current apps and preferences. Remove it when the
host's own sign-in changes too, such as on sign-out, so an open embed doesn't
keep the previous user. The host owns the modal and close control;
Create the iframe when “More apps” is opened, and remove it on close so reopening
loads current apps and preferences. The host owns the modal and close control;
there is no parent messaging API and no app list or credential is sent to it.
The app browser fills its iframe and responds to its size. It shows a spinner until its apps load.
The app browser fills its iframe and responds to its size.
This example assumes `puterOrigin` comes from the host app's deployment
settings. Translate the button and frame labels using the host app's
localization system.
This example assumes `puterOrigin` comes from the host app's deployment settings
and the caller has already established the GUI session. Translate the button and
frame labels using the host app's localization system.
```html
<button id="more-apps" type="button">More apps</button>
@@ -105,14 +64,10 @@ localization system.
const container = document.querySelector('#apps-frame');
const trigger = document.querySelector('#more-apps');
trigger.addEventListener('click', async () => {
const url = new URL('/embed/apps', puterOrigin);
// Signed out, the embed shows the recommended apps.
const user = puter.auth.isSignedIn() ? await puter.auth.getUser().catch(() => null) : null;
if (user) url.hash = `user=${encodeURIComponent(user.uuid)}`;
trigger.addEventListener('click', () => {
const frame = document.createElement('iframe');
frame.title = 'Your apps';
frame.src = url.href;
frame.src = new URL('/embed/apps', puterOrigin).href;
container.replaceChildren(frame);
dialog.showModal();
});
@@ -124,182 +79,18 @@ localization system.
</script>
```
## Implementation
## Implementation and checks
`createAppBrowser` in `src/gui/src/UI/Dashboard/AppBrowser.js` owns the shared UI
and data behavior; its `guestApps` option is the signed-out list. `TabApps.js`
injects desktop actions. `appsEmbed.js` supplies new-tab launching through
`launchAppInTab` (signed in) and `guestAppLaunchUrl` (signed out) in
`src/gui/src/helpers/appTabLaunch.js`, which build the same app URL as
`launch_app`, and loads only the embed entry, its SDK, and shared styles. `embedHostUser` in
`src/gui/src/helpers/embedHostUser.js` reads the host's user from the fragment, and
`embedHostTheme.js` beside it applies the host's theme.
The normal GUI webpack build emits `bundle.min.js`, `apps-embed.min.js`, and `feedback-embed.min.js`.
The `/embed/apps` route puts the recommended list in the page's config as
`guestApps`. No puter.js API or app-list endpoint changes are needed.
## Feedback dialog
`GET /embed/feedback` is the app feedback dialog (`puter.ui.showFeedbackDialog()`)
for a first-party page, with the same framing rules, query redirect, and
host-user binding as `/embed/apps`. It sends the feedback for the framing
page's origin, which the server reads from the referrer and pins with
`frame-ancestors`; opened top-level, it does nothing. Its page is transparent
so the dialog's own scrim covers the host.
puter.js uses it on a page one label under the GUI origin, other than the
subdomains the server refuses, when the page is signed in, framing it in a
modal `<dialog>` that stays hidden until the embed is ready. A session check that takes longer than 200ms shows a loading scrim
with a spinner in its place; Escape or a click on it cancels. The embed posts `{ msg: 'feedbackEmbed', state }` to its parent
(`loading`, then `ready` or `unavailable`) and finally
`{ msg: 'feedbackDialogClosed', sent }`. It reports `unavailable` without the
named user's session, or while that user's email still needs confirming, and
puter.js then uses the `/action/send-feedback` popup, which can sign in. So does
a frame that never answers, such as one the host's CSP blocks. `feedbackEmbed.js`
is the entry, sharing `embedSession` in `src/gui/src/helpers/embedSession.js`
with the app browser; `showFeedbackEmbed` in `src/puter-js/src/lib/guiEmbed.js`
is the host side.
## Sign-in and file pickers
`GET /embed/sign-in`, `/embed/show-open-file-picker`, `/embed/show-save-file-picker`
and `/embed/show-directory-picker` serve the same GUI popups as `/action/<action>`
for a first-party page, with the same framing rules, query redirect, and
`no-store` as `/embed/apps`. Any other spelling of the path (another case, a
trailing slash) redirects to it, since the shell boots the desktop for it. They render the normal GUI shell, which names the
framing page (read from the referrer, pinned with `frame-ancestors`) as
`gui_params.embed_host_origin`. The GUI then runs the popup boot unchanged, with
the framing page as `window.opener`, and `window.close()` asks the page to
remove the frame (`src/gui/src/helpers/popupFrame.js`). Without a framing page
to answer (opened top-level, or framed by a refused page) it does nothing. The
popup's parameters come from the fragment instead of the query: `msg_id`,
`options` and `request_auth`, plus `user` for a picker.
The frame posts `{ msg: 'puterPopupFrame', state }` to its parent: `loading` as
soon as the shell boots, `ready` once it shows a window or dialog, `unavailable`
when the page has to use the popup, `provider` when the user picks a sign-in
provider (below), and `closed` where a popup would close. Its
answers (`puter.token`, `fileOpenPicked`, `directoryPicked`, `fileSaved`, the
cancel messages, `sendMeFileData`) are the popup's.
puter.js uses them on a page one label under the GUI origin, other than the
subdomains the server refuses, unless the page is cross-origin isolated or in a
frame of another site (which `frame-ancestors` refuses too).
`showPopupFrame` in `src/puter-js/src/lib/guiEmbed.js` shows the frame in a box
the size of the popup window, over a scrim, hidden until `ready` and behind the
loading spinner after 200ms. Escape closes it, on the page or in the frame. One shows per popup, as each
popup has its own window name: a second picker request of the same kind
replaces the one showing, and a `signIn()` call made while a framed sign-in is
open settles with it. On
screens up to 600px wide the box fills the screen. A frame that is refused,
never answers, or reports `unavailable` falls back to the popup, opened through
a consent dialog when the click that asked for it has expired. A reload or navigation the frame
starts itself (logging out, a sign-out in another tab) names the frame as its
referrer, so the server refuses it; the page then shows its spinner and opens
the frame again, once per `ready`.
- **Sign-in** (`puter.auth.signIn()`) has no host-user binding: it is how the
page gets a user. The box has a close button, which rejects with
`auth_window_closed` as closing the popup does. Providers refuse to be
framed, so choosing one posts `{ state: 'provider', url }` with the
provider's start URL for this sign-in's `msg_id`, then `unavailable`. The
page opens the popup straight at that URL, once it checks the URL is the
GUI's `/auth/oidc/<provider>/start` for this `msg_id`, and the provider
returns it as this sign-in's popup. `attempt_temp_user_creation` keeps the popup, since
only the popup creates a temporary account.
- **Pickers** frame only for a signed-in page. The GUI reports `unavailable`
unless its session belongs to the user named in `user`, and the page then uses
the popup, which can sign in and switch accounts. The token the GUI sends
before a picker's answer isn't adopted, since it is for the page's own user.
Dismissing the loading scrim settles the picker as cancelled.
## Upgrade
`GET /embed/upgrade` is the deployment's upgrade dialog for a first-party page,
served like the popups above: the GUI shell with the same framing rules, query
redirect, exact-path redirect and `no-store`, naming the framing page as
`gui_params.embed_host_origin`. It runs only when framed by an allowed page.
puter.js frames it on a signed-in first-party page (the same pages as the
pickers) for `puter.ui.requestUpgrade(details)`, and for the Upgrade button of
the usage limit dialog a refused call shows there. Elsewhere both keep their
behavior: inside an app `requestUpgrade()` asks the desktop, and on any other
page the usage limit dialog opens the dashboard's upgrade page in a new tab.
The frame covers the page with no box or close button, and the GUI page is
transparent (`html.popup-frame-transparent`) so the dialog's own scrim covers
the host. The frame allows `payment` as well as `otp-credentials`. Escape on the
page is left to the dialog, since one there shouldn't drop a payment in
progress. Its fragment names `user` (the page's signed-in user) and, when the
refusal gave them, `reason` (`funds`, `subscription` or `storage`) and `method`.
The GUI reports `unavailable` unless its session belongs to `user`, the account
has no verification or password change waiting (which the frame couldn't be
closed from), and the deployment defines `window.UIUpgradeAccount` with
`UIUpgradeAccount.embeddable === true`. Otherwise it runs:
```js
new UIUpgradeAccount({ attribution: { appUid, reason, method }, onClose }).open_as_window();
```
`appUid` is the app the framing page's origin resolves to, never one the
fragment names. `open_as_window()` resolves once the dialog shows, and the GUI
then posts `ready`. While the page still hides the frame, which Chromium and
WebKit lay out at 0x0, the GUI posts `ready` first and opens the dialog once
the frame has a viewport, so a window it opens doesn't center on 0x0.
`onClose({ upgraded })` must run exactly once, when the
dialog closes or when it declines to open for the account; the GUI then posts
`{ msg: 'puterPopupFrame', state: 'closed', upgraded }` and the page removes
the frame. If `open_as_window()` rejects, the GUI posts `unavailable` instead. `requestUpgrade()` resolves `{ upgraded }`. A call made while the
frame shows settles with it rather than replacing it, and a call refused while
it shows still rejects but opens no usage limit dialog over it.
When the frame can't show the upgrade (refused, never ready, `unavailable`, or
no user to name), puter.js opens the dashboard's upgrade page in a new tab with
what was refused, through a consent dialog when the click has expired or the
tab is blocked, and `requestUpgrade()` resolves `{ upgraded: false }`.
## Email confirmation
`GET /embed/request-email-confirmation` walks a first-party page's user through
confirming their email, served like the upgrade: the GUI shell with the same
framing rules, redirects and `no-store`, run only when framed by an allowed
page. puter.js frames it on a signed-in first-party page for
`puter.ui.requestEmailConfirmation()`. Inside an app the desktop shows the same
windows over the app instead.
Like the upgrade, the frame covers the page with no box or close button, over a
transparent GUI page, and its fragment names `user`. Escape closes it, on the
page or on the save-account or code window. On a window, Escape closes that
window as its close button does, so a code already sent still answers. The GUI
reports `unavailable` unless its session belongs to `user` and the account has
no phone, card or password check waiting.
An email check is fine: the boot skips its own email gate for this action, so
the user gets one code window they can close.
The GUI then runs `ensureConfirmedEmail` (`src/gui/src/helpers/ensureConfirmedEmail.js`),
which the desktop's handler uses too: a temporary account gets the save-account
window first, then an unconfirmed email gets the code window, each at most
once. When the page's whoami already reads the email as confirmed,
`requestEmailConfirmation()` resolves `{ response: true }` without framing
anything, and a confirmation in the frame marks that whoami confirmed for the
calls after it. An email the GUI reads as confirmed shows nothing. Before
opening a window the GUI waits for the frame to have a viewport, as the upgrade
does. It then posts
`{ msg: 'puterPopupFrame', state: 'closed', confirmed }`, and
`requestEmailConfirmation()` resolves `{ response: confirmed }`, the field an
app reads from the desktop's answer. A call made while the frame shows settles
with it. A frame that is refused, never ready, or `unavailable` resolves
`{ response: false }`, since there's no popup to fall back to.
## Checks
and data behavior. `TabApps.js` injects desktop actions. `appsEmbed.js` supplies
new-tab launching and loads only the embed entry, its SDK, and shared styles.
The normal GUI webpack build emits `bundle.min.js` and `apps-embed.min.js`.
No puter.js API or app-list endpoint changes are needed.
Run the GUI component/browser tests (with the SDK bundle built and Playwright
Chromium installed), and the backend route tests:
```sh
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser src/feedbackEmbed
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
```
+2 -6
View File
@@ -117,7 +117,7 @@ export type EventMap = {
model_used: string;
service_used: string;
intended_service: string;
model_details?: {
model_details: {
id: string;
provider: string;
input_cost_key: string;
@@ -420,11 +420,7 @@ export type EventMap = {
old_username: string;
new_username: string;
};
'user.email-changed': {
user_id: number;
old_email: string | null;
new_email: string;
};
'user.email-changed': { user_id: number; new_email: string };
/** An account was suspended, or its suspension lifted. Local events. */
'user.suspended': { userId: number };
'user.unsuspended': { userId: number };
@@ -7468,11 +7468,6 @@ describe('AuthController user-protected mutations (validation paths)', () => {
{ expiresIn: '1h' },
);
const heard: Array<Record<string, unknown>> = [];
eventClient.on('user.email-changed', (_k, data) => {
heard.push(data as Record<string, unknown>);
});
const req = makeReq({});
(req as unknown as { query: Record<string, string> }).query = {
token: linkJwt,
@@ -7480,11 +7475,6 @@ describe('AuthController user-protected mutations (validation paths)', () => {
const res = makeRes();
await controller.handleChangeEmailConfirm(req, res);
expect(res.sent).toMatch(/Email changed successfully/);
expect(heard).toContainEqual({
user_id: user.id,
old_email: user.email ?? null,
new_email: newEmail,
});
const after = await server.stores.user.getById(user.id, {
force: true,
@@ -2647,7 +2647,6 @@ export class AuthController extends PuterController {
'user.email-changed' as never,
{
user_id: user.id,
old_email: user.email ?? null,
new_email: newEmail,
} as never,
{},
@@ -15,6 +15,7 @@ export interface OidcLoginContinuation {
embeddedInPopup: boolean;
openerOrigin: string | null;
messageId: string | null;
switchedToLogin: boolean;
}
interface OidcReturnDeps {
@@ -55,6 +56,7 @@ export function completeOidcLoginReturn(
data.userUuid !== user.uuid ||
typeof data.redirectUri !== 'string' ||
typeof data.embeddedInPopup !== 'boolean' ||
typeof data.switchedToLogin !== 'boolean' ||
(data.openerOrigin !== null && typeof data.openerOrigin !== 'string') ||
(data.messageId !== null && typeof data.messageId !== 'string')
) {
@@ -89,5 +91,6 @@ export function completeOidcLoginReturn(
),
);
}
if (data.switchedToLogin) append('oidc_switched', 'login');
return target;
}
@@ -27,7 +27,6 @@ import type { Actor } from '../../core/actor.js';
import { PuterRouter } from '../../core/http/PuterRouter.js';
import { PuterServer } from '../../server.js';
import { setupTestServer } from '../../testUtil.js';
import { embedFrameAncestors, embedHostOrigin } from './HomepageController.js';
// ── Test harness ────────────────────────────────────────────────────
//
@@ -530,46 +529,3 @@ describe('HomepageController GET /sw.js', () => {
expect(route?.options.subdomain).toBe('');
});
});
describe('embedFrameAncestors', () => {
const config = {
origin: 'https://example.test',
domain: 'example.test',
api_base_url: 'https://backend.example.test',
};
it('names a sibling subdomain that embeds the browser', () => {
expect(
embedFrameAncestors(config, 'https://sheets.example.test/doc/1'),
).toBe("'self' https://sheets.example.test");
});
it('refuses the configured API host even off the api label', () => {
expect(
embedFrameAncestors(config, 'https://backend.example.test/x'),
).toBe("'self'");
});
});
describe('embedHostOrigin', () => {
const config = {
origin: 'https://example.test',
domain: 'example.test',
api_base_url: 'https://backend.example.test',
static_hosting_domain: 'site.example.test',
};
it.each([
['https://sheets.example.test/doc/1', 'https://sheets.example.test'],
['https://backend.example.test/x', null],
['https://api.example.test/', null],
['https://someone.site.example.test/', null],
['https://a.sheets.example.test/', null],
['http://sheets.example.test/', null],
['https://example.test/', null],
['not a url', null],
[undefined, null],
])('%s frames as %s', (referer, expected) => {
expect(embedHostOrigin(config, referer)).toBe(expected);
});
});
@@ -22,33 +22,13 @@ import path from 'node:path';
import { PuterController } from '../types.js';
import { toAppShellView } from '../../util/appShellView.js';
import type { PuterRouter } from '../../core/http/PuterRouter';
import {
isReservedSubdomain,
subdomainLabelOf,
} from '../../core/http/middleware/hostRedirects.js';
import type { IConfig } from '../../types';
import type {
PuterHomepageService,
PageMeta,
LaunchOptions,
PopupFrame,
} from '../../services/homepage/PuterHomepageService';
/**
* GUI popups a first-party page can show in a frame at `/embed/<action>`,
* instead of opening `/action/<action>` in a window, plus the upgrade dialog,
* which it would otherwise open in a dashboard tab, and the email confirmation,
* which it otherwise can't show.
*/
export const FRAMED_POPUP_ACTIONS = [
'sign-in',
'show-open-file-picker',
'show-save-file-picker',
'show-directory-picker',
'upgrade',
'request-email-confirmation',
] as const;
/** Longest description/og:description/twitter:description on `/app/<name>`. */
export const APP_META_DESCRIPTION_MAX = 150;
@@ -77,37 +57,31 @@ export function appMetaDescription(text: string): string {
return `${cut.replace(/[\s,;:.!?…—-]+$/, '')}…`;
}
type EmbedFramingConfig = Pick<
IConfig,
| 'origin'
| 'domain'
| 'api_base_url'
| 'static_hosting_domain'
| 'static_hosting_domain_alt'
| 'private_app_hosting_domain'
| 'private_app_hosting_domain_alt'
>;
/**
* The origin of a first-party page that may frame an `/embed/*` page, named
* exactly from the request's referrer, or null. A wildcard over `*.<domain>`
* would also admit user-hosted sites whenever the hosting domains sit under it,
* so only a single label under `<domain>` qualifies, and not one this server
* answers itself (the API, WebDAV, SDK and native-app hosts).
* `frame-ancestors` for the app browser embed. A wildcard over `*.<domain>`
* would also admit user-hosted sites whenever the hosting domains sit under
* it, so the embedding page is named exactly, from the request's referrer.
*/
export function embedHostOrigin(
config: EmbedFramingConfig,
export function embedFrameAncestors(
config: Pick<
IConfig,
| 'origin'
| 'domain'
| 'static_hosting_domain'
| 'static_hosting_domain_alt'
| 'private_app_hosting_domain'
| 'private_app_hosting_domain_alt'
>,
referer: string | undefined,
): string | null {
): string {
const gui = new URL(config.origin ?? `https://${config.domain}`);
let parent: URL;
try {
parent = new URL(referer ?? '');
} catch {
return null;
return "'self'";
}
const host = parent.hostname.toLowerCase();
const label = subdomainLabelOf(host, config.domain);
const hostingDomains = [
config.static_hosting_domain,
config.static_hosting_domain_alt,
@@ -119,20 +93,9 @@ export function embedHostOrigin(
const allowed =
parent.protocol === gui.protocol &&
parent.port === gui.port &&
label !== undefined &&
!isReservedSubdomain(label) &&
host !== new URL(config.api_base_url).hostname &&
host.endsWith(`.${config.domain.toLowerCase()}`) &&
!hostingDomains.some((d) => host === d || host.endsWith(`.${d}`));
return allowed ? parent.origin : null;
}
/** `frame-ancestors` for an `/embed/*` page: the GUI and {@link embedHostOrigin}. */
export function embedFrameAncestors(
config: EmbedFramingConfig,
referer: string | undefined,
): string {
const host = embedHostOrigin(config, referer);
return host ? `'self' ${host}` : "'self'";
return allowed ? `'self' ${parent.origin}` : "'self'";
}
/**
@@ -169,7 +132,6 @@ export class HomepageController extends PuterController {
res: express.Response,
metaOverrides: Partial<PageMeta> = {},
launch: LaunchOptions = {},
popupFrame?: PopupFrame,
) => {
const meta = { ...defaultMeta(req), ...metaOverrides };
const actor =
@@ -178,27 +140,18 @@ export class HomepageController extends PuterController {
actor?: Parameters<typeof homepage.send>[0]['actor'];
}
).actor ?? null;
await homepage.send({ req, res, actor }, meta, launch, popupFrame);
await homepage.send({ req, res, actor }, meta, launch);
};
// -- Root + path-aliased shell routes ------------------------
router.get('/', {}, (req, res) => sendShell(req, res));
/**
* Headers shared by the `/embed/*` pages; false when the request was
* redirected instead. SDK bootstrap parameters must not change an
* embed's account or API origin, so a query string is dropped. Checked
* on the raw URL; `req.query` drops pairs past the parser's limit.
*/
const prepareEmbed = (
req: express.Request,
res: express.Response,
path: string,
): boolean => {
if (req.originalUrl.includes('?')) {
res.redirect(path);
return false;
router.get('/embed/apps', {}, (req, res) => {
// SDK bootstrap parameters must not change this page's account or API origin.
if (Object.keys(req.query).length) {
res.redirect('/embed/apps');
return;
}
res.removeHeader('X-Frame-Options');
res.setHeader(
@@ -206,61 +159,9 @@ export class HomepageController extends PuterController {
`frame-ancestors ${embedFrameAncestors(this.config, req.get('referer'))}`,
);
res.setHeader('Cache-Control', 'no-store');
return true;
};
router.get('/embed/apps', {}, async (req, res) => {
if (!prepareEmbed(req, res, '/embed/apps')) return;
// Shown to visitors without a session; a signed-in embed fetches
// its own list, so a failure here only costs signed-out visitors.
const guestApps = await this.services.recommendedApps
.getRecommendedApps()
.catch((): Array<Record<string, unknown>> => []);
res.send(homepage.renderAppBrowserEmbed({ guestApps }));
res.send(homepage.renderAppBrowserEmbed());
});
router.get('/embed/feedback', {}, (req, res) => {
if (!prepareEmbed(req, res, '/embed/feedback')) return;
// The feedback is recorded against this origin, which
// frame-ancestors has just pinned to the actual framing page.
res.send(
homepage.renderFeedbackEmbed({
hostOrigin: embedHostOrigin(
this.config,
req.get('referer'),
),
}),
);
});
// The GUI runs the popup's own boot, answering the framing page
// instead of an opener.
for (const action of FRAMED_POPUP_ACTIONS) {
const embedPath = `/embed/${action}`;
router.get(embedPath, {}, async (req, res) => {
// Routes match case-insensitively and with a trailing slash,
// and the shell boots the desktop for any other spelling, so
// only the exact one may be framed.
if (req.originalUrl !== embedPath) {
res.redirect(embedPath);
return;
}
if (!prepareEmbed(req, res, embedPath)) return;
await sendShell(
req,
res,
{},
{},
{
hostOrigin: embedHostOrigin(
this.config,
req.get('referer'),
),
},
);
});
}
router.get('/settings', {}, (req, res) => sendShell(req, res));
router.get('/settings/*splat', {}, (req, res) => sendShell(req, res));
@@ -1620,7 +1620,7 @@ describe('OIDCController signup callback', () => {
expect(captured.redirectUrl).toContain('action=signup');
});
it('creates a fresh user on first signup', async () => {
it('creates a fresh user without oidc_switched on first signup', async () => {
const state = oidc().signState({
provider: 'custom',
redirect_uri: TEST_ORIGIN + '/',
@@ -1646,9 +1646,11 @@ describe('OIDCController signup callback', () => {
);
expect(captured.cookies).toHaveLength(1);
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
// Fresh creation — must NOT advertise "you've actually been signed in".
expect(captured.redirectUrl).not.toContain('oidc_switched=login');
});
it('signs in to an already-linked account on signup, returning as a login would', async () => {
it('adds oidc_switched=login when signup hits an already-linked account', async () => {
// Seed an account linked on (provider, sub) so the signup callback
// resolves to `linked-sub` rather than creating a new user.
const sub = `sub-${Math.random().toString(36).slice(2, 8)}`;
@@ -1684,7 +1686,7 @@ describe('OIDCController signup callback', () => {
res,
);
expect(captured.cookies).toHaveLength(1);
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
expect(captured.redirectUrl).toContain('oidc_switched=login');
});
it('redirects to action=signup with auth_error when user resolution fails (unconfirmed email)', async () => {
+17 -5
View File
@@ -688,7 +688,14 @@ export class OIDCController extends PuterController {
);
}
await this.#finishLogin(req, res, user, stateDecoded);
// If we landed on an existing account (either via the
// provider_sub or via email match), signal the GUI so it can
// render a "signed in" flow rather than "account created".
const extra =
resolved.origin === 'created'
? undefined
: { oidc_switched: 'login' };
await this.#finishLogin(req, res, user, stateDecoded, extra);
};
router.get('/auth/oidc/callback/signup', cbOpts, signupCb);
router.post('/auth/oidc/callback/signup', cbOpts, signupCb);
@@ -827,14 +834,17 @@ if (window.opener) {
attempt = 0,
): Promise<
| { error: string; code?: string; requestCode?: string }
| { user: import('../../stores/user/UserStore.js').UserRow }
| {
user: import('../../stores/user/UserStore.js').UserRow;
origin: 'linked-sub' | 'linked-email' | 'created';
}
> {
// 1. Existing provider/sub link.
const linked = await this.services.oidc.findUserByProviderSub(
provider,
userinfo.sub,
);
if (linked) return { user: linked };
if (linked) return { user: linked, origin: 'linked-sub' };
// 2/3. Email match branch.
const claimedEmail =
@@ -871,7 +881,7 @@ if (window.opener) {
error: outcome.error ?? 'Failed to link provider.',
};
}
return { user: byEmail };
return { user: byEmail, origin: 'linked-email' };
}
}
@@ -901,7 +911,7 @@ if (window.opener) {
requestCode: outcome.requestCode,
};
}
return { user: outcome.user };
return { user: outcome.user, origin: 'created' };
}
async #processCallback(
@@ -990,6 +1000,7 @@ if (window.opener) {
res: Response,
user: UserRow,
stateDecoded: Record<string, unknown>,
extraQueryParams?: Record<string, string>,
): Promise<void> {
const origin = (this.config.origin ?? '').replace(/\/$/, '');
const continuation: OidcLoginContinuation = {
@@ -1007,6 +1018,7 @@ if (window.opener) {
stateDecoded.msg_id == null
? null
: String(stateDecoded.msg_id),
switchedToLogin: extraQueryParams?.oidc_switched === 'login',
};
if (user.otp_enabled) {
const challenge = this.services.token.sign(
@@ -139,7 +139,7 @@ describe('OIDC account second-factor login', () => {
expect(await response.json()).toMatchObject({
proceed: true,
next_step: 'complete',
redirectUrl: `${env.origin}/dashboard`,
redirectUrl: `${env.origin}/dashboard${flow === 'signup' ? '?oidc_switched=login' : ''}`,
});
expect(
response.headers
@@ -187,9 +187,9 @@ describe('createUserSubdomainNotFound', () => {
});
it('passes through reserved subdomains (api, js, native apps, etc.)', () => {
// `api`, `js`, `dav`, `docs`, `developer`, `about`, `apps`,
// `api`, `js`, `dav`, `docs`, `developer`, `editor`, `pdf`,
// `puter-app-icons`, etc. all pass through.
for (const sub of ['api', 'js', 'docs', 'about', 'puter-app-icons']) {
for (const sub of ['api', 'js', 'docs', 'editor', 'puter-app-icons']) {
const { out, next } = run(
createUserSubdomainNotFound(config),
makeReq({
@@ -865,13 +865,13 @@ describe('createNativeAppStatic', () => {
beforeAll(() => {
root = mkdtempSync(nodePath.join(tmpdir(), 'native-apps-'));
mkdirSync(nodePath.join(root, 'about', 'assets'), { recursive: true });
mkdirSync(nodePath.join(root, 'editor', 'assets'), { recursive: true });
writeFileSync(
nodePath.join(root, 'about', 'index.html'),
'<h1>about</h1>',
nodePath.join(root, 'editor', 'index.html'),
'<h1>editor</h1>',
);
writeFileSync(
nodePath.join(root, 'about', 'assets', 'app.js'),
nodePath.join(root, 'editor', 'assets', 'app.js'),
'console.log(1);',
);
mkdirSync(nodePath.join(root, 'docs', 'dist'), { recursive: true });
@@ -893,7 +893,7 @@ describe('createNativeAppStatic', () => {
it('leaves a native app name alone on a host outside our domains', async () => {
const req = staticReq({
subdomains: ['com', 'example', 'about'],
subdomains: ['com', 'example', 'editor'],
path: '/index.html',
});
(req as Request & { is_custom_domain?: boolean }).is_custom_domain =
@@ -907,7 +907,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
createNativeAppStatic(config),
staticReq({
subdomains: ['localhost', 'puter', 'about'],
subdomains: ['localhost', 'puter', 'editor'],
path: '/index.html',
}),
);
@@ -915,24 +915,17 @@ describe('createNativeAppStatic', () => {
expect(next).toHaveBeenCalledTimes(1);
});
// `editor`, `markus` and `pdf` are web apps on standard host routing,
// even with a folder of their own under the native apps root.
it.each(['api', 'editor', 'markus', 'pdf'])(
'passes %s through, as it is not a native app',
async (sub) => {
mkdirSync(nodePath.join(root, sub), { recursive: true });
writeFileSync(nodePath.join(root, sub, 'index.html'), sub);
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', sub],
path: '/index.html',
}),
);
expect(out.sent).toBeUndefined();
expect(next).toHaveBeenCalledTimes(1);
},
);
it('passes through subdomains that are not native apps', async () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'api'],
path: '/index.html',
}),
);
expect(out.sent).toBeUndefined();
expect(next).toHaveBeenCalledTimes(1);
});
it('passes through when there is no subdomain at all', async () => {
const { next } = await runStatic(
@@ -946,13 +939,13 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'about'],
subdomains: ['localhost', 'puter', 'editor'],
path: '/index.html',
}),
);
expect(out.sent).toEqual({
path: '/index.html',
root: nodePath.join(root, 'about'),
root: nodePath.join(root, 'editor'),
});
expect(next).not.toHaveBeenCalled();
});
@@ -961,11 +954,11 @@ describe('createNativeAppStatic', () => {
const { out } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'ABOUT'],
subdomains: ['localhost', 'puter', 'EDITOR'],
path: '/index.html',
}),
);
expect(out.sent?.root).toBe(nodePath.join(root, 'about'));
expect(out.sent?.root).toBe(nodePath.join(root, 'editor'));
});
it('serves docs out of its dist/ subdirectory, not the app root', async () => {
@@ -986,7 +979,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'about'],
subdomains: ['localhost', 'puter', 'editor'],
path: '/assets',
originalUrl: '/assets?v=2',
}),
@@ -1002,7 +995,7 @@ describe('createNativeAppStatic', () => {
const { out } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'about'],
subdomains: ['localhost', 'puter', 'editor'],
path: '/assets/',
}),
);
@@ -1014,7 +1007,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'about'],
subdomains: ['localhost', 'puter', 'editor'],
path: '/nope.html',
}),
);
@@ -1026,7 +1019,7 @@ describe('createNativeAppStatic', () => {
const { next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'about'],
subdomains: ['localhost', 'puter', 'editor'],
path: '/index.html',
}),
new Error('send failed'),
@@ -1039,7 +1032,7 @@ describe('createNativeAppStatic', () => {
runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'about'],
subdomains: ['localhost', 'puter', 'editor'],
path: '/../../etc/passwd',
}),
),
@@ -27,7 +27,15 @@ import { HttpError, isHttpError } from '../HttpError';
import { isLocalWorkerHost } from './localWorkerProxy';
/** Native-app subdomains served via `nativeAppStatic`. */
const NATIVE_APP_SUBDOMAINS = ['about', 'developer', 'docs', 'apps'] as const;
const NATIVE_APP_SUBDOMAINS = [
'about',
'developer',
'docs',
'editor',
'markus',
'pdf',
'apps',
] as const;
/** Subset served out of a `dist/` subdirectory rather than the app root. */
const NATIVE_APPS_WITH_DIST = new Set(['docs', 'developer']);
@@ -103,10 +111,6 @@ export const subdomainLabelOf = (
return label && !label.includes('.') ? label : undefined;
};
/** Whether core itself answers `<name>.<domain>` (`www` redirects to the root). */
export const isReservedSubdomain = (name: string): boolean =>
name === 'www' || RESERVED_SUBDOMAINS.has(name);
/**
* Record a claim on `<name>.<domain>`. Throws on a malformed or uppercase
* label, a subdomain core already handles, or a name that is already claimed.
@@ -119,7 +123,7 @@ export const addClaimedSubdomain = (
if (typeof name !== 'string' || !SUBDOMAIN_LABEL.test(name)) {
throw new Error(`Invalid subdomain label: ${JSON.stringify(name)}`);
}
if (isReservedSubdomain(name)) {
if (name === 'www' || RESERVED_SUBDOMAINS.has(name)) {
throw new Error(`Subdomain '${name}' is reserved`);
}
if (claims.has(name)) {
+2 -117
View File
@@ -352,10 +352,6 @@ describe('PuterServer host header validation', () => {
expect(res.body).toContain('/dist/apps-embed.min.js');
expect(res.body).not.toContain('/dist/bundle.min.js');
expect(res.body).toContain(`http://api.puter.localhost:${port}`);
const config = JSON.parse(
res.body.match(/id="app-browser-config">(.*?)<\/script>/)[1],
);
expect(Array.isArray(config.guestApps)).toBe(true);
}
const gui = await request('/embed/apps', {
host: `puter.localhost:${port}`,
@@ -368,116 +364,9 @@ describe('PuterServer host header validation', () => {
expect(api.status).toBe(404);
});
it('lets a deployment subdomain frame the feedback embed and names it', async () => {
const parent = `http://spreadsheet.puter.localhost:${port}`;
const res = await request('/embed/feedback', {
host: `puter.localhost:${port}`,
referer: `${parent}/sheet/1`,
});
expect(res.status).toBe(200);
expect(res.headers['x-frame-options']).toBeUndefined();
expect(res.headers['content-security-policy']).toBe(
`frame-ancestors 'self' ${parent}`,
);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.body).toContain('/dist/feedback-embed.min.js');
expect(res.body).not.toContain('/dist/bundle.min.js');
const config = JSON.parse(
res.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
);
expect(config).toEqual({
apiOrigin: `http://api.puter.localhost:${port}`,
hostOrigin: parent,
});
const hosted = await request('/embed/feedback', {
host: `puter.localhost:${port}`,
referer: `http://someone.site.puter.localhost:${port}/`,
});
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
expect(
JSON.parse(
hosted.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
).hostOrigin,
).toBeNull();
const redirected = await request('/embed/feedback?puter.api_origin=https://other.test', {
host: `puter.localhost:${port}`,
});
expect(redirected.status).toBe(302);
expect(redirected.headers.location).toBe('/embed/feedback');
});
it.each([
'sign-in',
'show-open-file-picker',
'show-save-file-picker',
'show-directory-picker',
'upgrade',
'request-email-confirmation',
])('lets a deployment subdomain frame the %s popup and names it to the GUI', async (action) => {
const parent = `http://spreadsheet.puter.localhost:${port}`;
const guiParams = (body: string) =>
JSON.parse(body.match(/gui\((\{.*\})\);/)[1]);
const res = await request(`/embed/${action}`, {
host: `puter.localhost:${port}`,
referer: `${parent}/sheet/1`,
});
expect(res.status).toBe(200);
expect(res.headers['x-frame-options']).toBeUndefined();
expect(res.headers['content-security-policy']).toBe(
`frame-ancestors 'self' ${parent}`,
);
expect(res.headers['cache-control']).toBe('no-store');
expect(guiParams(res.body).embed_host_origin).toBe(parent);
const hosted = await request(`/embed/${action}`, {
host: `puter.localhost:${port}`,
referer: `http://someone.site.puter.localhost:${port}/`,
});
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
expect(guiParams(hosted.body).embed_host_origin).toBeNull();
const redirected = await request(`/embed/${action}?auth_token=x&embedded_in_popup=true`, {
host: `puter.localhost:${port}`,
referer: `${parent}/sheet/1`,
});
expect(redirected.status).toBe(302);
expect(redirected.headers.location).toBe(`/embed/${action}`);
expect(redirected.headers['x-frame-options']).toBe('SAMEORIGIN');
});
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Request-Email-Confirmation'])(
'lets a first-party page frame only the exact spelling of %s',
async (spelling) => {
const res = await request(spelling, {
host: `puter.localhost:${port}`,
referer: `http://spreadsheet.puter.localhost:${port}/`,
});
expect(res.status).toBe(302);
expect(res.headers.location).toBe(spelling.toLowerCase().replace(/\/$/, ''));
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
expect(res.headers['content-security-policy']).toBeUndefined();
},
);
it('names no framing page to the popups it serves in a window', async () => {
const res = await request('/action/sign-in?embedded_in_popup=true', {
host: `puter.localhost:${port}`,
referer: `http://spreadsheet.puter.localhost:${port}/`,
});
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
expect(res.headers['content-security-policy']).toBeUndefined();
expect(res.body).not.toContain('embed_host_origin');
});
it.each([
['a user-hosted site', 'http://someone.site.puter.localhost:PORT/'],
['a private app host', 'http://someone.app.puter.localhost:PORT/'],
['the API host', 'http://api.puter.localhost:PORT/'],
['the WebDAV host', 'http://dav.puter.localhost:PORT/'],
['a native app host', 'http://about.puter.localhost:PORT/'],
['a nested subdomain', 'http://a.spreadsheet.puter.localhost:PORT/'],
['another site', 'http://evil.test:PORT/'],
['another port', 'http://spreadsheet.puter.localhost:1/'],
['a suppressed referrer', undefined],
@@ -490,12 +379,8 @@ describe('PuterServer host header validation', () => {
expect(res.headers['content-security-policy']).toBe("frame-ancestors 'self'");
});
it.each([
['plain', ''],
// Past the parser's 1000-pair limit, so `req.query` comes back empty.
['padded', '&'.repeat(1000)],
])('strips %s SDK bootstrap query parameters from the embed route', async (_label, padding) => {
const res = await request(`/embed/apps?${padding}puter.app_instance_id=other&puter.api_origin=https://other.test`, {
it('strips SDK bootstrap query parameters from the embed route', async () => {
const res = await request('/embed/apps?puter.app_instance_id=other&puter.api_origin=https://other.test', {
host: `puter.localhost:${port}`,
});
expect(res.status).toBe(302);
@@ -27,16 +27,17 @@ import { PuterService } from '../types.js';
*/
export const RECOMMENDED_APP_NAMES = [
'builder',
'word-processor',
'spreadsheet',
'presentation',
'whiteboard',
'pdf-editor',
'contacts',
'calendar',
'meetings',
'teamchat',
'email',
'whiteboard',
'spreadsheet',
'word-processor',
'presentation',
'pdf-editor',
'terminal',
'dev-center',
'cap-table',
'invoices',
@@ -144,22 +144,11 @@ const createInline = async (
return String(response.body.subId);
};
/**
* The post each label made, in order, once all have arrived. Matched by label
* since earlier tests' subscriptions stay live and post to the same sink.
*/
const delivered = async (...labels: string[]): Promise<SinkPost[]> => {
await vi.waitFor(
() =>
expect(sinkPosts.map((post) => post.label)).toEqual(
expect.arrayContaining(labels),
),
{ timeout: 30_000, interval: 50 },
);
return labels.map((label) =>
sinkPosts.find((post) => post.label === label)!,
);
};
const delivered = (count = 1): Promise<void> =>
vi.waitFor(() => expect(sinkPosts.length).toBeGreaterThanOrEqual(count), {
timeout: 30_000,
interval: 50,
});
beforeAll(async () => {
env = await setupPuterTestEnv({
@@ -266,11 +255,14 @@ describe('an inline handler in a user scope, end to end', () => {
await env.server.services.fs.touch(holder.id, {
path: `${holder.anchor}/note.txt`,
});
const [post] = await delivered('inline');
await delivered();
expect(post.path).toBe(`${holder.anchor}/note.txt`);
expect(sinkPosts[0]).toMatchObject({
label: 'inline',
path: `${holder.anchor}/note.txt`,
});
const { actor } = await env.server.services.auth.authenticate(
post.token!,
sinkPosts[0].token!,
);
expect(actor!.user?.id).toBe(holder.id);
expect(actor!.effectiveApp?.uid).toBe(appUid);
@@ -305,14 +297,14 @@ describe('an inline handler in a user scope, end to end', () => {
await env.server.services.fs.touch(holder.id, {
path: `${holder.anchor}/shared-${i}.txt`,
});
// The first test's 'inline' handler also posts for holders[0].
const posts = await delivered('first', 'second');
for (const [i, post] of posts.entries()) {
const { actor } = await env.server.services.auth.authenticate(
post.token!,
await delivered(2);
const runAs = new Set<number>();
for (const post of sinkPosts)
runAs.add(
(await env.server.services.auth.authenticate(post.token!))
.actor!.user!.id,
);
expect(actor!.user!.id).toBe(holders[i].id);
}
expect(runAs).toEqual(new Set(holders.map((h) => h.id)));
create.mockRestore();
},
);
@@ -63,28 +63,13 @@ describe('app browser embed shell', () => {
const html = service.renderAppBrowserEmbed();
const configJson = html.match(/id="app-browser-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson)).toEqual({
apiOrigin: 'https://api.deployment.test', sdkUrl, guestApps: [],
apiOrigin: 'https://api.deployment.test', sdkUrl,
});
expect(html).toContain('/dist/apps-embed.min.js');
expect(html).not.toContain('/dist/bundle.min.js');
expect(html).not.toContain('gui(');
});
it.each([
[{}, '/dist/apps-embed.min.js'],
[
{ gui_bundle: 'https://gui-cdn.deployment.test/bundle.min.js' },
'https://gui-cdn.deployment.test/apps-embed.min.js',
],
[
{ gui_bundle: '/static/bundle.min.js?v=42' },
'/static/apps-embed.min.js?v=42',
],
])('loads its script from beside the GUI bundle %j', (config, script) => {
const html = makeService(config).renderAppBrowserEmbed();
expect(html).toContain(`<script defer src="${script}"></script>`);
});
it('escapes configured values without breaking its JSON bootstrap', () => {
const sdkUrl = '/sdk.js?value=</script><script>unexpected()</script>';
const html = makeService({
@@ -95,41 +80,6 @@ describe('app browser embed shell', () => {
const configJson = html.match(/id="app-browser-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson).sdkUrl).toBe(sdkUrl);
});
it('carries the apps shown without a session, escaped', () => {
const guestApps = [
{ name: 'notes', title: '</script><script>unexpected()</script>' },
];
const html = makeService({}).renderAppBrowserEmbed({ guestApps });
expect(html).not.toContain('<script>unexpected()');
const configJson = html.match(/id="app-browser-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson).guestApps).toEqual(guestApps);
});
});
describe('feedback embed shell', () => {
it('carries the framing page and API origin, and loads only its own script', () => {
const html = makeService({
api_base_url: 'https://api.deployment.test',
gui_bundle: '/static/bundle.min.js?v=42',
}).renderFeedbackEmbed({ hostOrigin: 'https://notes.deployment.test' });
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson)).toEqual({
apiOrigin: 'https://api.deployment.test',
hostOrigin: 'https://notes.deployment.test',
});
expect(html).toContain('<script defer src="/static/feedback-embed.min.js?v=42"></script>');
expect(html).toContain('<link rel="stylesheet" href="/css/feedback-embed.css">');
expect(html).toContain('<main id="feedback-embed"></main>');
expect(html).not.toContain('bundle.min.js');
expect(html).not.toContain('apps-embed');
});
it('carries no framing page when none is allowed', () => {
const html = makeService({}).renderFeedbackEmbed({ hostOrigin: null });
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
expect(JSON.parse(configJson).hostOrigin).toBeNull();
});
});
/** Capture what the service sends, and return the rendered HTML. */
@@ -48,15 +48,6 @@ export interface LaunchOptions {
on_initialized?: Array<Record<string, unknown>>;
}
/**
* A GUI popup a first-party page frames at `/embed/<action>`. `hostOrigin` is
* that page, read from the referrer and pinned with frame-ancestors; null when
* no allowed page frames it.
*/
export interface PopupFrame {
hostOrigin: string | null;
}
interface PuterGuiAddonsEvent {
req: Request;
path: string;
@@ -176,54 +167,15 @@ export class PuterHomepageService extends PuterService {
this.#guiParams[key] = val;
}
/** `guestApps` is what the embed shows a visitor without a session. */
renderAppBrowserEmbed({
guestApps = [],
}: { guestApps?: Array<Record<string, unknown>> } = {}): string {
return this.#renderEmbed({
rootId: 'app-browser',
rootClass: 'dashboard',
stylesheet: 'apps-embed.css',
script: 'apps-embed.min.js',
config: {
apiOrigin: this.config.api_base_url,
sdkUrl:
this.config.env === 'dev'
? '/sdk/puter.dev.js'
: (this.config.gui_puterjs_bundle ??
'https://js.puter.com/v2/'),
guestApps,
},
});
}
/**
* `hostOrigin` is the first-party page framing the dialog, which the
* feedback is sent for; null when no allowed page frames it.
*/
renderFeedbackEmbed({ hostOrigin }: { hostOrigin: string | null }): string {
return this.#renderEmbed({
rootId: 'feedback-embed',
stylesheet: 'feedback-embed.css',
script: 'feedback-embed.min.js',
config: { apiOrigin: this.config.api_base_url, hostOrigin },
});
}
#renderEmbed({
rootId,
rootClass,
stylesheet,
script,
config,
}: {
rootId: string;
rootClass?: string;
stylesheet: string;
script: string;
config: Record<string, unknown>;
}): string {
const configJson = JSON.stringify(config).replace(/</g, '\\u003c');
renderAppBrowserEmbed(): string {
const configJson = JSON.stringify({
apiOrigin: this.config.api_base_url,
sdkUrl:
this.config.env === 'dev'
? '/sdk/puter.dev.js'
: (this.config.gui_puterjs_bundle ??
'https://js.puter.com/v2/'),
}).replace(/</g, '\\u003c');
return `<!DOCTYPE html>
<html lang="en">
@@ -234,33 +186,16 @@ export class PuterHomepageService extends PuterService {
<title>${encode(String(this.config.gui_params?.title ?? 'Puter'))}</title>
<link rel="stylesheet" href="/css/normalize.css">
<link rel="stylesheet" href="/css/dashboard.css">
<link rel="stylesheet" href="/css/${stylesheet}">
<link rel="stylesheet" href="/css/apps-embed.css">
</head>
<body>
<main id="${rootId}"${rootClass ? ` class="${rootClass}"` : ''}></main>
<script type="application/json" id="${rootId}-config">${configJson}</script>
<script defer src="${encode(this.#embedScript(script))}"></script>
<main id="app-browser" class="dashboard"></main>
<script type="application/json" id="app-browser-config">${configJson}</script>
<script defer src="/dist/apps-embed.min.js"></script>
</body>
</html>`;
}
/**
* Embed scripts are built beside the GUI bundle, so they are served from
* wherever `gui_bundle` is (a CDN in production), with the same query.
*/
#embedScript(name: string): string {
const base = 'http://relative.invalid';
const bundle = new URL(
this.config.gui_bundle ?? '/dist/bundle.min.js',
base,
);
const script = new URL(name, bundle);
script.search = bundle.search;
return script.origin === base
? `${script.pathname}${script.search}`
: script.href;
}
/** `scriptPath` is a same-origin absolute path, like `/ext/push/worker.js`. */
registerServiceWorkerScript(scriptPath: string): void {
if (
@@ -312,7 +247,6 @@ export class PuterHomepageService extends PuterService {
ctx: { req: Request; res: Response; actor?: Actor | null },
meta: PageMeta,
launchOptions: LaunchOptions = {},
popupFrame?: PopupFrame,
): Promise<void> {
const { req, res, actor } = ctx;
@@ -337,7 +271,6 @@ export class PuterHomepageService extends PuterService {
{ req, actor: actor ?? null },
meta,
launchOptions,
popupFrame,
);
res.send(html);
}
@@ -348,7 +281,6 @@ export class PuterHomepageService extends PuterService {
ctx: { req: Request; actor: Actor | null },
meta: PageMeta,
launchOptions: LaunchOptions,
popupFrame?: PopupFrame,
): Promise<string> {
const { req, actor } = ctx;
const env = this.config.env ?? 'prod';
@@ -394,8 +326,6 @@ export class PuterHomepageService extends PuterService {
eventsNotifications: notificationsFoldInEnabled(this.config),
...meta,
launch_options: launchOptions,
// After `meta`, so nothing page-specific can name the opener.
...(popupFrame ? { embed_host_origin: popupFrame.hostOrigin } : {}),
};
const event: PuterGuiAddonsEvent = {
@@ -78,10 +78,7 @@ describe('LocalWorkerService shutdown disposal', () => {
disposals[0].mockImplementationOnce(async () => {
await held;
});
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
// The test server keeps arming timers from real callbacks while fakes
// are installed, so only what shutdown arms synchronously is checked.
const arm = vi.spyOn(globalThis, 'setTimeout');
vi.useFakeTimers();
try {
let finished = false;
const draining = Promise.resolve(service.onServerShutdown()).then(
@@ -89,13 +86,12 @@ describe('LocalWorkerService shutdown disposal', () => {
finished = true;
},
);
expect(arm.mock.calls.map(([, ms]) => ms)).toEqual([5_000]);
await vi.advanceTimersByTimeAsync(4_999);
expect(finished).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await draining;
expect(vi.getTimerCount()).toBe(0);
} finally {
arm.mockRestore();
release();
vi.useRealTimers();
}
@@ -39,7 +39,6 @@ import {
MAX_REALTIME_MESSAGE_BYTES,
MAX_UPSTREAM_MESSAGE_BYTES,
OpenAIRealtimeRelayService,
promptMessagesOf,
REALTIME_PATH,
type RealtimeUsage,
type RealtimeTranscriptionUsage,
@@ -123,65 +122,6 @@ describe('realtimeUsageRows', () => {
});
});
describe('promptMessagesOf', () => {
it('reads message text, transcripts and function output from items', () => {
expect(
promptMessagesOf({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'assistant',
content: [
{ type: 'output_text', text: 'Hi' },
{ type: 'output_audio', transcript: 'Spoken' },
{ type: 'input_audio', audio: 'AAAA' },
],
},
}),
).toEqual([
{ role: 'assistant', content: 'Hi' },
{ role: 'assistant', content: 'Spoken' },
]);
expect(
promptMessagesOf({
type: 'conversation.item.create',
item: { type: 'function_call_output', output: '{"ok":1}' },
}),
).toEqual([{ role: 'tool', content: '{"ok":1}' }]);
});
it('reads response instructions and out-of-band input', () => {
expect(
promptMessagesOf({
type: 'response.create',
response: {
instructions: 'Summarize.',
input: [
{ type: 'item_reference', id: 'item_1' },
{
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Text' }],
},
],
},
}),
).toEqual([
{ role: 'system', content: 'Summarize.' },
{ role: 'user', content: 'Text' },
]);
});
it('returns nothing for audio and other events', () => {
expect(
promptMessagesOf({ type: 'input_audio_buffer.append', audio: 'x' }),
).toEqual([]);
expect(
promptMessagesOf({ type: 'session.update', session: {} }),
).toEqual([]);
});
});
describe('realtimeTranscriptionRows', () => {
it('prices token usage by transcription model', () => {
const rows = realtimeTranscriptionRows('gpt-4o-mini-transcribe', {
@@ -1440,139 +1380,6 @@ describe('OpenAIRealtimeRelayService relay', () => {
}
});
describe('prompt checks', () => {
type Check = {
completionId: string;
allow: boolean;
parameters: { model: string; messages: unknown[] };
};
let checks: Check[];
let costs: Record<string, unknown>[];
let refuse: (check: Check) => boolean;
const validate = (_key: string, data: Check) => {
checks.push(structuredClone(data));
if (refuse(data)) data.allow = false;
};
const costCalculated = (_key: string, data: Record<string, unknown>) =>
void costs.push(data);
beforeEach(() => {
checks = [];
costs = [];
refuse = () => false;
server.clients.event.on('ai.prompt.validate', validate as never);
server.clients.event.on(
'ai.prompt.cost-calculated',
costCalculated as never,
);
});
afterEach(() => {
server.clients.event.off('ai.prompt.validate', validate as never);
server.clients.event.off(
'ai.prompt.cost-calculated',
costCalculated as never,
);
});
it('checks the text sent before each response and logs its cost under the same id', async () => {
const c = open(
`${relayUrl}?model=gpt-realtime-mini&auth_token=${user.token}`,
);
await c.waitFor('session.created');
c.ws.send(
JSON.stringify({
type: 'session.update',
session: { instructions: 'Be brief.' },
}),
);
c.ws.send(
JSON.stringify({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Hello' }],
},
}),
);
c.ws.send(JSON.stringify({ type: 'response.create' }));
await vi.waitFor(() => expect(costs).toHaveLength(1));
expect(checks).toEqual([
expect.objectContaining({
allow: true,
parameters: {
model: 'gpt-realtime-mini',
messages: [
{ role: 'system', content: 'Be brief.' },
{ role: 'user', content: 'Hello' },
],
},
}),
]);
expect(costs[0]).toMatchObject({
completionId: checks[0].completionId,
input_tokens: 7,
output_tokens: 3,
input_ucents: 7 * 60,
output_ucents: 3 * 240,
total_ucents: 7 * 60 + 3 * 240,
model_used: 'gpt-realtime-mini',
});
// A response with no new text is still logged.
c.ws.send(JSON.stringify({ type: 'response.create' }));
await vi.waitFor(() => expect(costs).toHaveLength(2));
expect(checks[1].parameters.messages).toEqual([]);
expect(costs[1].completionId).toBe(checks[1].completionId);
c.ws.close();
});
it('closes the session when the check refuses the text', async () => {
refuse = (check) =>
JSON.stringify(check.parameters.messages).includes('refuse me');
const c = open(`${relayUrl}?auth_token=${user.token}`);
await c.waitFor('session.created');
c.ws.send(
JSON.stringify({
type: 'response.create',
response: { instructions: 'refuse me' },
}),
);
expect(await c.waitFor('error')).toMatchObject({
error: { code: 'permission_denied' },
});
expect((await c.closed).code).toBe(1008);
expect(costs).toHaveLength(0);
});
it('checks pending text on its own once it passes 64 KiB', async () => {
const c = open(`${relayUrl}?auth_token=${user.token}`);
await c.waitFor('session.created');
const item = (text: string) =>
JSON.stringify({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text }],
},
});
c.ws.send(item('a'.repeat(40 * 1024)));
c.ws.send(item('b'.repeat(40 * 1024)));
c.ws.send(JSON.stringify({ type: 'response.create' }));
await vi.waitFor(() => expect(costs).toHaveLength(1));
expect(
checks.map((check) =>
(check.parameters.messages as { content: string }[]).map(
(m) => m.content[0],
),
),
).toEqual([['a'], ['b']]);
expect(costs[0].completionId).toBe(checks[1].completionId);
c.ws.close();
});
});
it('does not allocate credential limiter buckets for many unique invalid signatures', async () => {
const before = upstreamRequests.length;
const auth = vi.spyOn(server.services.auth, 'authenticate');
@@ -2860,12 +2667,8 @@ describe('OpenAIRealtimeRelayService relay', () => {
),
).toHaveLength(64),
);
// Holds are reserved and usage recorded one at a time, which a loaded
// runner takes past vi.waitFor's default second.
const settled = (check: () => Promise<void> | void) =>
vi.waitFor(check, { timeout: 5_000 });
// The pool grew one item per commit, with nothing spare at the cap.
await settled(async () =>
await vi.waitFor(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(64 * 10_896_000),
@@ -2894,7 +2697,7 @@ describe('OpenAIRealtimeRelayService relay', () => {
for (let batch = 0; batch < 8; batch++) {
for (let i = Math.max(1, batch * 8); i < (batch + 1) * 8; i++)
complete(i);
await settled(() =>
await vi.waitFor(() =>
expect(
recorded.mock.calls
.flatMap(([, rows]) => rows)
@@ -2910,13 +2713,13 @@ describe('OpenAIRealtimeRelayService relay', () => {
.filter((row) => row.usageType.includes('transcription_'))
.reduce((sum, row) => sum + row.costOverride!, 0),
).toBe(640);
await settled(async () =>
await vi.waitFor(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(2 * 10_896_000),
);
c.ws.close();
await settled(async () =>
await vi.waitFor(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(0),
@@ -17,12 +17,11 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createHash, randomUUID } from 'node:crypto';
import { createHash } from 'node:crypto';
import type { IncomingMessage, Server as HttpServer } from 'node:http';
import type { Duplex } from 'node:stream';
import express from 'express';
import type { AnyTokenPayload } from '../auth/types.js';
import type { EventMap } from '../../clients/event/types.js';
import WebSocket, { WebSocketServer, type RawData } from 'ws';
import type { Actor } from '../../core/actor.js';
import {
@@ -202,8 +201,6 @@ const RECONNECT_NOTICE_INTERVAL_MS = 60_000;
const TRANSCRIPTION_DONE =
'conversation.item.input_audio_transcription.completed';
const METERING_DRIVER = 'openai-realtime';
// Text awaiting a prompt check; past this it is checked without a response.
const MAX_PENDING_PROMPT_CHARS = 64 * 1024;
// Provider organization IDs, as OpenAI puts them in some error messages.
const ORG_ID = /\borg-[A-Za-z0-9]{8,}/g;
@@ -480,50 +477,6 @@ const clientEventRefusal = (event: RealtimeEvent): string | null => {
return null;
};
type PromptMessage = { role: string; content: string };
const itemPromptMessages = (item: unknown): PromptMessage[] => {
if (!isRecord(item)) return [];
if (item.type === 'function_call_output') {
return typeof item.output === 'string' && item.output
? [{ role: 'tool', content: item.output }]
: [];
}
if (item.type !== 'message' || !Array.isArray(item.content)) return [];
const role = typeof item.role === 'string' ? item.role : 'user';
return item.content.flatMap((part) => {
if (!isRecord(part)) return [];
const text = part.text ?? part.transcript;
return typeof text === 'string' && text
? [{ role, content: text }]
: [];
});
};
/** The text a client event adds to the model's context, as chat messages. */
export const promptMessagesOf = (event: unknown): PromptMessage[] => {
if (!isRecord(event)) return [];
if (event.type === 'conversation.item.create') {
return itemPromptMessages(event.item);
}
const config =
event.type === 'session.update'
? event.session
: event.type === 'response.create'
? event.response
: undefined;
if (!isRecord(config)) return [];
const messages: PromptMessage[] =
typeof config.instructions === 'string' && config.instructions
? [{ role: 'system', content: config.instructions }]
: [];
if (Array.isArray(config.input)) {
for (const item of config.input)
messages.push(...itemPromptMessages(item));
}
return messages;
};
/** Whichever of two pricings of the same usage costs more. */
export const costlierRows = (
a: UsageInput[],
@@ -947,14 +900,6 @@ export class OpenAIRealtimeRelayService extends PuterService {
let requested = 0;
// Credit holds of responses whose usage isn't recorded yet.
const responseHolds = new Map<string, Promise<CreditHold | null>>();
// Text sent since the last prompt check, checked when the next
// response starts. Each started response maps to the completion id
// its check logged, or null if the check refused it.
const checkPrompts =
this.clients.event.hasListeners('ai.prompt.validate');
let promptMessages: PromptMessage[] = [];
let promptChars = 0;
const responseCompletions = new Map<string, Promise<string | null>>();
// Committed input items awaiting usage, each with the transcription
// model in force at commit and the credit held for it.
const pendingTranscriptions = new Map<
@@ -1117,15 +1062,13 @@ export class OpenAIRealtimeRelayService extends PuterService {
identity?.type === 'app-under-user'
? identity.session
: undefined;
if (
!(
sessionUids?.has(sessionUid ?? '') ||
sessionUids?.has(parentUid ?? '') ||
(tokenUid &&
identity?.type === 'access-token' &&
identity.token_uid === tokenUid)
)
)
if (!(
sessionUids?.has(sessionUid ?? '') ||
sessionUids?.has(parentUid ?? '') ||
(tokenUid &&
identity?.type === 'access-token' &&
identity.token_uid === tokenUid)
))
return;
if (token) {
kv.del(realtimeAuthKey(token));
@@ -1487,82 +1430,6 @@ export class OpenAIRealtimeRelayService extends PuterService {
}
};
// Runs the host's prompt check on the pending text, which also logs
// it. A refusal closes the session.
const checkPrompt = async (): Promise<string | null> => {
const completionId = randomUUID().replaceAll('-', '').slice(0, 25);
const check: EventMap['ai.prompt.validate'] = {
username: actor!.user?.username || '',
actor,
completionId,
allow: true,
intended_service: METERING_DRIVER,
parameters: { model: billingModel, messages: promptMessages },
};
promptMessages = [];
promptChars = 0;
try {
await this.clients.event.emitAndWait(
'ai.prompt.validate',
check,
{},
);
} catch (err) {
console.warn('[realtime] prompt check failed', err);
}
if (check.allow !== false) return completionId;
reject('permission_denied', 'Prompt blocked by policy');
return null;
};
const notePrompt = (event: RealtimeEvent) => {
for (const message of promptMessagesOf(event)) {
if (
promptChars + message.content.length >
MAX_PENDING_PROMPT_CHARS
)
void checkPrompt();
promptMessages.push(message);
promptChars += message.content.length;
}
};
// Adds a response's cost to the row its prompt check logged.
const logResponseCost = async (
id: string,
rows: UsageInput[],
usage: unknown,
) => {
const completion = responseCompletions.get(id);
if (!completion) return;
responseCompletions.delete(id);
const completionId = await completion;
if (!completionId) return;
const input = { tokens: 0, ucents: 0 };
const output = { tokens: 0, ucents: 0 };
for (const row of rows) {
const side = row.usageType.endsWith('_output') ? output : input;
side.tokens += row.usageAmount;
side.ucents += row.costOverride ?? 0;
}
this.clients.event.emit(
'ai.prompt.cost-calculated',
{
completionId,
username: actor!.user?.username || '',
usage,
input_tokens: input.tokens,
output_tokens: output.tokens,
input_ucents: input.ucents,
output_ucents: output.ucents,
total_ucents: input.ucents + output.ucents,
costs_currency: 'usd-cents',
model_used: billingModel,
service_used: 'openai',
intended_service: METERING_DRIVER,
},
{},
);
};
// One transcription item's credit at `name`'s price and cost factor,
// or null when the account can't cover it. Reservations run one at a
// time, so a session's own holds don't race each other's balance check.
@@ -1698,8 +1565,6 @@ export class OpenAIRealtimeRelayService extends PuterService {
if (typeof id !== 'string') break;
inFlightIds.add(id);
holdResponse(id);
if (checkPrompts)
responseCompletions.set(id, checkPrompt());
if (closed) {
upstream?.send(
JSON.stringify({
@@ -1710,15 +1575,18 @@ export class OpenAIRealtimeRelayService extends PuterService {
}
break;
}
case 'response.done': {
case 'response.done':
inFlight = Math.max(0, inFlight - 1);
const usage = event.response?.usage ?? undefined;
const rows = realtimeUsageRows(billingModel, usage);
meter(rows, takeHold(event.response?.id));
if (typeof event.response?.id === 'string') {
inFlightIds.delete(event.response.id);
void logResponseCost(event.response.id, rows, usage);
}
meter(
realtimeUsageRows(
billingModel,
event.response?.usage ?? undefined,
),
takeHold(event.response?.id),
);
if (inFlight === 0) {
onIdle?.();
if (
@@ -1730,7 +1598,6 @@ export class OpenAIRealtimeRelayService extends PuterService {
endUpstream();
}
break;
}
case 'input_audio_buffer.speech_started': {
// Detected speech is committed when it stops, from where
// the provider says it began.
@@ -1972,7 +1839,6 @@ export class OpenAIRealtimeRelayService extends PuterService {
pending.shift();
pendingBytes -= (next.data as Buffer).length;
if (event.type === 'response.create') requested++;
if (checkPrompts) notePrompt(event);
sendUpstream(next.data, next.isBinary);
}
return undefined;
+8 -10
View File
@@ -1,11 +1,11 @@
# OpenAI Realtime relay
The relay serves `/puterai/openai/v1/realtime` on the API host. The SDK exposes
it through [`puter.ai.realtime()`](../../../docs/src/AI/realtime.md).
it through [`puter.ai.convo()`](../../../docs/src/AI/convo.md).
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime-websocket.md).
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime.md).
## Transport
@@ -27,7 +27,7 @@ The socket opens before authentication completes. Authentication and model
failures arrive as OpenAI-shaped error events followed by a close frame.
```js
const conversation = await puter.ai.realtime({ output: ['text'] });
const conversation = await puter.ai.convo({ output: ['text'] });
conversation.on('error', (event) => console.error(event));
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
@@ -105,13 +105,11 @@ excludes outstanding holds and accepts fractional positive credit. Admission of
new billable work continues to use the atomic hold path, which includes every
outstanding reservation.
When the host listens for `ai.prompt.validate`, each response that starts runs
it on the text the client sent since the previous check: session and response
instructions, message text and transcripts, and function call output, as chat
messages. The response's cost follows as `ai.prompt.cost-calculated` under the
same completion id. A refusal closes the session with `permission_denied`; the
response may already be streaming by then. Pending text past 64 KiB is checked
on its own. Audio is not checked.
Text, transcripts and raw audio are forwarded without new content logging.
The relay does not invoke `ai.prompt.validate`. A realtime adapter needs the host
listeners' chat payload and denial contracts before that hook can safely apply
to instructions and conversation text. Raw audio and generated transcripts need
separate policy decisions.
Credential checks run in batches of at most 16 with no overlapping sweeps.
Session and access-token revocation events close affected sockets and invalidate
+4 -9
View File
@@ -1542,22 +1542,18 @@ describe('AppStore detailed stats', () => {
let db;
const APP_UID = `app-stats-${Date.now()}`;
// The windows come from the clock, so it is pinned: mid-week and
// mid-month, and minutes clear of midnight in any time zone.
const NOW = new Date('2026-06-17T12:07:30Z');
const nowSeconds = Math.floor(NOW.getTime() / 1000);
const nowSeconds = Math.floor(Date.now() / 1000);
beforeAll(async () => {
server = await setupTestServer();
appStore = server.stores.app;
db = server.clients.db;
await clearAppCache(server.clients.redis);
vi.useFakeTimers({ toFake: ['Date'], now: NOW });
// Two users in one hour. Windows end at now, exclusive.
// Two users; the repeat shares a timestamp so it is always same-hour.
for (const [userId, offset] of [
[1, 60],
[1, 60],
[1, 0],
[1, 0],
[2, 120],
]) {
await db.write(
@@ -1568,7 +1564,6 @@ describe('AppStore detailed stats', () => {
});
afterAll(async () => {
vi.useRealTimers();
await server?.shutdown();
});
-3
View File
@@ -154,9 +154,6 @@ export const setupTestServer = async (
redis: { useMock: true },
// Suites run system jobs themselves, not on the poll timer.
jobs: { enabled: false },
// The health loop's timed `SELECT 1` would land in tests that
// count queries.
server_health: { disabled_checks: ['database-liveness'] },
s3: { localConfig: { inMemory: true } },
no_default_user: true,
no_devwatch: true,
+8 -8
View File
@@ -256,7 +256,12 @@ export interface IPreludeConfig {
* an RCS agent provisioned in the Prelude account to actually use RCS.
*/
preferredChannel?:
'sms' | 'rcs' | 'whatsapp' | 'viber' | 'zalo' | 'telegram';
| 'sms'
| 'rcs'
| 'whatsapp'
| 'viber'
| 'zalo'
| 'telegram';
}
/**
@@ -1101,11 +1106,7 @@ interface IConfigOptional {
builtin_apps: Record<string, string>;
/** Force the bundled GUI even in dev. Default: false. */
use_bundled_gui: boolean;
/**
* Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. The
* `/embed/*` pages load `apps-embed.min.js` and `feedback-embed.min.js`
* from the same directory.
*/
/** Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. */
gui_bundle: string;
/** Override the GUI CSS path when bundled. Default: `/dist/bundle.min.css`. */
gui_css: string;
@@ -1392,8 +1393,7 @@ export interface ServerDrainInfo {
}
export interface WithCostsReporting extends WithLifecycle {
getReportedCosts?: () =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getReportedCosts?: () => // eslint-disable-next-line @typescript-eslint/no-explicit-any
| Promise<Record<string, any>[]>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
| Record<string, any>[];
+3 -10
View File
@@ -37,9 +37,6 @@ const repoRoot = path.resolve(backendDir, '../..');
const isPgmockMode =
(process.env.PUTER_TEST_DB_ENGINE ?? '').toLowerCase() === 'postgres';
const pgmockTimeoutMs = 600_000;
// Loaded CI runners stall timers well past the 5 s / 10 s defaults; a real
// hang still fails, just later.
const ciTimeouts = { testTimeout: 20_000, hookTimeout: 60_000 };
// Tests that always boot pgmock regardless of PUTER_TEST_DB_ENGINE. Too slow
// for CI; run locally or via `npm run test:backend:postgres`.
@@ -106,11 +103,9 @@ export const lowerDecoratorsPlugin = {
loader: 'ts',
target: 'es2024',
sourcefile: id,
sourcemap: 'external',
sourcemap: 'inline',
});
// Without the map, coverage and stack traces report esbuild's
// output lines instead of the source's.
return { code: result.code, map: result.map };
return { code: result.code, map: null };
},
};
@@ -150,9 +145,7 @@ export default defineConfig(({ mode }) => ({
hookTimeout: pgmockTimeoutMs,
fileParallelism: false,
}
: isCi
? ciTimeouts
: {}),
: {}),
coverage: {
provider: 'v8',
reporter: isCi
+5 -13
View File
@@ -247,10 +247,10 @@ function generateTableOfContentsHTML (htmlContent, title) {
html += '<nav class="toc-nav">';
const cleanTitle = removeTags(title);
html += `<a href="#" class="toc-link toc-level-1" data-level="1">${breakAfterDots(cleanTitle)}</a>`;
html += `<a href="#" class="toc-link toc-level-1" data-level="1">${cleanTitle}</a>`;
for ( const heading of headings ) {
html += `<a href="#${heading.slug}" class="toc-link toc-level-${heading.level}" data-level="${heading.level}">${breakAfterDots(heading.text)}</a>`;
html += `<a href="#${heading.slug}" class="toc-link toc-level-${heading.level}" data-level="${heading.level}">${heading.text}</a>`;
}
html += '</nav>';
@@ -457,12 +457,10 @@ function generateDocsHTML (filePath, rootDir, page, isIndex = false) {
html += '</div>';
// content
html += `<div id="docs-content-${page.slug ?? ''}" class="docs-content col-xl-7 col-lg-7 col-md-12 col-sm-12 col-xs-12">`;
// title, with the context menu beside it
const pageTitle = breakAfterDots(page.page_title ?? page.title);
html += '<div class="page-title-row">';
html += `<h1>${page.icon ? `<img src="/${baseURL}${page.icon}" style="opacity:0.5; width: 24px; height: 24px; margin-right: 10px;">` : '' }${pageTitle}</h1>`;
// context menu
html += generateMenuHTML();
html += '</div>';
html += `<h1>${page.icon ? `<img src="/${baseURL}${page.icon}" style="opacity:0.5; width: 24px; height: 24px; margin-right: 10px;">` : '' }${page.page_title ?? page.title}</h1>`;
// Platform compatibility badges
html += generatePlatformCompatibilityHTML(frontMatter);
html += '<hr class="hr-inset">';
@@ -854,12 +852,6 @@ function removeTags (html) {
return html.replace(/<[^>]*>?/gm, '');
}
// Let a long title wrap after a dot, so `puter.auth.getDetailedAppUsage()`
// never splits inside the method name.
function breakAfterDots (html) {
return html.replace(/\.(?=\w)/g, '.<wbr>');
}
// Replace '/path/to/root-directory' with the path to your root directory
generateDocumentation('./src');
generateRedirects();
+8 -8
View File
@@ -194,18 +194,18 @@ Choose a model and compare provider rates in the [AI model directory](https://de
These AI features are supported out of the box when using Puter.js:
- **[`puter.ai.chat()`](/AI/chat/)** - Chat with AI models like Claude, GPT, and others
- **[`puter.ai.txt2img()`](/AI/txt2img/)** - Generate images from text descriptions
- **[`puter.ai.txt2speech()`](/AI/txt2speech/)** - Convert text to speech
- **[`puter.ai.speech2txt()`](/AI/speech2txt/)** - Transcribe audio recordings into text
- **[`puter.ai.img2txt()`](/AI/img2txt/)** - Extract text from images (OCR)
- **[`puter.ai.txt2vid()`](/AI/txt2vid/)** - Generate short video clips from text or a reference image with Wan, Seedance, Veo, Kling, MiniMax H3 and other models, or edit a video you supply with Gemini Omni, FLUX 3 or Kling Omni
- **[`puter.ai.speech2speech()`](/AI/speech2speech/)** - Convert speech in one voice to another voice
- **[`puter.ai.realtime()`](/AI/realtime/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
- **[Realtime WebSocket API](/AI/realtime-websocket/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
- **[`puter.ai.listModels()`](/AI/listModels/)** - List available AI chat models (and providers) that Puter currently exposes.
- **[`puter.ai.listModelProviders()`](/AI/listModelProviders/)** - List the AI providers that Puter currently exposes.
- **[`puter.ai.txt2img()`](/AI/txt2img/)** - Generate images from text descriptions
- **[`puter.ai.img2txt()`](/AI/img2txt/)** - Extract text from images (OCR)
- **[`puter.ai.txt2speech()`](/AI/txt2speech/)** - Convert text to speech
- **[`puter.ai.txt2speech.listEngines()`](/AI/txt2speech.listEngines/)** - List available TTS engines/models
- **[`puter.ai.txt2speech.listVoices()`](/AI/txt2speech.listVoices/)** - List available TTS voices
- **[`puter.ai.speech2speech()`](/AI/speech2speech/)** - Convert speech in one voice to another voice
- **[`puter.ai.txt2vid()`](/AI/txt2vid/)** - Generate short video clips from text or a reference image with Wan, Seedance, Veo, Kling, MiniMax H3 and other models, or edit a video you supply with Gemini Omni, FLUX 3 or Kling Omni
- **[`puter.ai.speech2txt()`](/AI/speech2txt/)** - Transcribe audio recordings into text
- **[Realtime WebSocket API](/AI/realtime/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
- **[`puter.ai.convo()`](/AI/convo/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
## Examples
+18 -18
View File
@@ -29,24 +29,24 @@ An object containing the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `model` | `String` | The model you want to use for the completion. If not specified, defaults to `gpt-5.4-nano`. More than 500 models are available from providers including OpenAI, Anthropic, Google, Alibaba Cloud, xAI, Mistral, OpenRouter, Infron, and others. For a full list, see the [AI models list](https://developer.puter.com/ai/models/) page. |
| `stream` | `Boolean` | A boolean indicating whether you want to stream the completion. Defaults to `false`. |
| `max_tokens` | `Number` | The maximum number of tokens to generate in the completion. By default, the specific model's maximum is used. |
| `temperature` | `Number` | A number between 0 and 2 indicating the randomness of the completion. Lower values make the output more focused and deterministic, while higher values make it more random. By default, the model's own temperature is used. See [Model-specific features](#model-specific-features). |
| `reasoning_effort` / `reasoning.effort` | `String` | Controls how much effort reasoning models spend thinking. Supported values: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. Lower values give faster responses with less reasoning. OpenAI models, Moonshot's Kimi K3.1 Pro models, Meta's Muse Spark models, `gemini-4-argon`, `gemini-3.1-flash-lite` and `gemini-3-flash-preview` only. See [Model-specific features](#model-specific-features). |
| `thinking` | `Object \| null` | Extended-thinking control: `{ type: "adaptive" \| "enabled" \| "disabled" \| "between_tools", budgetTokens?, display? }`. Pass `null` to send no thinking configuration at all (the model's own default); leaving it unset falls back to the legacy derivation from `reasoning_effort`. `budgetTokens` only applies to `type: "enabled"`. |
| `verbosity` / `text.verbosity` | `String` | Controls how long or short responses are. Supported values: `low`, `medium`, and `high`. Lower values give shorter responses. OpenAI models only. |
| `tools` | `Array` | Function definitions the AI can call. See [Function Calling](#function-calling) for details. |
| `toolChoice` | `String \| Object` | Which tool, if any, the model must call. Pass `"auto"` (the model decides), `"none"` (never call a tool), `"required"` (call at least one), or an object naming a specific tool: `{ type: "tool", name: "..." }`. Requires `tools`. |
| `parallelToolCalls` | `Boolean` | Whether the model may call more than one tool in a single turn. Left unset, tool calls run one at a time. |
| `streamToolInput` | `Boolean` | Streaming only. When `true`, a tool call's arguments arrive incrementally as `tool_use_start` / `tool_input_delta` chunks instead of a single `tool_use` chunk once the call completes. |
| `normalize` | `Boolean` | Controls the format of the non-streaming response. See [Response normalization](#response-normalization). |
| `compaction` | `Boolean \| Object` | Opt into inline context compaction for long conversations. See [Compaction](#compaction). |
| `signal` | `AbortSignal` | Abort the request, including while waiting for the next streamed chunk. Cancellation rejects with the signal reason (normally an `AbortError`). |
| `provider` | `String` | Pin the request to a specific provider, for example `openrouter` or `infron`. Without it, Puter selects a provider for the requested model. Call [`puter.ai.listModelProviders()`](/AI/listModelProviders) for the available values, and [`puter.ai.listModels(provider)`](/AI/listModels) for the models a given provider serves. See [Providers](#providers). |
| `fallback` | `Boolean` | Set to `false` to fail the request when the first provider tried fails, instead of retrying it on another provider that serves the same model. Defaults to `true`. See [Providers](#providers). |
| `outputFormat` | `Object` | Constrains the response to a JSON schema: `{ type: "json_schema", schema, name?, strict? }`. |
| `stopSequences` | `Array<String>` | Up to the model's limit of strings; generation stops the moment one of them appears in the output. |
| `model` | String | The model you want to use for the completion. If not specified, defaults to `gpt-5.4-nano`. More than 500 models are available from providers including OpenAI, Anthropic, Google, Alibaba Cloud, xAI, Mistral, OpenRouter, Infron, and others. For a full list, see the [AI models list](https://developer.puter.com/ai/models/) page. |
| `stream` | Boolean | A boolean indicating whether you want to stream the completion. Defaults to `false`. |
| `max_tokens` | Number | The maximum number of tokens to generate in the completion. By default, the specific model's maximum is used. |
| `temperature` | Number | A number between 0 and 2 indicating the randomness of the completion. Lower values make the output more focused and deterministic, while higher values make it more random. By default, the model's own temperature is used. See [Model-specific features](#model-specific-features). |
| `reasoning_effort` / `reasoning.effort` | String | Controls how much effort reasoning models spend thinking. Supported values: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. Lower values give faster responses with less reasoning. OpenAI models, Moonshot's Kimi K3.1 Pro models, Meta's Muse Spark models, `gemini-4-argon`, `gemini-3.1-flash-lite` and `gemini-3-flash-preview` only. See [Model-specific features](#model-specific-features). |
| `thinking` | Object \| null | Extended-thinking control: `{ type: "adaptive" \| "enabled" \| "disabled" \| "between_tools", budgetTokens?, display? }`. Pass `null` to send no thinking configuration at all (the model's own default); leaving it unset falls back to the legacy derivation from `reasoning_effort`. `budgetTokens` only applies to `type: "enabled"`. |
| `verbosity` / `text.verbosity` | String | Controls how long or short responses are. Supported values: `low`, `medium`, and `high`. Lower values give shorter responses. OpenAI models only. |
| `tools` | Array | Function definitions the AI can call. See [Function Calling](#function-calling) for details. |
| `toolChoice` | String \| Object | Which tool, if any, the model must call. Pass `"auto"` (the model decides), `"none"` (never call a tool), `"required"` (call at least one), or an object naming a specific tool: `{ type: "tool", name: "..." }`. Requires `tools`. |
| `parallelToolCalls` | Boolean | Whether the model may call more than one tool in a single turn. Left unset, tool calls run one at a time. |
| `streamToolInput` | Boolean | Streaming only. When `true`, a tool call's arguments arrive incrementally as `tool_use_start` / `tool_input_delta` chunks instead of a single `tool_use` chunk once the call completes. |
| `normalize` | Boolean | Controls the format of the non-streaming response. See [Response normalization](#response-normalization). |
| `compaction` | Boolean \| Object | Opt into inline context compaction for long conversations. See [Compaction](#compaction). |
| `signal` | AbortSignal | Abort the request, including while waiting for the next streamed chunk. Cancellation rejects with the signal reason (normally an `AbortError`). |
| `provider` | String | Pin the request to a specific provider, for example `openrouter` or `infron`. Without it, Puter selects a provider for the requested model. Call [`puter.ai.listModelProviders()`](/AI/listModelProviders) for the available values, and [`puter.ai.listModels(provider)`](/AI/listModels) for the models a given provider serves. See [Providers](#providers). |
| `fallback` | Boolean | Set to `false` to fail the request when the first provider tried fails, instead of retrying it on another provider that serves the same model. Defaults to `true`. See [Providers](#providers). |
| `outputFormat` | Object | Constrains the response to a JSON schema: `{ type: "json_schema", schema, name?, strict? }`. |
| `stopSequences` | Array of String | Up to the model's limit of strings; generation stops the moment one of them appears in the output. |
Some models accept additional options or handle these options differently. See [Model-specific features](#model-specific-features).
+143
View File
@@ -0,0 +1,143 @@
---
title: puter.ai.convo()
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
platforms: [websites, apps, nodejs, workers]
---
The conversation API prepares a realtime session, verifies Puter sign-in, and lets you connect when your app is ready. Realtime conversations require a paid Puter plan; usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime/).
## Syntax
```js
const conversation = await puter.ai.convo(options = {});
await conversation.connect();
```
## Parameters
The options object accepts these fields.
| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `model` | String | `gpt-realtime-2.1-mini` | Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
| `instructions` | String | Provider default | Session instructions, up to 8192 characters. |
| `output` | Array of Strings | `['audio']` | Accepts `['text']`, `['audio']`, or both. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
| `voice` | String | Provider default | OpenAI voice identifier, up to 128 characters. |
| `turnDetection` | Boolean | `true` | Whether the provider detects the end of spoken turns automatically. Set to `false` for manual audio commits. |
## Return value
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
The conversation exposes these properties and methods.
| Member | Behavior |
| --- | --- |
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
| `model` | Resolved model name. |
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
| `send(event)` | Sends a native OpenAI JSON event. |
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
| `off(type, handler)` | Removes a listener. |
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
## Convenience events
The conversation emits these events alongside native events.
| Event | Fields |
| --- | --- |
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
| `text` | `delta`, `responseId` |
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
| `turn.done` | `responseId`, native provider `usage`, `status` |
| `close` | `code`, `reason` |
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
## Browser media
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
| Member | Behavior |
| --- | --- |
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
| `microphone.unmute()` | Enables capture tracks and forwarding. |
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
| `speaker.stop()` | Clears playback and releases its audio context. |
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
## Errors and limits
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
## Examples
A text conversation uses convenience methods for input and streamed output.
```js
const conversation = await puter.ai.convo({
output: ['text'],
instructions: 'Keep replies short.',
});
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
conversation.on('error', (event) => console.error(event));
await conversation.connect();
conversation.sendText('Say hello in three words.');
```
A voice conversation enables the microphone and speaker after connection.
```js
const conversation = await puter.ai.convo();
conversation.on('transcript', ({ role, text }) => console.log(role, text));
conversation.on('error', (event) => console.error(event));
await conversation.connect();
await conversation.speaker.start();
await conversation.microphone.start();
// To interrupt a response and submit a replacement text turn:
await conversation.interrupt();
conversation.sendText('Actually, make it Wednesday.');
// When the user ends the conversation:
conversation.close();
```
-2
View File
@@ -22,8 +22,6 @@ A `Promise` that will resolve to an array of string containing each AI providers
## Examples
### List all model providers
```html;ai-list-model-providers
<html>
<body>
+2 -6
View File
@@ -43,15 +43,13 @@ Example model entry:
]
```
<div class="info">Successful results are cached for 60 seconds per provider.</div>
## Errors
Network and server failures reject the promise; they do not resolve to an empty
catalogue. Network failures use `{ message, code: "network_error" }`, invalid
catalogue responses use `invalid_response`, idle timeouts use `request_timeout`,
and server errors pass through unchanged.
<div class="info">Successful results are cached for 60 seconds per provider.</div>
## Model variants
Some models have variants. A variant is the same model with a different price, rate limit, or speed. The variant is a suffix on the model ID, separated by a colon.
@@ -66,8 +64,6 @@ The model ID without a suffix is the standard variant. Not every model has varia
## Examples
### List all models
```html;ai-list-models
<html>
<body>
-126
View File
@@ -1,126 +0,0 @@
---
title: Realtime WebSocket API (Beta)
description: Connect to OpenAI realtime conversations through Puter without puter.js.
platforms: [websites, apps, nodejs, workers]
---
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter.
Puter authenticates the user and charges their account for usage.
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.realtime()`](/AI/realtime/).
## Connection and authentication
Connect to this URL on the Puter API host:
```text
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
```
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
```text
Authorization: Bearer <PUTER_TOKEN>
```
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
## Text example
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
```js
import WebSocket from 'ws';
const socket = new WebSocket(
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
);
const send = (event) => socket.send(JSON.stringify(event));
socket.on('message', (data) => {
const event = JSON.parse(data.toString());
if (event.type === 'session.created') {
send({
type: 'session.update',
session: {
type: 'realtime',
output_modalities: ['text'],
instructions: 'Keep replies short.',
},
});
}
if (event.type === 'session.updated') {
send({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Hello!' }],
},
});
send({ type: 'response.create' });
}
if (event.type === 'response.output_text.delta')
process.stdout.write(event.delta);
if (event.type === 'error')
console.error(event.error);
if (event.type === 'response.done')
socket.close();
});
socket.on('error', console.error);
socket.on('close', (code, reason) => console.log(code, reason.toString()));
```
## Events, audio, and interruption
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
## Server restarts
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
```json
{
"type": "puter.reconnect",
"event_id": "event_puter_1767225600000",
"reason": "server_restarting",
"close_in_ms": 90000
}
```
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
## Errors, billing, and limits
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
+95 -122
View File
@@ -1,151 +1,124 @@
---
title: puter.ai.realtime()
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
title: Realtime WebSocket API (Beta)
description: Connect to OpenAI realtime conversations through Puter without puter.js.
platforms: [websites, apps, nodejs, workers]
---
Prepares a realtime OpenAI conversation that your app can connect to when it's ready.
Preparing the conversation verifies Puter sign-in. Realtime conversations require a paid Puter plan, and usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter. Puter authenticates the user and charges their account for usage.
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime-websocket/).
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.convo()`](/AI/convo/).
## Syntax
## Connection and authentication
```js
const conversation = await puter.ai.realtime(options = {});
await conversation.connect();
Connect to this URL on the Puter API host:
```text
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
```
## Parameters
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
#### `options` (Object) (Optional)
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
The options object accepts these fields.
```text
Authorization: Bearer <PUTER_TOKEN>
```
| Option | Type | Description |
|--------|------|-------------|
| `model` | `String` | The realtime model. Defaults to `gpt-realtime-2.1-mini`. Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
| `instructions` | `String` | Session instructions, up to 8192 characters. Defaults to the provider's default. |
| `output` | `Array<String>` | Accepts `['text']`, `['audio']`, or both. Defaults to `['audio']`. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
| `voice` | `String` | OpenAI voice identifier, up to 128 characters. Defaults to the provider's default. |
| `turnDetection` | `Boolean` | Whether the provider detects the end of spoken turns automatically. Defaults to `true`. Set to `false` for manual audio commits. |
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
## Return value
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
The conversation exposes these properties and methods.
## Text example
| Member | Behavior |
| --- | --- |
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
| `model` | Resolved model name. |
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
| `send(event)` | Sends a native OpenAI JSON event. |
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
| `off(type, handler)` | Removes a listener. |
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
## Errors and limits
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
## Convenience events
The conversation emits these events alongside native events.
| Event | Fields |
| --- | --- |
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
| `text` | `delta`, `responseId` |
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
| `turn.done` | `responseId`, native provider `usage`, `status` |
| `close` | `code`, `reason` |
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
## Browser media
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
| Member | Behavior |
| --- | --- |
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
| `microphone.unmute()` | Enables capture tracks and forwarding. |
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
| `speaker.stop()` | Clears playback and releases its audio context. |
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
## Examples
### Have a text conversation
A text conversation uses convenience methods for input and streamed output.
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
```js
const conversation = await puter.ai.realtime({
output: ['text'],
instructions: 'Keep replies short.',
import WebSocket from 'ws';
const socket = new WebSocket(
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
);
const send = (event) => socket.send(JSON.stringify(event));
socket.on('message', (data) => {
const event = JSON.parse(data.toString());
if (event.type === 'session.created') {
send({
type: 'session.update',
session: {
type: 'realtime',
output_modalities: ['text'],
instructions: 'Keep replies short.',
},
});
}
if (event.type === 'session.updated') {
send({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content: [{ type: 'input_text', text: 'Hello!' }],
},
});
send({ type: 'response.create' });
}
if (event.type === 'response.output_text.delta')
process.stdout.write(event.delta);
if (event.type === 'error')
console.error(event.error);
if (event.type === 'response.done')
socket.close();
});
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
conversation.on('error', (event) => console.error(event));
await conversation.connect();
conversation.sendText('Say hello in three words.');
socket.on('error', console.error);
socket.on('close', (code, reason) => console.log(code, reason.toString()));
```
### Have a voice conversation
## Events, audio, and interruption
A voice conversation enables the microphone and speaker after connection.
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
```js
const conversation = await puter.ai.realtime();
conversation.on('transcript', ({ role, text }) => console.log(role, text));
conversation.on('error', (event) => console.error(event));
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
await conversation.connect();
await conversation.speaker.start();
await conversation.microphone.start();
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
// To interrupt a response and submit a replacement text turn:
await conversation.interrupt();
conversation.sendText('Actually, make it Wednesday.');
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
// When the user ends the conversation:
conversation.close();
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
## Server restarts
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
```json
{
"type": "puter.reconnect",
"event_id": "event_puter_1767225600000",
"reason": "server_restarting",
"close_in_ms": 90000
}
```
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
## Errors, billing, and limits
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
+2 -2
View File
@@ -54,7 +54,7 @@ Example response:
## Examples
### List engines for a specific provider
<strong class="example-title">List engines for a specific provider</strong>
```html;ai-txt2speech-list-engines
<html>
@@ -73,7 +73,7 @@ Example response:
</html>
```
### List engines using options object
<strong class="example-title">List engines using options object</strong>
```js
const engines = await puter.ai.txt2speech.listEngines({ provider: 'elevenlabs' });
+4 -6
View File
@@ -4,9 +4,7 @@ description: List available TTS voices, optionally filtered by provider.
platforms: [websites, apps, nodejs, workers]
---
Returns the voices available from a TTS provider.
Each voice entry includes metadata such as language, category, and supported models.
Returns the voices available from a TTS provider. Each voice entry includes metadata such as language, category, and supported models.
## Syntax
@@ -54,7 +52,7 @@ Example response (with `provider: 'all'`):
## Examples
### List voices for a provider
<strong class="example-title">List voices for a provider</strong>
```html;ai-txt2speech-list-voices
<html>
@@ -73,7 +71,7 @@ Example response (with `provider: 'all'`):
</html>
```
### List all default (AWS Polly) voices
<strong class="example-title">List all default (AWS Polly) voices</strong>
```js
const voices = await puter.ai.txt2speech.listVoices();
@@ -83,7 +81,7 @@ for (const voice of voices) {
}
```
### List Gemini voices
<strong class="example-title">List Gemini voices</strong>
```js
const voices = await puter.ai.txt2speech.listVoices({ provider: 'gemini' });
+1 -3
View File
@@ -4,9 +4,7 @@ description: Convert text to speech with AI using multiple languages, voices, an
platforms: [websites, apps, nodejs, workers]
---
Converts text into speech using AI.
It supports multiple languages and voices.
Converts text into speech using AI. Supports multiple languages and voices.
## Syntax
+2 -2
View File
@@ -183,9 +183,9 @@ These Apps API are supported out of the box when using Puter.js:
- **[`puter.apps.create()`](/Apps/create/)** - Create a new application
- **[`puter.apps.list()`](/Apps/list/)** - List all applications
- **[`puter.apps.get()`](/Apps/get/)** - Get information about a specific application
- **[`puter.apps.update()`](/Apps/update/)** - Update application settings
- **[`puter.apps.delete()`](/Apps/delete/)** - Delete an application
- **[`puter.apps.update()`](/Apps/update/)** - Update application settings
- **[`puter.apps.get()`](/Apps/get/)** - Get information about a specific application
- **[`puter.apps.checkName()`](/Apps/checkName/)** - Check whether an app name is available
## Examples
+2 -4
View File
@@ -4,9 +4,7 @@ description: Check whether an app name is still available.
platforms: [websites, apps, nodejs, workers]
---
Checks whether an app name is free, without creating anything.
App names are unique across all Puter accounts, so a name is free only when no app on any account uses it. Useful before calling [`puter.apps.create()`](/Apps/create/), which rejects when the name is already taken.
Checks whether an app name is free, without creating anything. App names are unique across all Puter accounts, so a name is free only when no app on any account uses it. Useful before calling [`puter.apps.create()`](/Apps/create/), which rejects when the name is already taken.
## Syntax
@@ -26,7 +24,7 @@ A `Promise` that will resolve to an object describing the name's availability.
## Examples
### Check a name before creating the app
<strong class="example-title">Check a name before creating the app</strong>
```html
<html>
+13 -17
View File
@@ -4,9 +4,7 @@ description: Create apps in the Puter desktop environment.
platforms: [websites, apps, nodejs, workers]
---
Creates a Puter app with the given name.
The app will be created in the user's apps, and will be accessible to this app. The app will be created with no permissions, and will not be able to access any data until permissions are granted to it.
Creates a Puter app with the given name. The app will be created in the user's apps, and will be accessible to this app. The app will be created with no permissions, and will not be able to access any data until permissions are granted to it.
## Syntax
@@ -41,19 +39,17 @@ The title of the app. If this parameter is not provided, the app will be created
An object containing the options for the app to create. The object can contain the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `name` | `String` | Required. The name of the app to create. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected. |
| `indexURL` | `String` | Required. The URL of the app's index page. This URL must be accessible to the user. If it's missing, the promise will be rejected. |
| `title` | `String` | The human-readable title of the app. If it's missing, the app will be created with `name` as its title. |
| `description` | `String` | The description of the app aimed at the end user. |
| `icon` | `String` | The new icon of the app. |
| `filetypeAssociations` | `Array<String>` | An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extensions and MIME types are supported. For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters. |
| `maximizeOnStart` | `Boolean` | Whether the app should be maximized when it is started. Defaults to `false`. |
| `background` | `Boolean` | Whether the app should run in the background. Defaults to `false`. |
| `feedbackEnabled` | `Boolean` | Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Defaults to `false`. |
| `metadata` | `Object` | An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON. |
| `dedupeName` | `Boolean` | Whether to deduplicate the app name if it already exists. Defaults to `false`. |
- `name` (String) (required): The name of the app to create. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected.
- `indexURL` (String) (required): The URL of the app's index page. This URL must be accessible to the user. If this parameter is not provided, the promise will be rejected.
- `title` (String) (optional): The human-readable title of the app. If this parameter is not provided, the app will be created with `name` as its title.
- `description` (String) (optional): The description of the app aimed at the end user.
- `icon` (String) (optional): The new icon of the app.
- `maximizeOnStart` (Boolean) (optional): Whether the app should be maximized when it is started. Defaults to `false`.
- `filetypeAssociations` (Array<String>) (optional): An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extentions and MIME types are supported; For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters.
- `dedupeName` (Boolean) (optional) - Whether to deduplicate the app name if it already exists. Defaults to `false`.
- `background` (Boolean) (optional) - Whether the app should run in the background. Defaults to `false`.
- `feedbackEnabled` (Boolean) (optional) - Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Defaults to `false`.
- `metadata` (Object) (optional) - An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON.
## Return value
@@ -61,7 +57,7 @@ A `Promise` that will resolve to the [`CreateAppResult`](/Objects/createappresul
## Examples
### Create an app pointing to example.com
<strong class="example-title">Create an app pointing to example.com</strong>
```html;app-create
<html>
+1 -1
View File
@@ -24,7 +24,7 @@ A `Promise` that will resolve to an object `{ success: true, uid: <app uid> }` i
## Examples
### Create a random app then delete it
<strong class="example-title">Create a random app then delete it</strong>
```html;app-delete
<html>
+6 -9
View File
@@ -4,9 +4,7 @@ description: Retrieve details of your Puter app.
platforms: [websites, apps, nodejs, workers]
---
Returns an app with the given name.
If the app does not exist, the promise will be rejected.
Returns an app with the given name. If the app does not exist, the promise will be rejected.
## Syntax
@@ -21,14 +19,13 @@ puter.apps.get(name, options)
The name of the app to get.
#### `options` (Object) (optional)
### options (optional)
An object containing the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `icon_size` | `Number \| null` | An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size). |
| `stats_period` | `String` | The period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time). |
- `stats_period` (optional): A string representing the period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time).
- `icon_size` (optional): An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size).
## Return value
@@ -36,7 +33,7 @@ A `Promise` that will resolve to the [`App`](/Objects/app/) object with the give
## Examples
### Create a random app then get it
<strong class="example-title">Create a random app then get it</strong>
```html;app-get
<html>
+15 -13
View File
@@ -4,9 +4,7 @@ description: List all apps in your Puter account.
platforms: [websites, apps, nodejs, workers]
---
Returns an array of all apps belonging to the user and that this app has access to.
If the user has no apps, the array will be empty.
Returns an array of all apps belonging to the user and that this app has access to. If the user has no apps, the array will be empty.
## Syntax
@@ -21,15 +19,19 @@ puter.apps.list(options)
An object containing the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum number of apps to return in a single call. |
| `cursor` | `String \| null` | Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one. |
| `stream` | `Boolean` | If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`. |
| `includeTotal` | `Boolean` | If `true`, the paginated result includes a `total` count of the user's apps. |
| `offset` | `Number` | Skips the given number of apps. Prefer `cursor` for paging through large lists. |
| `icon_size` | `Number \| null` | An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size). |
| `stats_period` | `String` | The period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time). |
- `stats_period` (optional): A string representing the period for which to get the user and open count. Possible values are `today`, `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`, `last_year`, `month_to_date`, `year_to_date`, `last_12_months`. Default is `all` (all time).
- `icon_size` (optional): An integer representing the size of the icons to return. Possible values are `null`, `16`, `32`, `64`, `128`, `256`, and `512`. Default is `null` (the original size).
- `limit` (optional): Maximum number of apps to return in a single call.
- `offset` (optional): Skips the given number of apps. Prefer `cursor` for paging through large lists.
- `cursor` (optional): Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one.
- `includeTotal` (optional): If `true`, the paginated result includes a `total` count of the user's apps.
- `stream` (optional): If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`.
## Return value
@@ -55,7 +57,7 @@ for await (const page of puter.apps.list({ stream: true })) {
## Examples
### Create 3 random apps and then list them
<strong class="example-title">Create 3 random apps and then list them</strong>
```html;app-list
<html>
+11 -14
View File
@@ -17,19 +17,16 @@ The name of the app to update.
#### `attributes` (required)
An object containing the attributes to update. The object can contain the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `title` | `String` | The new title of the app. |
| `indexURL` | `String` | The new URL of the app's index page. This URL must be accessible to the user. |
| `description` | `String` | The new description of the app aimed at the end user. |
| `icon` | `String` | The new icon of the app. |
| `name` | `String` | The new name of the app. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected. |
| `filetypeAssociations` | `Array<String>` | An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extensions and MIME types are supported. For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters. |
| `maximizeOnStart` | `Boolean` | Whether the app should be maximized when it is started. Defaults to `false`. |
| `background` | `Boolean` | Whether the app should run in the background. Defaults to `false`. |
| `feedbackEnabled` | `Boolean` | Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Omitted leaves the app's current value unchanged. |
| `metadata` | `Object` | An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON. |
- `name` (optional): The new name of the app. App names are unique across all Puter accounts. If any app already has this name, the promise will be rejected.
- `indexURL` (optional): The new URL of the app's index page. This URL must be accessible to the user.
- `title` (optional): The new title of the app.
- `description` (optional): The new description of the app aimed at the end user.
- `icon` (optional): The new icon of the app.
- `maximizeOnStart` (optional): Whether the app should be maximized when it is started. Defaults to `false`.
- `background` (optional): Whether the app should run in the background. Defaults to `false`.
- `feedbackEnabled` (optional): Whether users can send feedback to you through [`puter.ui.showFeedbackDialog()`](/UI/showFeedbackDialog/). Omitted leaves the app's current value unchanged.
- `filetypeAssociations` (optional): An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extentions and MIME types are supported; For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. At most 200 entries, each at most 60 characters.
- `metadata` (optional): An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. At most 16 KiB when serialized as JSON.
Changing `indexURL` can merge the app into an existing app for that hosted origin. The returned app can have a different UID. The deleted source app's KV data and KV shares are removed. Data already belonging to the surviving app is retained.
@@ -38,7 +35,7 @@ A `Promise` that will resolve to the [`App`](/Objects/app/) object that was upda
## Examples
### Create a random app then change its title
<strong class="example-title">Create a random app then change its title</strong>
```html;app-update
<html>
+1 -1
View File
@@ -98,8 +98,8 @@ This is essential for users to access the various Puter.js APIs integrated into
These authentication features are supported out of the box when using Puter.js:
- **[`puter.auth.signIn()`](/Auth/signIn/)** - Sign in a user
- **[`puter.auth.isSignedIn()`](/Auth/isSignedIn/)** - Check if a user is signed in
- **[`puter.auth.signOut()`](/Auth/signOut/)** - Sign out the current user
- **[`puter.auth.isSignedIn()`](/Auth/isSignedIn/)** - Check if a user is signed in
- **[`puter.auth.getUser()`](/Auth/getUser/)** - Get information about the current user
- **[`puter.auth.getProfile()`](/Auth/getProfile/)** - Get a user's profile, when available
- **[`puter.auth.getProfilePicture()`](/Auth/getProfilePicture/)** - Get a user's profile picture, when available
+1 -3
View File
@@ -29,9 +29,7 @@ The id of the application.
A `Promise` that resolves to a [`DetailedAppUsage`](/Objects/detailedappusage) object containing resource usage statistics for the given application.
## Examples
### Get an app's usage
## Example
```html
<html>
+1 -3
View File
@@ -26,9 +26,7 @@ None
A `Promise` that resolves to a [`MonthlyUsage`](/Objects/monthlyusage) object containing the user's monthly usage information.
## Examples
### Get the user's monthly usage
## Example
```html;auth-get-monthly-usage
<html>
+3 -7
View File
@@ -4,9 +4,7 @@ description: Read a user's profile, returning null when it is not available.
platforms: [websites, apps, nodejs, workers]
---
Returns a user's profile, which holds their picture, display name, and bio.
Users set these on the [Account page](https://puter.com/dashboard#account) of their Puter dashboard. A user can always read their own profile. Another user's profile is available only while that user is on a paid plan; otherwise the method resolves to `null`, the same as for a user who does not exist.
Returns a user's profile: their picture, display name, and bio. Users set these on the [Account page](https://puter.com/dashboard#account) of their Puter dashboard. A user can always read their own profile. Another user's profile is available only while that user is on a paid plan; otherwise the method resolves to `null`, the same as for a user who does not exist.
## Syntax
@@ -17,7 +15,7 @@ puter.auth.getProfile(username);
## Parameters
#### `username` (optional)
### `username` (optional)
The username to look up. Defaults to the signed-in user.
@@ -27,9 +25,7 @@ A promise that resolves to a [`UserProfile`](/Objects/userprofile) object, or `n
When signed out with no `username`, it resolves to `null` without opening a sign-in prompt.
## Examples
### Show the user's profile
## Example
```html
<html>
+3 -7
View File
@@ -4,9 +4,7 @@ description: Read a user's profile picture, returning null when unavailable.
platforms: [websites, apps, nodejs, workers]
---
Returns the `picture` field of a user's profile (see [`puter.auth.getProfile()`](/Auth/getProfile/)).
A user can always read their own picture. Another user's picture is available only while that user is on a paid plan.
Returns the `picture` field of a user's profile (see [`puter.auth.getProfile()`](/Auth/getProfile/)). A user can always read their own picture. Another user's picture is available only while that user is on a paid plan.
## Syntax
@@ -17,7 +15,7 @@ puter.auth.getProfilePicture(username);
## Parameters
#### `username` (optional)
### `username` (optional)
The username to look up. Defaults to the signed-in user.
@@ -29,9 +27,7 @@ Missing users, profiles that are not public to the caller, profiles with no pict
When signed out with no `username`, it resolves to `null` without opening a sign-in prompt.
## Examples
### Show the user's profile picture
## Example
```html
<html>
+1 -3
View File
@@ -20,9 +20,7 @@ None
A promise that resolves to a [`User`](/Objects/user) object containing the user's basic information.
## Examples
### Get the signed-in user
## Example
```html;auth-get-user
<html>
+1 -3
View File
@@ -20,9 +20,7 @@ None
Returns `true` if the user is signed in, `false` otherwise.
## Examples
### Check whether the user is signed in
## Example
```html;auth-is-signed-in
<html>
+7 -12
View File
@@ -4,9 +4,7 @@ description: Initiate sign in process in your application with user's Puter acco
platforms: [websites]
---
Initiates the sign in process for the user.
This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in. Puter's own apps on puter.com subdomains show the sign-in in a frame over the page instead, and open the popup when the user picks a sign-in provider such as Google.
Initiates the sign in process for the user. This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in.
It is important to note that all essential methods in Puter handle authentication automatically. This method is only necessary if you want to handle authentication manually, for example if you want to build your own custom authentication flow.
@@ -29,12 +27,11 @@ puter.auth.signIn(options)
#### `options` (optional)
An object with the following properties:
`options` is an object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `attempt_temp_user_creation` | `Boolean` | Whether Puter should automatically create a temporary user. This is useful if you want to quickly onboard a user without requiring them to sign up. They can always sign up later if they want to. |
| `request_auth` | `Boolean` | Asks the popup to let the user re-pick their account, even when your site already holds a token for them. Puter otherwise skips that prompt for a site it has seen before. Useful for an explicit "switch account" button. |
- `attempt_temp_user_creation`: A boolean value that indicates whether to Puter should automatically create a temporary user. This is useful if you want to quickly onboard a user without requiring them to sign up. They can always sign up later if they want to.
- `request_auth`: A boolean value that asks the popup to let the user re-pick their account, even when your site already holds a token for them. Puter otherwise skips that prompt for a site it has seen before. Useful for an explicit "switch account" button.
Each call completes from its own sign-in window, including when multiple calls run at once.
@@ -42,7 +39,7 @@ Each call completes from its own sign-in window, including when multiple calls r
A `Promise` that will resolve to a [`SignInResult`](/Objects/signinresult/) object when the user has signed in.
## Errors
## Rejection
The promise will reject with an object containing an `error` code and a human-readable `msg` in the following cases:
@@ -56,9 +53,7 @@ The promise will reject with an object containing an `error` code and a human-re
The promise may also reject with the failure response returned by the authentication window itself.
## Examples
### Sign in from a button click
## Example
```html;auth-sign-in
<html>
+1 -3
View File
@@ -22,9 +22,7 @@ None
A `Promise` that resolves with nothing once the user is signed out and, on a website, this browser's push subscription for your app is ended. It doesn't reject.
## Examples
### Sign the user out
## Example
```html;auth-sign-out
<html>
+8 -18
View File
@@ -5,9 +5,7 @@ platforms: [websites, apps, nodejs, workers]
draft: true
---
Changes fields on the signed-in user's profile and returns the updated profile.
Fields left out of the patch are left as they are; `null` clears a field.
Changes fields on the signed-in user's profile and returns the updated profile. Fields left out of the patch are left as they are; `null` clears a field.
## Syntax
@@ -17,27 +15,19 @@ puter.auth.updateProfile(patch);
## Parameters
#### `patch` (required)
### `patch` (required)
An object with any of these fields:
| Option | Type | Description |
|--------|------|-------------|
| `displayName` | `String \| null` | The user's display name, at most 64 characters. Surrounding whitespace is removed. |
| `picture` | `String \| null` | A base64 image data URL such as `data:image/png;base64,...`. At most 512 KiB. |
| `bio` | `String \| null` | The user's bio, at most 280 characters. Surrounding whitespace is removed. |
- `picture` (String or `null`): a base64 image data URL such as `data:image/png;base64,...`. At most 512 KiB.
- `displayName` (String or `null`): at most 64 characters. Surrounding whitespace is removed.
- `bio` (String or `null`): at most 280 characters. Surrounding whitespace is removed.
Any other field is rejected.
## Return value
A promise that resolves to the stored [`UserProfile`](/Objects/userprofile).
The profile belongs to the account, so the call must be made with a user session; an app acting on a user's behalf cannot change it.
## Errors
The promise rejects with an object carrying a `code` and `message` when the patch is not accepted:
A promise that resolves to the stored [`UserProfile`](/Objects/userprofile). It rejects with an object carrying a `code` and `message` when the patch is not accepted:
| `code` | Meaning |
| --------------------------- | ----------------------------------------------------- |
@@ -47,9 +37,9 @@ The promise rejects with an object carrying a `code` and `message` when the patc
| `profile_picture_too_large` | `picture` is over the size limit |
| `profile_field_too_long` | `displayName` or `bio` is over its length limit |
## Examples
The profile belongs to the account, so the call must be made with a user session; an app acting on a user's behalf cannot change it.
### Change the user's display name
## Example
```html;auth-update-profile
<html>
+1 -1
View File
@@ -88,6 +88,6 @@ router.post('/notify', async ({ request, user }) => {
## Functions
- **[`puter.email.sendTransactional()`](/Email/sendTransactional/)** - Send a transactional email from your app
- **[`puter.email.list()`](/Email/list/)** - List the messages in the user's mailbox, newest first
- **[`puter.email.get()`](/Email/get/)** - Fetch and parse one message, attachments included
- **[`puter.email.sendTransactional()`](/Email/sendTransactional/)** - Send a transactional email from your app
+7 -11
View File
@@ -4,9 +4,7 @@ description: Fetch and parse one message from the user's mailbox by its id.
platforms: [websites, apps, nodejs, workers]
---
Reads one message by the `id` a listing returned.
The whole raw message is downloaded and parsed, so the result carries the full subject, sender and recipients, the text and HTML bodies, every header, and each attachment with its bytes. Pass `raw: true` to get the unparsed `message/rfc822` bytes as a `Blob` instead.
Reads one message by the `id` a listing returned. The whole raw message is downloaded and parsed, so the result carries the full subject, sender and recipients, the text and HTML bodies, every header, and each attachment with its bytes. Pass `raw: true` to get the unparsed `message/rfc822` bytes as a `Blob` instead.
Reading the mailbox requires read access to the `~/.mail` folder, the same grant [`puter.email.list()`](/Email/list/) needs.
@@ -25,11 +23,9 @@ The message id from `puter.email.list()`. Looks up the inbox.
#### `options` (Object)
| Option | Type | Description |
|--------|------|-------------|
| `id` | `String` | Required. The message id. |
| `folder` | `String` | Either `'inbox'` or `'sent'`. Default `'inbox'`. A message id is unique within a folder, so a sent message must be read with `folder: 'sent'`. |
| `raw` | `Boolean` | When `true`, resolve with the raw message `Blob` and skip parsing. Default `false`. |
- `id` (String) (required): The message id.
- `folder` (String): `'inbox'` or `'sent'`. Default `'inbox'`. A message id is unique within a folder, so a sent message must be read with `folder: 'sent'`.
- `raw` (Boolean): When `true`, resolve with the raw message `Blob` and skip parsing. Default `false`.
## Return value
@@ -49,7 +45,7 @@ Rejects with an object carrying a `code`:
## Examples
### Read the newest message in the inbox
<strong class="example-title">Read the newest message in the inbox</strong>
```html
<html>
@@ -70,7 +66,7 @@ Rejects with an object carrying a `code`:
</html>
```
### Save every attachment of a message to the user's Documents
<strong class="example-title">Save every attachment of a message to the user's Documents</strong>
```html
<html>
@@ -93,7 +89,7 @@ Rejects with an object carrying a `code`:
</html>
```
### Download the raw message
<strong class="example-title">Download the raw message</strong>
```html
<html>
+8 -12
View File
@@ -4,9 +4,7 @@ description: List the messages in the user's mailbox, newest first, one page at
platforms: [websites, apps, nodejs, workers]
---
Lists the messages in one folder of the user's mailbox, newest first.
Every call returns one page of `items` plus, while more pages exist, a `cursor` to pass back for the next one. Listing reads the mailbox's folder structure only, so it never downloads a message: each item carries the subject, date, and size, and `puter.email.get()` fetches the rest.
Lists the messages in one folder of the user's mailbox, newest first. Every call returns one page of `items` plus, while more pages exist, a `cursor` to pass back for the next one. Listing reads the mailbox's folder structure only, so it never downloads a message: each item carries the subject, date, and size, and `puter.email.get()` fetches the rest.
The mailbox belongs to the user, so it is protected like the rest of their files. An app reads it only after the user grants read access to the `~/.mail` folder. To ask for it, call [`puter.perms.request()`](/Perms/request/):
@@ -25,12 +23,10 @@ puter.email.list(options)
#### `options` (Object) (optional)
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum messages per page. Default `50`, capped at `1000`. |
| `folder` | `String` | Use `'inbox'` for mail received at the user's address, or `'sent'` for their outgoing copies. Default `'inbox'`. |
| `cursor` | `String \| null` | The `cursor` from the previous page. Pass `null` or leave it out to fetch the first page. |
| `stream` | `Boolean` | When `true`, returns an async iterator of pages for `for await ... of` instead of a single page. |
- `folder` (String): `'inbox'` for mail received at the user's address, `'sent'` for their outgoing copies. Default `'inbox'`.
- `limit` (Number): Maximum messages per page. Default `50`, capped at `1000`.
- `cursor` (String | null): The `cursor` from the previous page. `null` or absent fetches the first page.
- `stream` (Boolean): When `true`, returns an async iterator of pages for `for await ... of` instead of a single page.
`offset` and `includeTotal` are not supported for mailboxes; passing either rejects with `invalid_request`.
@@ -49,7 +45,7 @@ Rejects with an object carrying a `code`:
## Examples
### List the ten newest messages
<strong class="example-title">List the ten newest messages</strong>
```html
<html>
@@ -68,7 +64,7 @@ Rejects with an object carrying a `code`:
</html>
```
### Walk the whole sent folder with a cursor
<strong class="example-title">Walk the whole sent folder with a cursor</strong>
```html
<html>
@@ -90,7 +86,7 @@ Rejects with an object carrying a `code`:
</html>
```
### Stream pages
<strong class="example-title">Stream pages</strong>
```html
<html>
+20 -30
View File
@@ -4,9 +4,7 @@ description: Send a transactional email from your app — authorized by a worker
platforms: [websites, apps, nodejs, workers]
---
Sends one transactional email from your app.
Every send must be authorized by a worker: call it from inside a worker, or pass the worker's token as `emailAccessToken`. The account that makes the call is the one billed and rate-limited.
Sends one transactional email from your app. Every send must be authorized by a worker: call it from inside a worker, or pass the worker's token as `emailAccessToken`. The account that makes the call is the one billed and rate-limited.
<div class="info">Transactional email is available to accounts on a paid plan for now. A call from a free account fails with <code>402</code> <code>subscription_required</code>. Under the <a href="/user-pays-model/">User-Pays Model</a> that is the plan of the <em>calling</em> account — your users when your app sends with their session, your own when the worker sends directly.</div>
@@ -33,25 +31,21 @@ A plain-text body. Shorthand for `text`; use the options form for anything else.
#### `options` (Object)
| Option | Type | Description |
|--------|------|-------------|
| `to` | `String \| Array` | Required. One recipient address, or an array of them. |
| `subject` | `String` | Required. As above. |
| `text` | `String` | Plain-text body. At least one of `text` and `html` is required. |
| `html` | `String` | HTML body. An inline image is shown with `<img src="cid:...">`. See `attachments.cid`. |
| `emailAccessToken` | `String` | A worker's auth token. Inside a worker, that's `me.puter.authToken`. Required when the caller is not itself a worker. The caller stays the billed and rate-limited identity. |
| `attachments` | `Array` | Up to **10** attachments, **25 MB** in total. Each attachment is an object with the `attachments.*` fields in the rows that follow. |
| `attachments.path` | `String` | A Puter path (`~/` allowed, meaning the caller's home). The file is read on the server with the caller's file permissions only, and streamed rather than uploaded. Prefer this over `content` for anything larger than a few hundred kilobytes. |
| `attachments.uid` | `String` | A Puter file uid, as an alternative to `path`. Read with the caller's file permissions, falling back to the worker owner's. Use a uid to attach a file from the worker owner's storage. |
| `attachments.content` | `String` | The file body as base64. Mutually exclusive with `path`/`uid`. |
| `attachments.filename` | `String` | Required with `content`. Defaults to the file's name for a `path`/`uid` attachment. |
| `attachments.contentType` | `String` | MIME type. Detected from the file for `path`/`uid` attachments. |
| `attachments.cid` | `String` | Content-ID that makes the attachment an inline part of the `html` body. With `cid: 'logo'`, `<img src="cid:logo">` shows it. Printable ASCII with no whitespace or angle brackets. Inline parts are billed like any other attachment. |
| `replyTo` | `String` | Where replies go. Defaults to the confirmed account email of the worker's owner when the worker has no app binding, or its owner owns the bound app and that app wasn't created by another app. Otherwise, or while the address is unconfirmed, the message goes out without a Reply-To. |
| `cc` | `String \| Array` | Carbon-copy recipient(s). |
| `bcc` | `String \| Array` | Blind-copy recipient(s). |
A message can have at most **10** recipients across `to`, `cc` and `bcc`.
- `to` (String | Array) (required) - Recipient address(es).
- `subject` (String) (required) - As above.
- `text` (String) - Plain-text body. At least one of `text` and `html` is required.
- `html` (String) - HTML body. An inline image is shown with `<img src="cid:...">` — see `cid` under `attachments`.
- `cc` (String | Array) - Carbon-copy recipient(s).
- `bcc` (String | Array) - Blind-copy recipient(s). At most **10** recipients across `to`, `cc` and `bcc`.
- `replyTo` (String) - Where replies go. Defaults to the confirmed account email of the worker's owner when the worker has no app binding, or its owner owns the bound app and that app wasn't created by another app. Otherwise, or while the address is unconfirmed, the message goes out without a Reply-To.
- `emailAccessToken` (String) - A worker's auth token — inside a worker, `me.puter.authToken`. Required when the caller is not itself a worker. The caller stays the billed and rate-limited identity.
- `attachments` (Array) - Up to **10** attachments, **25 MB** in total. Each is an object:
- `filename` (String) - Required with `content`; defaults to the file's name for a `path`/`uid` attachment.
- `content` (String) - The file body as base64. Mutually exclusive with `path`/`uid`.
- `path` (String) - A Puter path (`~/` allowed, meaning the caller's home). The file is read on the server with the caller's file permissions only, and streamed rather than uploaded — prefer this over `content` for anything larger than a few hundred kilobytes.
- `uid` (String) - A Puter file uid, as an alternative to `path`. Read with the caller's file permissions, falling back to the worker owner's — use a uid to attach a file from the worker owner's storage.
- `contentType` (String) - MIME type. Detected from the file for `path`/`uid` attachments.
- `cid` (String) - Content-ID that makes the attachment an inline part of the `html` body: with `cid: 'logo'`, `<img src="cid:logo">` shows it. Printable ASCII with no whitespace or angle brackets. Inline parts are billed like any other attachment.
## Return value
@@ -62,11 +56,7 @@ A `Promise` that resolves to an object:
- `suppressed` (Array) - Recipients (lowercased) dropped because they unsubscribed from your app's mail. The message went to the others.
- `failed` (Array) - Recipients (lowercased) whose delivery failed. Everyone else got their copy — retry with just these addresses.
Each recipient gets a private copy of the message, so the unsubscribe link in one copy can only act for the mailbox that received it. Per-recipient failures come back in `failed` rather than failing the call.
## Errors
The promise rejects only when no recipient could be delivered, or when every `to` recipient has unsubscribed (`400`).
Each recipient gets a private copy of the message, so the unsubscribe link in one copy can only act for the mailbox that received it. Per-recipient failures come back in `failed` rather than failing the call; the promise rejects only when no recipient could be delivered, or when every `to` recipient has unsubscribed (`400`).
In case of an error, the `Promise` rejects with `{ message, code }`. Codes you may see:
@@ -100,7 +90,7 @@ Sends are rate-limited per calling account; the numbers are on [Rate Limits and
## Examples
### Send a plain-text notification from a worker
<strong class="example-title">Send a plain-text notification from a worker</strong>
```js
// The worker is the caller, so its owner is billed and rate-limited.
@@ -114,7 +104,7 @@ router.post('/api/alert', async ({ request }) => {
});
```
### Let the user pay for their own sends
<strong class="example-title">Let the user pay for their own sends</strong>
```js
// The user's session makes the call; the worker's token authorizes it.
@@ -132,7 +122,7 @@ router.post('/api/receipt', async ({ request, user }) => {
});
```
### Attach a file and show an inline image
<strong class="example-title">Attach a file and show an inline image</strong>
```js
// The uid of a file in the worker owner's storage, e.g. from
+20 -26
View File
@@ -4,11 +4,9 @@ description: Read what a subject recorded while nothing was listening.
platforms: [websites, apps, nodejs, workers]
---
Reads the events a subject has stored, a page at a time.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
A subscription only delivers while something is listening, and `fetch()` catches up on what happened while the client was closed or offline. Only `notif:` subjects (the notification mailbox) store events. Subjects for `fs:` and `kv:` are refused with `fetch_unsupported_subject`.
Reads the events a subject has stored, a page at a time. A subscription only delivers while something is listening, and `fetch()` catches up on what happened while the client was closed or offline. Only `notif:` subjects (the notification mailbox) store events. Subjects for `fs:` and `kv:` are refused with `fetch_unsupported_subject`.
It's a plain query. Nothing is registered and no position is saved, so calling it twice returns the same result. You keep the `cursor` and pass it back.
@@ -27,13 +25,11 @@ puter.events.fetch(options)
#### `options` (Object) (required)
| Option | Type | Description |
|--------|------|-------------|
| `subject` | `String` | Required. What to read. Use `notif:app-user` for your app's notifications for the user, and `notif:developer` for notifications about your app, for its owner. The full form is `notif:<appId>:<audience>`, where the audience is `account`, `developer`, or `app-user`. Apps and websites never see `account` notifications, so `notif:account` returns an empty page for them. |
| `cursor` | `String` | The `cursor` from the previous page. Leave it off to start from the oldest notification still kept. A read from a cursor returns the notifications created after it, plus any notification [replaced](/Notifications/notify/#groups) since that page was read, even one from an earlier page. |
| `limit` | `Number` | Events per page. Defaults to 50, max 200. |
| `from` | `String` | Where a read without a cursor starts. The default, `'start'`, starts from the oldest notification still kept. With `'end'`, the read skips what's already there. It returns no items and a `cursor` at the newest notification, and reads from that cursor return only notifications created or replaced after it. Ignored when a cursor is given. |
| `after` | `String` | The older name for `cursor`, still accepted. If both are given, `cursor` is used. |
- `subject` (String) (required): What to read. Use `notif:app-user` for your app's notifications for the user, and `notif:developer` for notifications about your app, for its owner. The full form is `notif:<appId>:<audience>`, where the audience is `account`, `developer`, or `app-user`. Apps and websites never see `account` notifications, so `notif:account` returns an empty page for them.
- `cursor` (String): The `cursor` from the previous page. Leave it off to start from the oldest notification still kept. A read from a cursor returns the notifications created after it, plus any notification [replaced](/Notifications/notify/#groups) since that page was read, even one from an earlier page.
- `after` (String): The older name for `cursor`, still accepted. If both are given, `cursor` is used.
- `from` (String): Where a read without a cursor starts. `'start'`, the default, starts from the oldest notification still kept. `'end'` skips what's already there: it returns no items and a `cursor` at the newest notification, and reads from that cursor return only notifications created or replaced after it. Ignored when a cursor is given.
- `limit` (Number): Events per page. Defaults to 50, max 200.
## Return value
@@ -46,18 +42,18 @@ Each item is a notification event:
| Field | Type | Description |
| --- | --- | --- |
| `id` | `String` | The notification's uid. Live deliveries carry the same id, so you can drop duplicates. A replacement keeps the id, so tell it apart by `replaced` and `ts`. |
| `subject` | `String` | `notif:<appId or userId>:<audience>`, the part of the mailbox it belongs to. |
| `op` | `String` | Always `post`. |
| `uid` | `String` | The notification's uid. |
| `type` | `String` | The kind of notification, such as `share.received`, `app.worker.deployed`, or `app.message`. The types are listed below. |
| `audience` | `String` | `account`, `developer`, or `app-user`. |
| `appUid` | `String \| null` | The app it's about, or `null` for one that names no app. |
| `notification` | `Object` | The stored payload. It always has `type`, and every type except `kv.share.received` has a `title`. Other fields depend on `type`. |
| `replaced` | `Boolean` | Present and `true` when the notification replaced an earlier one with the same `uid`, as an app's notification with a [`group`](/Notifications/notify/#groups) does. |
| `self` | `Boolean` | Always `true`, since a mailbox is your own. |
| `ts` | `Number` | When it was created, in milliseconds since the epoch. On a replacement, when it was replaced, and the same on its live and fetched copies. |
| `seq` | `Number` | Position within the page. |
| `id` | String | The notification's uid. Live deliveries carry the same id, so you can drop duplicates. A replacement keeps the id, so tell it apart by `replaced` and `ts`. |
| `subject` | String | `notif:<appId or userId>:<audience>`, the part of the mailbox it belongs to. |
| `op` | String | Always `post`. |
| `uid` | String | The notification's uid. |
| `type` | String | The kind of notification, such as `share.received`, `app.worker.deployed`, or `app.message`. The types are listed below. |
| `audience` | String | `account`, `developer`, or `app-user`. |
| `appUid` | String \| null | The app it's about, or `null` for one that names no app. |
| `notification` | Object | The stored payload. It always has `type`, and every type except `kv.share.received` has a `title`. Other fields depend on `type`. |
| `replaced` | Boolean | Present and `true` when the notification replaced an earlier one with the same `uid`, as an app's notification with a [`group`](/Notifications/notify/#groups) does. |
| `self` | Boolean | Always `true`, since a mailbox is your own. |
| `ts` | Number | When it was created, in milliseconds since the epoch. On a replacement, when it was replaced, and the same on its live and fetched copies. |
| `seq` | Number | Position within the page. |
Besides `type` and `title`, `notification` carries these fields for each type:
@@ -78,8 +74,6 @@ Apps see `developer` notifications only for apps the user owns. Asking for a par
Notifications are kept for the server's retention window. A client away for longer starts from what's left.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -95,7 +89,7 @@ The promise rejects with `{ message, code }`:
## Examples
### Catch up on everything missed
<strong class="example-title">Catch up on everything missed</strong>
```html;events-fetch
<html>
@@ -124,7 +118,7 @@ The promise rejects with `{ message, code }`:
</html>
```
### Read the missed ones, then keep listening
<strong class="example-title">Read the missed ones, then keep listening</strong>
```html;events-fetch-then-listen
<html>
+2 -6
View File
@@ -4,11 +4,9 @@ description: Read one schedule, including one that has ended.
platforms: [websites, apps, nodejs, workers]
---
Reads one schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or one notification your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
An ended schedule can be read for 7 days after it ends.
Reads one schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or one notification your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later). An ended schedule can be read for 7 days after it ends.
An app can read only the schedules it created. An account session can read any of the user's schedules. An id this caller can't read reads as not existing, so the call doesn't reveal which schedules exist.
@@ -28,8 +26,6 @@ The `scheduleId` from [`onSchedule()`](/Events/onSchedule/), [`notify()`](/Notif
A `Promise` that resolves to the schedule, the object [`onSchedule()`](/Events/onSchedule/#return-value) returns, without `off()`. Its `state` says whether it's `active`, `suspended`, `sending` or `ended`, and `nextRunAt` says when it's next due.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -42,7 +38,7 @@ The promise rejects with `{ message, code }`:
## Examples
### Check when a stored notification goes out
<strong class="example-title">Check when a stored notification goes out</strong>
```html;events-get-schedule
<html>
+7 -14
View File
@@ -4,11 +4,9 @@ description: Publish, list and remove the named handlers that persistent subscri
platforms: [websites, apps, nodejs, workers]
---
A **handler** is a function that [persistent subscriptions](/Events/onPersistent/) and [schedules](/Events/onSchedule/) run in the background.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
A handler runs only when a subscription bound to it has a delivery, or a schedule bound to it is due. Nothing else can trigger it.
A **handler** is a function that [persistent subscriptions](/Events/onPersistent/) and [schedules](/Events/onSchedule/) run in the background. A handler runs only when a subscription bound to it has a delivery, or a schedule bound to it is due. Nothing else can trigger it.
A handler lives in one of two scopes:
@@ -99,14 +97,9 @@ puter.events.handlers.publish(name, handler, options)
- `name` (String) (required): The name subscriptions bind to. Letters, digits, and `_ . : -`, starting with a letter or digit, up to 128 characters. Unique within the app.
- `handler` (Function | String | Object) (required): A function (serialized with `toString()`), a source string, or `{ file: '~/AppData/…/handler.js' }`. A file is read at this call, so later edits to it take effect only when you publish again.
The `options` object takes these options:
| Option | Type | Description |
|--------|------|-------------|
| `appUid` | `String` | Required outside an app. The app to publish into. Inside an app, it can only name that app. With `scope: 'user'` it can only name the app making the call, and needs no value. Only [`workers.destroy()`](/Events/workers/) can name another app for a user scope, from an account session. |
| `scope` | `String` | Either `'app'` or `'user'`. Defaults to `'app'`. With `'user'`, it publishes into the signed-in user's own [user scope](#user-scope) of the app. |
| `replace` | `Boolean` | Overwrite whatever is published under the name. |
- `options.replace` (Boolean): Overwrite whatever is published under the name.
- `options.scope` (String): `'app'` or `'user'`. Defaults to `'app'`. `'user'` publishes into the signed-in user's own [user scope](#user-scope) of the app.
- `options.appUid` (String): The app to publish into. Required outside an app. Inside an app, it can only name that app. With `scope: 'user'` it can only name the app making the call, and needs no value. Only [`workers.destroy()`](/Events/workers/) can name another app for a user scope, from an account session.
Resolves to `{ name, hash, updatedAt, outcome, resumed }`. Its `outcome` is `'created'`, `'updated'`, or `'unchanged'` (the same source was already published), and `resumed` counts the suspended subscriptions this publish brought back.
@@ -191,7 +184,7 @@ All four methods reject with `{ message, code }`:
The first example publishes into a user scope from inside an app, for the signed-in user. The others run in Node.js signed in with your account token, and `appUid` names an app you own. Inside your own app, leave out `appUid`.
### Publish into the user's scope, list it, then remove it
<strong class="example-title">Publish into the user's scope, list it, then remove it</strong>
```js
const published = await puter.events.handlers.publish(
@@ -210,7 +203,7 @@ for (const handler of await puter.events.handlers.list({ scope: 'user' })) {
await puter.events.handlers.remove('digest', { scope: 'user' });
```
### Publish a handler, list it, then remove it
<strong class="example-title">Publish a handler, list it, then remove it</strong>
```js
const published = await puter.events.handlers.publish(
@@ -231,7 +224,7 @@ const removed = await puter.events.handlers.remove('ingestUpload', { appUid });
console.log(removed.removed, removed.suspended);
```
### Deploy a whole set from a build step
<strong class="example-title">Deploy a whole set from a build step</strong>
```js
const published = await puter.events.handlers.publishAll([
+7 -13
View File
@@ -4,11 +4,9 @@ description: List the persistent subscriptions this caller holds.
platforms: [websites, apps, nodejs, workers]
---
Lists the persistent subscriptions created with [`puter.events.onPersistent()`](/Events/onPersistent/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Session subscriptions from [`onLocal()`](/Events/onLocal/) aren't stored, so they aren't listed.
Lists the persistent subscriptions created with [`puter.events.onPersistent()`](/Events/onPersistent/). Session subscriptions from [`onLocal()`](/Events/onLocal/) aren't stored, so they aren't listed.
An app sees only the subscriptions it created. Outside an app, such as in Node.js with an account token, you see all of them. Deleting an app deletes its subscriptions. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, sees none, whether the account or an app created it.
@@ -24,12 +22,10 @@ puter.events.list(options)
#### `options` (Object) (optional)
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum subscriptions per request. Defaults to 50, max 200. |
| `cursor` | `String \| null` | The cursor from a previous page. Passing it, even as `null`, returns a single page instead of the full list. |
| `stream` | `Boolean` | Returns an async iterator of pages instead of a promise. |
| `includeTotal` | `Boolean` | Adds `total` to the page. Ask for it on the first page only, since it gets slower as the count grows. |
- `limit` (Number): Maximum subscriptions per request. Defaults to 50, max 200.
- `cursor` (String | null): The cursor from a previous page. Passing it, even as `null`, returns a single page instead of the full list.
- `includeTotal` (Boolean): Adds `total` to the page. Ask for it on the first page only, since it gets slower as the count grows.
- `stream` (Boolean): Returns an async iterator of pages instead of a promise.
## Return value
@@ -44,8 +40,6 @@ Each subscription is the object [`onPersistent()`](/Events/onPersistent/#return-
- `contextKeys` (Array | null) and `contextHash` (String | null) describe the stored `context`. The values are never returned, since context often holds secrets. The hash changes whenever a value does.
- `suspendedAt` (Number | null) and `suspendedReason` (String | null) are set when a subscription is [suspended](/Events/onPersistent/#suspended-subscriptions), with `handler_not_found`, `failures`, `no_credit`, or `permission_revoked`.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -57,7 +51,7 @@ The promise rejects with `{ message, code }`:
## Examples
### List everything this account is watching
<strong class="example-title">List everything this account is watching</strong>
```html;events-list
<html>
@@ -84,7 +78,7 @@ The promise rejects with `{ message, code }`:
</html>
```
### Find the ones that stopped, and why
<strong class="example-title">Find the ones that stopped, and why</strong>
```html;events-list-suspended
<html>
+5 -11
View File
@@ -4,11 +4,9 @@ description: List the schedules this caller holds, one page at a time.
platforms: [websites, apps, nodejs, workers]
---
Lists the schedules created with [`puter.events.onSchedule()`](/Events/onSchedule/), and the notifications your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
Ended schedules stay in the list for 7 days, with the reason they ended.
Lists the schedules created with [`puter.events.onSchedule()`](/Events/onSchedule/), and the notifications your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later). Ended schedules stay in the list for 7 days, with the reason they ended.
An app sees only the schedules it created for the user it runs for. An account session, such as the Puter desktop, sees all of the user's schedules, including ones left by apps they no longer use, so that's where to clean up stray schedules. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, sees none.
@@ -26,11 +24,9 @@ puter.events.listSchedules(options)
#### `options` (Object) (optional)
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum schedules per page. Capped at 200, and defaults to 50. |
| `cursor` | `String \| null` | The `cursor` from the previous page. Leave it out, or pass `null`, for the first page. |
| `includeTotal` | `Boolean` | Adds `total`, the number of schedules across every page. Ask for it on the first page only. |
- `limit` (Number): Maximum schedules per page. Capped at 200, and defaults to 50.
- `cursor` (String | null): The `cursor` from the previous page. Leave it out, or pass `null`, for the first page.
- `includeTotal` (Boolean): Adds `total`, the number of schedules across every page. Ask for it on the first page only.
## Return value
@@ -44,8 +40,6 @@ Pages can be shorter than `limit` before the last one, so keep going until `curs
The `context` a schedule was created with is never returned, since it often holds secrets. The `contextKeys` field lists its key names, and `contextHash` changes whenever a value does.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -59,7 +53,7 @@ The promise rejects with `{ message, code }`:
## Examples
### List every schedule, page by page
<strong class="example-title">List every schedule, page by page</strong>
```html;events-list-schedules
<html>
+2 -4
View File
@@ -4,11 +4,9 @@ description: End a subscription created with puter.events.onLocal().
platforms: [websites, apps, nodejs]
---
Ends a subscription returned by [`puter.events.onLocal()`](/Events/onLocal/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
The handler stops being called immediately, and the server is told if the connection is still open.
Ends a subscription returned by [`puter.events.onLocal()`](/Events/onLocal/). The handler stops being called immediately, and the server is told if the connection is still open.
Ending a subscription counts toward its own [unsubscribe rate limit](/rate-limits-and-quotas/#events), not the `subscribe` one. Over that limit `off()` still resolves and the handler still stops, but the server may keep the subscription until the connection closes, and a warning is logged to the console.
@@ -27,7 +25,7 @@ A `Promise` that resolves when the subscription is gone. It never rejects. Calli
## Examples
### Watch a directory, then stop watching it
<strong class="example-title">Watch a directory, then stop watching it</strong>
```html;events-off
<html>
+7 -13
View File
@@ -4,11 +4,9 @@ description: Subscribe to changes on a file, directory, key-value key, or notifi
platforms: [websites, apps, nodejs]
---
Subscribes to a subject and calls `handler` each time something matching it changes.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
The subscription belongs to this client's connection. Nothing is stored, nothing runs while the page is closed, and the subscription ends when the connection does. Changes from other devices and regions reach it too. A change made in another region usually arrives a few hundred milliseconds later than a local one. See [Subjects and events](/Events/subjects/) for the subject syntax and the event shape.
Subscribes to a subject and calls `handler` each time something matching it changes. The subscription belongs to this client's connection. Nothing is stored, nothing runs while the page is closed, and the subscription ends when the connection does. Changes from other devices and regions reach it too. A change made in another region usually arrives a few hundred milliseconds later than a local one. See [Subjects and events](/Events/subjects/) for the subject syntax and the event shape.
In a Puter worker, a subscription only lasts for one invocation. To react to changes from a worker, use [`onPersistent()`](/Events/onPersistent/) with a published handler.
@@ -30,11 +28,9 @@ Called with `{ event }` for each delivery. See [The event](/Events/subjects/#the
#### `options` (Object) (optional)
| Option | Type | Description |
|--------|------|-------------|
| `onError` | `Function` | Called with `{ message, code }` once the subscription is over. That happens when it can't be restored after a disconnect (see [Reconnects](#reconnects)), or when the server ends it, with `code: 'subscription_ended'` and a `reason` (see [Subscriptions the server ends](#subscriptions-the-server-ends)). The handler isn't called after that. Call `onLocal()` again to resume. Without `onError`, the error is logged to the console. |
| `includeValue` | `Boolean` | For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`. |
| `timeout` | `Number` | How long to wait for the server to confirm the subscription, in milliseconds. Defaults to `30000`. |
- `onError` (Function): Called with `{ message, code }` once the subscription is over. That happens when it can't be restored after a disconnect (see [Reconnects](#reconnects)), or when the server ends it, with `code: 'subscription_ended'` and a `reason` (see [Subscriptions the server ends](#subscriptions-the-server-ends)). The handler isn't called after that. Call `onLocal()` again to resume. Without `onError`, the error is logged to the console.
- `timeout` (Number): How long to wait for the server to confirm the subscription, in milliseconds. Defaults to `30000`.
- `includeValue` (Boolean): For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`.
## Return value
@@ -51,8 +47,6 @@ A `Promise` that resolves, once the server confirms the subscription, to a subsc
- `includeValue` (Boolean): Whether `kv:` deliveries carry the new value.
- `off` (Function): Ends the subscription. See [`subscription.off()`](/Events/off/).
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -104,7 +98,7 @@ If the connection is down when this happens, or drops before `onError` is called
## Examples
### Watch a directory and print what changes
<strong class="example-title">Watch a directory and print what changes</strong>
```html;events-watch-folder
<html>
@@ -136,7 +130,7 @@ If the connection is down when this happens, or drops before `onError` is called
</html>
```
### React to a file that does not exist yet
<strong class="example-title">React to a file that does not exist yet</strong>
```html;events-watch-missing
<html>
@@ -169,7 +163,7 @@ If the connection is down when this happens, or drops before `onError` is called
</html>
```
### Watch this app's key-value store
<strong class="example-title">Watch this app's key-value store</strong>
```html;events-watch-kv
<html>
+72 -78
View File
@@ -4,11 +4,9 @@ description: Subscribe to changes with a subscription that keeps running when yo
platforms: [websites, apps, nodejs, workers]
---
Creates a subscription that outlives this connection.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
It's stored on the account, keeps matching while your app is closed, and runs a handler in an [events worker](/Events/workers/). The handler is either inline code you pass as `handler`, which is published into the signed-in user's own [user scope](/Events/handlers/#user-scope) of your app, or a handler published under a name with [`puter.events.handlers.publish()`](/Events/handlers/). Each event also reaches every connected client. Compare [`puter.events.onLocal()`](/Events/onLocal/), which ends with the page.
Creates a subscription that outlives this connection. It's stored on the account, keeps matching while your app is closed, and runs a handler in an [events worker](/Events/workers/). The handler is either inline code you pass as `handler`, which is published into the signed-in user's own [user scope](/Events/handlers/#user-scope) of your app, or a handler published under a name with [`puter.events.handlers.publish()`](/Events/handlers/). Each event also reaches every connected client. Compare [`puter.events.onLocal()`](/Events/onLocal/), which ends with the page.
The subscription is live right away in the region where it was created. Right after this call resolves, changes made in other regions can take a moment longer to reach it, usually well under a second.
@@ -25,78 +23,17 @@ puter.events.onPersistent(options)
#### `options` (Object) (required)
| Option | Type | Description |
|--------|------|-------------|
| `subject` | `String` | Required. What to watch, in the same form [`onLocal()`](/Events/onLocal/) takes, such as `fs:~/Documents` or `kv:<handle>:*`. |
| `handler` | `Function \| String \| Object` | The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and it runs for this user's events only. With `handlerName`, only its hash is sent, and the subscription is created only if it matches what's published under that name. A function also runs in this client for each delivery it receives (see [Where the handler runs](#where-the-handler-runs)). |
| `handlerName` | `String` | The published handler to run in an [events worker](/Events/workers/). Up to 128 characters. A subscription made outside an app has no events worker, so its handler runs only in connected clients. |
| `context` | `Object` | Values the handler needs, passed to it as a frozen `ctx`. Up to 4 KB serialized. See [Context is captured once](#context-is-captured-once-up-to-4-kb). |
| `queue` | `Boolean` | Handles events like a work queue. Each event goes to one consumer at a time, and it's offered again if a run never finishes or hits a temporary error. Requires `handlerName` or an inline `handler`. Defaults to `false`. See [Choosing a mode](#choosing-a-mode). |
| `includeValue` | `Boolean` | For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`. |
| `expiresAt` | `Number \| String` | When the subscription ends on its own, as unix seconds or an ISO-8601 string. Must be in the future. |
| `handlerScope` | `String` | Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. With `'user'`, it binds to a handler in the signed-in user's own scope, published with `handlers.publish(name, handler, { scope: 'user' })`. |
| `onError` | `Function` | Called with `{ message, code }` when this client stops running `handler` because its connection can't be restored (`reauth_required` after a sign-out, `events_connection_failed` otherwise). The subscription itself keeps going in the events worker, and this client takes deliveries again once it reconnects. Only used with a function `handler`. Without it, the stop is logged to the console. |
| `delivery` | `String` | Deprecated. Use `queue` instead. The value `'single'` is the same as `queue: true`, and `'broadcast'` is the default. |
| `targets` | `Array` | Deprecated and ignored. |
## Return value
A `Promise` that resolves to the subscription:
- `subId` (String): Its id, which [`puter.events.update()`](/Events/update/) and [`puter.events.unsubscribe()`](/Events/unsubscribe/) take. It never changes.
- `subject` (String): For `kv:` and `notif:`, the subject in full form, so `kv:cart` comes back as `kv:<appId>:cart`. For `fs:`, as you passed it, except a relative path comes back resolved the same way [`onLocal()`](/Events/onLocal/) returns it.
- `anchor`, `match`, `op`: As [`onLocal()`](/Events/onLocal/#return-value) returns them.
- `queue` (Boolean), `handlerName` (String | null), `includeValue` (Boolean). An inline handler comes back as its server-assigned `handlerName`, which starts with `@`.
- `handlerScope` (String): `'user'` when the subscription is bound to a handler in the user's own scope. Absent otherwise.
- `appUid` (String | null): The app that created it, or `null` if it was created outside an app.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values.
- `createdAt`, `expiresAt` (Number | null): Unix seconds.
- `suspendedAt` (Number | null), `suspendedReason` (String | null): Set when the subscription is [suspended](#suspended-subscriptions).
- `off()` (Function): Ends the subscription and stops running its handler here. Same as [`puter.events.unsubscribe(subId)`](/Events/unsubscribe/).
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `events_handler_hash_mismatch` | The published handler isn't the source passed as `handler`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope, or source was supplied to check a named handler outside an app. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_invalid` | `handler` isn't a function, a nonempty source string, or `{ file }`. |
| `invalid_subject` | The subject is empty, not a string, or can't be parsed, or it's a `notif:` subject and this server has notification events turned off. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope of this app. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_handler_required` | `queue: true` without a `handlerName` or an inline `handler`. |
| `events_background_consent_required` | An app subscribed with a handler, and the user hasn't granted `events:background`. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `bad_request` | `queue` isn't a boolean, `delivery` isn't `'broadcast'` or `'single'`, the two disagree, or `handlerName` isn't a string or is over 128 characters. |
| `invalid_expires_at` | `expiresAt` isn't a future time. |
| `invalid_include_value` | `includeValue` isn't a boolean, or the subject isn't `kv:`. |
| `invalid_subject_op`, `invalid_subject_audience`, `invalid_subject_pattern`, `invalid_kv_pattern`, `invalid_kv_handle_key`, `events_cross_app_disabled`, `events_kv_handles_disabled`, `forbidden` | As on [`onLocal()`](/Events/onLocal/#errors). |
| `subject_does_not_exist` | The subject doesn't exist, or this account can't read it. |
| `events_subscription_limit` | The account or app is at its [persistent subscription limit](/rate-limits-and-quotas/#events). |
| `events_value_too_large` | A field is longer than can be stored, such as an app id over 40 characters. |
| `events_durable_requires_account` | Temporary (anonymous) accounts only get session subscriptions. Scoped access tokens, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, get no persistent subscriptions either, whether the account or an app created them. |
| `too_many_requests` | Over the subscribe rate limit. |
| `events_disabled` | Events aren't enabled on this server. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
- `subject` (String) (required): What to watch, in the same form [`onLocal()`](/Events/onLocal/) takes, such as `fs:~/Documents` or `kv:<handle>:*`.
- `handlerName` (String): The published handler to run in an [events worker](/Events/workers/). Up to 128 characters. A subscription made outside an app has no events worker, so its handler runs only in connected clients.
- `handlerScope` (String): Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. `'user'` binds to a handler in the signed-in user's own scope, published with `handlers.publish(name, handler, { scope: 'user' })`.
- `queue` (Boolean): Handles events like a work queue. Each event goes to one consumer at a time, and it's offered again if a run never finishes or hits a temporary error. Requires `handlerName` or an inline `handler`. Defaults to `false`. See [Choosing a mode](#choosing-a-mode).
- `handler` (Function | String | Object): The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and it runs for this user's events only. With `handlerName`, only its hash is sent, and the subscription is created only if it matches what's published under that name. A function also runs in this client for each delivery it receives (see [Where the handler runs](#where-the-handler-runs)).
- `context` (Object): Values the handler needs, passed to it as a frozen `ctx`. Up to 4 KB serialized. See [Context is captured once](#context-is-captured-once-up-to-4-kb).
- `expiresAt` (Number | String): When the subscription ends on its own, as unix seconds or an ISO-8601 string. Must be in the future.
- `includeValue` (Boolean): For a `kv:` subject, include the key's new value as `event.value`. See [Getting the new value](/Events/subjects/#getting-the-new-value) for when it's left out. Other subjects are refused with `invalid_include_value`.
- `onError` (Function): Called with `{ message, code }` when this client stops running `handler` because its connection can't be restored (`reauth_required` after a sign-out, `events_connection_failed` otherwise). The subscription itself keeps going in the events worker, and this client takes deliveries again once it reconnects. Only used with a function `handler`. Without it, the stop is logged to the console.
- `delivery` (String): Deprecated. Use `queue` instead. The value `'single'` is the same as `queue: true`, and `'broadcast'` is the default.
- `targets` (Array): Deprecated and ignored.
## Background delivery needs consent
@@ -226,11 +163,68 @@ Clients connect to the nearest region. Events reach a client wherever it's conne
- Undelivered events are held in the region where the change happened. If that region goes down, only what it was holding is lost.
- Order is kept within a region and is best effort across regions. Without `queue`, coalescing (250 ms) also runs per region, so two quick writes can arrive as one event nearby and as two farther away.
## Return value
A `Promise` that resolves to the subscription:
- `subId` (String): Its id, which [`puter.events.update()`](/Events/update/) and [`puter.events.unsubscribe()`](/Events/unsubscribe/) take. It never changes.
- `subject` (String): For `kv:` and `notif:`, the subject in full form, so `kv:cart` comes back as `kv:<appId>:cart`. For `fs:`, as you passed it, except a relative path comes back resolved the same way [`onLocal()`](/Events/onLocal/) returns it.
- `anchor`, `match`, `op`: As [`onLocal()`](/Events/onLocal/#return-value) returns them.
- `queue` (Boolean), `handlerName` (String | null), `includeValue` (Boolean). An inline handler comes back as its server-assigned `handlerName`, which starts with `@`.
- `handlerScope` (String): `'user'` when the subscription is bound to a handler in the user's own scope. Absent otherwise.
- `appUid` (String | null): The app that created it, or `null` if it was created outside an app.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values.
- `createdAt`, `expiresAt` (Number | null): Unix seconds.
- `suspendedAt` (Number | null), `suspendedReason` (String | null): Set when the subscription is [suspended](#suspended-subscriptions).
- `off()` (Function): Ends the subscription and stops running its handler here. Same as [`puter.events.unsubscribe(subId)`](/Events/unsubscribe/).
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `events_handler_hash_mismatch` | The published handler isn't the source passed as `handler`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope, or source was supplied to check a named handler outside an app. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_invalid` | `handler` isn't a function, a nonempty source string, or `{ file }`. |
| `invalid_subject` | The subject is empty, not a string, or can't be parsed, or it's a `notif:` subject and this server has notification events turned off. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope of this app. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_handler_required` | `queue: true` without a `handlerName` or an inline `handler`. |
| `events_background_consent_required` | An app subscribed with a handler, and the user hasn't granted `events:background`. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `bad_request` | `queue` isn't a boolean, `delivery` isn't `'broadcast'` or `'single'`, the two disagree, or `handlerName` isn't a string or is over 128 characters. |
| `invalid_expires_at` | `expiresAt` isn't a future time. |
| `invalid_include_value` | `includeValue` isn't a boolean, or the subject isn't `kv:`. |
| `invalid_subject_op`, `invalid_subject_audience`, `invalid_subject_pattern`, `invalid_kv_pattern`, `invalid_kv_handle_key`, `events_cross_app_disabled`, `events_kv_handles_disabled`, `forbidden` | As on [`onLocal()`](/Events/onLocal/#return-value). |
| `subject_does_not_exist` | The subject doesn't exist, or this account can't read it. |
| `events_subscription_limit` | The account or app is at its [persistent subscription limit](/rate-limits-and-quotas/#events). |
| `events_value_too_large` | A field is longer than can be stored, such as an app id over 40 characters. |
| `events_durable_requires_account` | Temporary (anonymous) accounts only get session subscriptions. Scoped access tokens, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, get no persistent subscriptions either, whether the account or an app created them. |
| `too_many_requests` | Over the subscribe rate limit. |
| `events_disabled` | Events aren't enabled on this server. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
## Examples
The first example is the inline form, which any app can use for the signed-in user. The others bind to a handler the app's owner published, so they run in your own app or from Node.js signed in as its developer.
### Watch a folder with an inline handler
<strong class="example-title">Watch a folder with an inline handler</strong>
```js
await puter.perms.request('backgroundEvents');
@@ -248,7 +242,7 @@ await puter.events.unsubscribe(sub.subId);
The handler is stored in the user's scope under `sub.handlerName`, and keeps running for this user until the subscription ends. After the subscription ends, Puter removes the handler about a day later, once nothing is bound to it. You can remove it sooner, as [Clean Up Background Work](/recipes/clean-up-background-work/#remove-a-user-scope) shows.
### Watch a folder with a handler the app's owner published
<strong class="example-title">Watch a folder with a handler the app's owner published</strong>
Publish once as the developer to ship one shared handler to every user.
@@ -273,7 +267,7 @@ const sub = await puter.events.onPersistent({
await puter.events.unsubscribe(sub.subId);
```
### Bind to the exact source you wrote against
<strong class="example-title">Bind to the exact source you wrote against</strong>
```js
const handler = ({ event, ctx }) => console.log(ctx.label, event.path);
+89 -95
View File
@@ -4,13 +4,11 @@ description: Run your app's handler at an interval, on a cron expression in a ti
platforms: [websites, apps, nodejs, workers]
---
Runs a handler on a timer.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
<div class="info">Schedules are available on puter.com. A self-hosted Puter server answers <code>events_disabled</code>.</div>
A schedule can run at an interval, on a cron expression in a time zone, or once at a set time. It's stored on the user's account and runs in an [events worker](/Events/workers/), whether or not your app is open. It never runs in the client that created it.
Runs a handler on a timer. A schedule can run at an interval, on a cron expression in a time zone, or once at a set time. It's stored on the user's account and runs in an [events worker](/Events/workers/), whether or not your app is open. It never runs in the client that created it.
The handler is either inline code you pass as `handler`, or a handler published under a name with [`puter.events.handlers.publish()`](/Events/handlers/). Inline code is published into the signed-in user's own [user scope](/Events/handlers/#user-scope) of your app and runs for that user only. A named handler published by the app's owner is shared by every user of the app.
@@ -31,87 +29,20 @@ puter.events.onSchedule(options)
Give exactly one of `every`, `cron` or `at`.
| Option | Type | Description |
|--------|------|-------------|
| `every` | `Number \| String` | Run at this interval, in milliseconds or as a duration such as `'30m'`, `'6h'` or `'1d'`. The units are `s`, `m`, `h`, `d` and `w`. The interval must be a whole number of seconds, at least your plan's [minimum interval](#how-often-a-schedule-can-run), and at most 366 days. |
| `cron` | `String` | Run on a [cron expression](#cron-expressions), such as `'0 9 * * 1-5'` for 09:00 on weekdays. |
| `at` | `Number \| String \| Date` | Run once, at this [time](#times). It must be at least 1 second and at most 366 days ahead. A schedule with `at` takes no `startAt`, `expiresAt` or `maxRuns`. |
| `handler` | `Function \| String \| Object` | Required unless you pass `handlerName`. The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and every run calls it. With `handlerName`, only its hash is sent, and the schedule is created only if it matches what's published under that name. It never runs in this client. |
| `handlerName` | `String` | Required unless you pass `handler`. The published handler each run calls. |
| `context` | `Object` | Values the handler needs, passed to every run as a frozen `ctx`. Up to 4 KB serialized. It's read once, at this call. To replace it, use [`updateSchedule()`](/Events/updateSchedule/). |
| `tz` | `String` | The IANA time zone the `cron` expression runs in, such as `'America/New_York'`. Defaults to `'UTC'`. Only allowed with `cron`. See [Time zones and daylight saving time](#time-zones-and-daylight-saving-time). |
| `startAt` | `Number \| String \| Date` | For `every`, the first run. Without it, the first run is one interval after this call. A `startAt` in the past sets where the intervals line up, and the first run is the next one after this call. For example, `every: '1d'` with `startAt: '2026-01-01'` runs at midnight UTC every day. For `cron`, the earliest time the schedule may run. At most 366 days ahead. |
| `expiresAt` | `Number \| String \| Date` | The last time the schedule may run. A run due at exactly this time still runs. |
| `maxRuns` | `Number` | How many slots the schedule has, from 1 to 100,000. It ends at its `maxRuns`-th slot counted from the first. It counts slots, not runs that happened, so slots skipped while the schedule was behind or suspended (see [When a schedule runs](#when-a-schedule-runs)) still count, and the retries of one slot count once. With `expiresAt` too, the one that comes first ends the schedule. |
| `handlerScope` | `String` | Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. With `'user'`, it binds to a handler the signed-in user's scope holds, published with `handlers.publish(name, handler, { scope: 'user' })`. |
| `handlerHash` | `String` | The SHA-256 hex digest of the handler source, in place of `handler`, to check it against `handlerName`. |
- `every` (Number | String): Run at this interval, in milliseconds or as a duration such as `'30m'`, `'6h'` or `'1d'`. The units are `s`, `m`, `h`, `d` and `w`. The interval must be a whole number of seconds, at least your plan's [minimum interval](#how-often-a-schedule-can-run), and at most 366 days.
- `cron` (String): Run on a [cron expression](#cron-expressions), such as `'0 9 * * 1-5'` for 09:00 on weekdays.
- `tz` (String): The IANA time zone the `cron` expression runs in, such as `'America/New_York'`. Defaults to `'UTC'`. Only allowed with `cron`. See [Time zones and daylight saving time](#time-zones-and-daylight-saving-time).
- `at` (Number | String | Date): Run once, at this [time](#times). It must be at least 1 second and at most 366 days ahead. A schedule with `at` takes no `startAt`, `expiresAt` or `maxRuns`.
- `startAt` (Number | String | Date): For `every`, the first run. Without it, the first run is one interval after this call. A `startAt` in the past sets where the intervals line up, and the first run is the next one after this call. For example, `every: '1d'` with `startAt: '2026-01-01'` runs at midnight UTC every day. For `cron`, the earliest time the schedule may run. At most 366 days ahead.
- `expiresAt` (Number | String | Date): The last time the schedule may run. A run due at exactly this time still runs.
- `maxRuns` (Number): How many slots the schedule has, from 1 to 100,000. It ends at its `maxRuns`-th slot counted from the first. It counts slots, not runs that happened, so slots skipped while the schedule was behind or suspended (see [When a schedule runs](#when-a-schedule-runs)) still count, and the retries of one slot count once. With `expiresAt` too, the one that comes first ends the schedule.
- `handler` (Function | String | Object): The handler code, as a function, a source string, or `{ file: '~/AppData/…/handler.js' }`. Required unless you pass `handlerName`. Without `handlerName`, the source is sent and published into the signed-in user's own user scope, and every run calls it. With `handlerName`, only its hash is sent, and the schedule is created only if it matches what's published under that name. It never runs in this client.
- `handlerName` (String): The published handler each run calls. Required unless you pass `handler`.
- `handlerScope` (String): Where `handlerName` is looked up, `'app'` or `'user'`. Defaults to `'app'`, the handlers the app's owner published. `'user'` binds to a handler the signed-in user's scope holds, published with `handlers.publish(name, handler, { scope: 'user' })`.
- `handlerHash` (String): The SHA-256 hex digest of the handler source, in place of `handler`, to check it against `handlerName`.
- `context` (Object): Values the handler needs, passed to every run as a frozen `ctx`. Up to 4 KB serialized. It's read once, at this call. To replace it, use [`updateSchedule()`](/Events/updateSchedule/).
## Return value
A `Promise` that resolves to the schedule. All times are in milliseconds since the epoch.
- `scheduleId` (String): Its id, which [`getSchedule()`](/Events/getSchedule/), [`updateSchedule()`](/Events/updateSchedule/) and [`removeSchedule()`](/Events/removeSchedule/) take.
- `kind` (String): `'recurring'` for `every` and `cron`, `'once'` for `at`, and `'deferred'` for a notification sent later with [`notify()`](/Notifications/notify/#send-it-later).
- `appUid` (String): The app that created it.
- `handlerName` (String | null): The handler each run calls, or `null` once the schedule has ended. For a schedule created with an inline `handler`, it's the name Puter gave the handler, which starts with `@`.
- `handlerScope` (String): `'user'` when the handler is in the user's own [user scope](/Events/handlers/#user-scope). Absent for an app handler.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values. The `contextKeys` field is `null` when there's no context, and once the schedule has ended.
- `every` (Number | null): The interval, in milliseconds, of an `every` schedule.
- `cron` (String | null): The expression of a `cron` schedule.
- `tz` (String): The time zone of a `cron` schedule, and `'UTC'` for the others.
- `startAt` (Number): The first time it may run. For `at`, its only run.
- `endsAt` (Number | null): The last time it may run, from `expiresAt` or `maxRuns`. For `at`, its only run.
- `state` (String): `'active'`, `'suspended'`, `'sending'`, or `'ended'`. A delayed notification is `'sending'` during a send attempt. A failed attempt can return it to `'active'` before retrying.
- `suspendedReason` (String | null): Why it's [suspended](#suspended-and-ended-schedules).
- `endReason` (String | null), `endedAt` (Number | null): Why and when it [ended](#suspended-and-ended-schedules).
- `nextRunAt` (Number | null): The next slot of the schedule, worked out from its definition and the clock. A late or retried run for an earlier slot can still happen first. After the last slot is due, it stays at that slot until the run for it is done. It's `null` while the schedule is suspended or sending, and once it has ended.
- `createdAt` (Number): When it was created.
- `off()` (Function): Removes the schedule. Same as [`puter.events.removeSchedule(scheduleId)`](/Events/removeSchedule/). Only on the object `onSchedule()` returns.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_value_too_large` | A field is longer than can be stored. |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `invalid_request` | `options` isn't an object. |
| `events_handler_required` | There's neither a `handler` nor a `handlerName`. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` is empty, too long, has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_schedule_app_required` | The call wasn't made by an app, for example from Node.js with an account token. |
| `events_durable_requires_account` | The call came from a scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, or from a temporary (guest) account. |
| `too_many_requests` | Over the create rate limit, which is shared with subscribing. |
| `events_background_consent_required` | The user hasn't granted your app `events:background`. |
| `events_schedule_invalid` | An option is malformed. For example, more than one of `every`, `cron` and `at`, an `every` that isn't a whole number of seconds, a time with no zone, an `at` less than 1 second or more than 366 days ahead, an unsupported cron expression, an unknown `tz`, or `tz` without `cron`. The message says which. |
| `events_schedule_never_fires` | The schedule would never run. Its first run or its `startAt` is more than 366 days away, or it ends before its first run. |
| `events_schedule_too_frequent` | It would run more often than your plan's [minimum interval](#how-often-a-schedule-can-run). |
| `events_schedule_too_deep` | The call was made from a handler at the end of a [handler chain](/Events/onPersistent/#handlers-that-trigger-handlers), so the schedule could never run. |
| `bad_request` | `handlerName` is empty or over 128 characters, `handlerHash` isn't a SHA-256 hex digest, or `handlerScope` isn't `'app'` or `'user'`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope. The schedule isn't created. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_schedule_limit` | The user holds as many schedules as their plan allows, for your app or in total. |
| `events_schedule_budget` | The schedule would make your app's schedules, or all of the user's schedules, run more times an hour than their plan allows. |
| `events_schedule_busy` | Puter is checking too many cron expressions at once. Try again in a moment. |
| `events_disabled` | Schedules aren't available on this server, as on self-hosted servers. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
## Times
### Times
The `at`, `startAt` and `expiresAt` options each take one of these:
@@ -213,15 +144,15 @@ A run's `event` carries:
| Field | Type | Description |
| --- | --- | --- |
| `subject` | `String` | `schedule:<scheduleId>`. |
| `op` | `String` | Always `'tick'`. |
| `id` | `String` | `<scheduleId>:<scheduledFor>`. The same on every attempt at one run, so use it to skip work you've already done. |
| `scheduleId` | `String` | The schedule this run belongs to. |
| `scheduledFor` | `Number` | The slot this run is for, in milliseconds since the epoch. |
| `firedAt` | `Number` | When this attempt was sent to the handler, in milliseconds since the epoch. |
| `missed` | `Number` | Slots skipped since the last run, for example while the schedule was suspended. Only this run happens for them. |
| `missedCapped` | `Boolean` | Present, and `true`, when `missed` stopped counting at 1,000. |
| `attempt` | `Number` | Attempts at this run, this one included. `1` on the first try. |
| `subject` | String | `schedule:<scheduleId>`. |
| `op` | String | Always `'tick'`. |
| `id` | String | `<scheduleId>:<scheduledFor>`. The same on every attempt at one run, so use it to skip work you've already done. |
| `scheduleId` | String | The schedule this run belongs to. |
| `scheduledFor` | Number | The slot this run is for, in milliseconds since the epoch. |
| `firedAt` | Number | When this attempt was sent to the handler, in milliseconds since the epoch. |
| `missed` | Number | Slots skipped since the last run, for example while the schedule was suspended. Only this run happens for them. |
| `missedCapped` | Boolean | Present, and `true`, when `missed` stopped counting at 1,000. |
| `attempt` | Number | Attempts at this run, this one included. `1` on the first try. |
The `user` binding is valid for 15 minutes, so use it only during the run. Writes made through `user` count toward the same [handler chain](/Events/onPersistent/#handlers-that-trigger-handlers) limit as a subscription's, starting from the depth of the call that created the schedule.
@@ -277,11 +208,74 @@ An ended schedule never runs again. It has `state: 'ended'` and an `endReason`,
When schedules end with `permission_revoked`, the user's app gets an `app.events.ended` notification about them, which you can read with [`puter.events.fetch()`](/Events/fetch/).
## Return value
A `Promise` that resolves to the schedule. All times are in milliseconds since the epoch.
- `scheduleId` (String): Its id, which [`getSchedule()`](/Events/getSchedule/), [`updateSchedule()`](/Events/updateSchedule/) and [`removeSchedule()`](/Events/removeSchedule/) take.
- `kind` (String): `'recurring'` for `every` and `cron`, `'once'` for `at`, and `'deferred'` for a notification sent later with [`notify()`](/Notifications/notify/#send-it-later).
- `appUid` (String): The app that created it.
- `handlerName` (String | null): The handler each run calls, or `null` once the schedule has ended. For a schedule created with an inline `handler`, it's the name Puter gave the handler, which starts with `@`.
- `handlerScope` (String): `'user'` when the handler is in the user's own [user scope](/Events/handlers/#user-scope). Absent for an app handler.
- `contextKeys` (Array | null), `contextHash` (String | null): The key names and a hash of the stored context, never its values. The `contextKeys` field is `null` when there's no context, and once the schedule has ended.
- `every` (Number | null): The interval, in milliseconds, of an `every` schedule.
- `cron` (String | null): The expression of a `cron` schedule.
- `tz` (String): The time zone of a `cron` schedule, and `'UTC'` for the others.
- `startAt` (Number): The first time it may run. For `at`, its only run.
- `endsAt` (Number | null): The last time it may run, from `expiresAt` or `maxRuns`. For `at`, its only run.
- `state` (String): `'active'`, `'suspended'`, `'sending'`, or `'ended'`. A delayed notification is `'sending'` during a send attempt. A failed attempt can return it to `'active'` before retrying.
- `suspendedReason` (String | null): Why it's [suspended](#suspended-and-ended-schedules).
- `endReason` (String | null), `endedAt` (Number | null): Why and when it [ended](#suspended-and-ended-schedules).
- `nextRunAt` (Number | null): The next slot of the schedule, worked out from its definition and the clock. A late or retried run for an earlier slot can still happen first. After the last slot is due, it stays at that slot until the run for it is done. It's `null` while the schedule is suspended or sending, and once it has ended.
- `createdAt` (Number): When it was created.
- `off()` (Function): Removes the schedule. Same as [`puter.events.removeSchedule(scheduleId)`](/Events/removeSchedule/). Only on the object `onSchedule()` returns.
The promise rejects with `{ message, code }`:
| `code` | Meaning |
| --- | --- |
| `events_value_too_large` | A field is longer than can be stored. |
| `events_handler_conflict` | The inline handler couldn't be confirmed after a concurrent publish. Try again. |
| `invalid_request` | `options` isn't an object. |
| `events_handler_required` | There's neither a `handler` nor a `handlerName`. |
| `events_user_handlers_disabled` | Publishing into a user scope isn't turned on for this server. |
| `events_handler_forbidden` | The call can't publish into a user scope: it came from a scoped access token, a temporary account, or on behalf of a different app. |
| `insufficient_funds` | Publishing into a user scope needs credit on a hosted Puter server, and the user has none. Arrives as HTTP 402. |
| `forbidden` | The user already holds as many [worker units](/rate-limits-and-quotas/#worker-units) as their plan allows, so a new user scope can't be created. |
| `events_handler_limit` | The user scope already holds the [maximum number of handlers](/rate-limits-and-quotas/#handlers). |
| `events_handler_too_large` | The handler is over 64 KB. |
| `events_worker_too_large` | The user scope's handlers would exceed 1 MB combined. |
| `events_handler_name_invalid` | `handlerName` is empty, too long, has characters that aren't allowed, or starts with `@`, which is reserved for inline handlers. |
| `events_handler_free_variable` | The handler uses an outside variable. The message names it. |
| `events_handler_invalid` | `handler` isn't a function, a source string, or `{ file }`. |
| `events_handler_hash_unavailable` | This environment has no `crypto.subtle`, so `handler` can't be hashed. Pass `handlerName` alone. |
| `events_context_invalid` | `context` isn't JSON-serializable. |
| `events_context_too_large` | The serialized `context` is over 4 KB. |
| `auth_canceled` | Nobody was signed in, and the user closed the sign-in without finishing it. |
| `events_schedule_app_required` | The call wasn't made by an app, for example from Node.js with an account token. |
| `events_durable_requires_account` | The call came from a scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, or from a temporary (guest) account. |
| `too_many_requests` | Over the create rate limit, which is shared with subscribing. |
| `events_background_consent_required` | The user hasn't granted your app `events:background`. |
| `events_schedule_invalid` | An option is malformed. For example, more than one of `every`, `cron` and `at`, an `every` that isn't a whole number of seconds, a time with no zone, an `at` less than 1 second or more than 366 days ahead, an unsupported cron expression, an unknown `tz`, or `tz` without `cron`. The message says which. |
| `events_schedule_never_fires` | The schedule would never run. Its first run or its `startAt` is more than 366 days away, or it ends before its first run. |
| `events_schedule_too_frequent` | It would run more often than your plan's [minimum interval](#how-often-a-schedule-can-run). |
| `events_schedule_too_deep` | The call was made from a handler at the end of a [handler chain](/Events/onPersistent/#handlers-that-trigger-handlers), so the schedule could never run. |
| `bad_request` | `handlerName` is empty or over 128 characters, `handlerHash` isn't a SHA-256 hex digest, or `handlerScope` isn't `'app'` or `'user'`. |
| `events_handler_not_found` | Nothing is published under `handlerName` in that scope. The schedule isn't created. |
| `events_handler_hash_mismatch` | The published handler isn't the source you passed as `handler`. |
| `events_schedule_limit` | The user holds as many schedules as their plan allows, for your app or in total. |
| `events_schedule_budget` | The schedule would make your app's schedules, or all of the user's schedules, run more times an hour than their plan allows. |
| `events_schedule_busy` | Puter is checking too many cron expressions at once. Try again in a moment. |
| `events_disabled` | Schedules aren't available on this server, as on self-hosted servers. |
| `events_failed` | The server sent a response the SDK couldn't read. |
With a `{ file }` handler, errors from [`puter.fs.read()`](/FS/read/) also pass through.
## Examples
The handler is published once, by the app's developer, from a deploy script or the browser console. The schedule is created from the app, for each user.
### Run a handler on weekday mornings in the user's time zone
<strong class="example-title">Run a handler on weekday mornings in the user's time zone</strong>
```js
// Deploy script, run as the app's developer
@@ -314,7 +308,7 @@ const schedule = await puter.events.onSchedule({
if (schedule.nextRunAt !== null) console.log(`next digest at ${new Date(schedule.nextRunAt).toString()}`);
```
### Run once, an hour from now
<strong class="example-title">Run once, an hour from now</strong>
```js
const reminder = await puter.events.onSchedule({
@@ -330,7 +324,7 @@ await puter.events.updateSchedule(reminder.scheduleId, { at: Date.now() + 2 * 60
await reminder.off();
```
### Run every 6 hours, on the hour, 28 times
<strong class="example-title">Run every 6 hours, on the hour, 28 times</strong>
```js
await puter.events.onSchedule({
+2 -6
View File
@@ -4,11 +4,9 @@ description: End a schedule, or cancel a notification stored to send later.
platforms: [websites, apps, nodejs, workers]
---
Ends a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
It doesn't run again, and it stays in [`listSchedules()`](/Events/listSchedules/) for 7 days with `endReason: 'removed'`. A run that already started isn't stopped.
Ends a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/). It doesn't run again, and it stays in [`listSchedules()`](/Events/listSchedules/) for 7 days with `endReason: 'removed'`. A run that already started isn't stopped.
It also cancels a notification your app stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later), the same as [`puter.notifications.cancel()`](/Notifications/cancel/).
@@ -32,8 +30,6 @@ A `Promise` that resolves when the schedule has ended.
An app can only remove schedules it created. An account session can remove any of the user's schedules, including ones left by apps they no longer use. A scoped access token can't remove any.
## Errors
An id this caller doesn't hold, or a schedule that already ended, is reported as not existing, so removing a schedule twice rejects the second time. With `events_schedule_sending`, `auth_canceled`, `too_many_requests` or `events_disabled`, nothing was removed. When the call fails any other way, such as a network error or `events_failed`, the removal may still have happened, so read the schedule again with [`getSchedule()`](/Events/getSchedule/) to find out.
It rejects with `{ message, code }`:
@@ -49,7 +45,7 @@ It rejects with `{ message, code }`:
## Examples
### Cancel a notification, then read it
<strong class="example-title">Cancel a notification, then read it</strong>
```html;events-remove-schedule
<html>
+20 -22
View File
@@ -4,11 +4,9 @@ description: The subject strings Events subscriptions watch, and the events they
platforms: [websites, apps, nodejs, workers]
---
A subject is the string that says what a subscription watches.
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
[`onLocal()`](/Events/onLocal/) and [`onPersistent()`](/Events/onPersistent/) take the same subjects and deliver the same events.
A subject is the string that says what a subscription watches. [`onLocal()`](/Events/onLocal/) and [`onPersistent()`](/Events/onPersistent/) take the same subjects and deliver the same events.
## Syntax
@@ -151,30 +149,30 @@ The handler is called with `{ event }`. A file change carries:
| Field | Type | Description |
| --- | --- | --- |
| `id` | `String` | Unique id for the event. |
| `subject` | `String` | The node it happened to, as `fs:<uid>:<op>`. Not the subject you subscribed with. |
| `op` | `String` | `add` (a create, or a copy's destination), `write`, `move` (a move or a rename), or `remove`. |
| `uid` | `String` | The uid of the node that changed. |
| `path` | `String` | The path of the node that changed. In another user's files, it's a [masked path](/FS/listShared/), `/<owner>/<uid>/<name>/…`, where `<uid>` and `<name>` are those of the node the subscription is attached to. |
| `from` | `String` | On a `move`, the path the node left, masked the same way. Only present when the subscription was watching that location. |
| `self` | `Boolean` | `true` when the account holding the subscription made the change. Mail filed into the account's `~/.mail` folder is always `false`, including mail the account sent to itself. |
| `viaWorker` | `Boolean` | `true` when the change came from server-side code running as an account, such as a worker using `me.puter` or an [events handler](/Events/handlers/) running in the events worker. A worker using `user.puter` acts as the user who called it, so its changes are that user's own, with `viaWorker` set to `false`. A handler running in a client writes as that client, also with `viaWorker` set to `false`. To skip your own changes, check `self && !viaWorker`, which still lets through the ones a worker made as your account. |
| `ts` | `Number` | When it happened, in milliseconds since the epoch. |
| `seq` | `Number` | Position within one dispatch, when a change goes to several subscriptions. |
| `id` | String | Unique id for the event. |
| `subject` | String | The node it happened to, as `fs:<uid>:<op>`. Not the subject you subscribed with. |
| `op` | String | `add` (a create, or a copy's destination), `write`, `move` (a move or a rename), or `remove`. |
| `uid` | String | The uid of the node that changed. |
| `path` | String | The path of the node that changed. In another user's files, it's a [masked path](/FS/listShared/), `/<owner>/<uid>/<name>/…`, where `<uid>` and `<name>` are those of the node the subscription is attached to. |
| `from` | String | On a `move`, the path the node left, masked the same way. Only present when the subscription was watching that location. |
| `self` | Boolean | `true` when the account holding the subscription made the change. Mail filed into the account's `~/.mail` folder is always `false`, including mail the account sent to itself. |
| `viaWorker` | Boolean | `true` when the change came from server-side code running as an account, such as a worker using `me.puter` or an [events handler](/Events/handlers/) running in the events worker. A worker using `user.puter` acts as the user who called it, so its changes are that user's own, with `viaWorker` set to `false`. A handler running in a client writes as that client, also with `viaWorker` set to `false`. To skip your own changes, check `self && !viaWorker`, which still lets through the ones a worker made as your account. |
| `ts` | Number | When it happened, in milliseconds since the epoch. |
| `seq` | Number | Position within one dispatch, when a change goes to several subscriptions. |
A key-value change carries `key` instead of `uid` and `path`, and different ops:
| Field | Type | Description |
| --- | --- | --- |
| `id` | `String` | Unique id for the event. |
| `subject` | `String` | `kv:<appId>:<key>`, naming the key that changed. Through a share, `kv:<handle>:<key>`. |
| `op` | `String` | `set` for a write, `del` for a removal, `expire` when only the key's lifetime changed. |
| `key` | `String` | The key that changed. Through a share, relative to the handle. |
| `value` | `Any` | The new value, or `null` on a `del`. Only with `includeValue`, and only within the [limits above](#getting-the-new-value). Never on an `expire`. |
| `self` | `Boolean` | As above. |
| `viaWorker` | `Boolean` | As above. |
| `ts` | `Number` | As above. |
| `seq` | `Number` | As above. |
| `id` | String | Unique id for the event. |
| `subject` | String | `kv:<appId>:<key>`, naming the key that changed. Through a share, `kv:<handle>:<key>`. |
| `op` | String | `set` for a write, `del` for a removal, `expire` when only the key's lifetime changed. |
| `key` | String | The key that changed. Through a share, relative to the handle. |
| `value` | Any | The new value, or `null` on a `del`. Only with `includeValue`, and only within the [limits above](#getting-the-new-value). Never on an `expire`. |
| `self` | Boolean | As above. |
| `viaWorker` | Boolean | As above. |
| `ts` | Number | As above. |
| `seq` | Number | As above. |
A posted notification carries the fields listed on [`fetch()`](/Events/fetch/#return-value). An app message's live dismissal carries `op: 'dismiss'` and its `uid`, with no `notification` content. Dismissals follow the same audience rules. The notification SDK exposes them through [`on('dismiss')`](/Notifications/on/).
+2 -6
View File
@@ -4,11 +4,9 @@ description: End a persistent subscription.
platforms: [websites, apps, nodejs, workers]
---
Ends a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
It stops right away, and any undelivered backlog is dropped. For a session subscription from [`puter.events.onLocal()`](/Events/onLocal/), use [`subscription.off()`](/Events/off/).
Ends a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/). It stops right away, and any undelivered backlog is dropped. For a session subscription from [`puter.events.onLocal()`](/Events/onLocal/), use [`subscription.off()`](/Events/off/).
An app can end only the subscriptions it created. Outside an app, you can end any of yours, including ones left by deleted apps. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, can't end any.
@@ -28,8 +26,6 @@ The `subId` of the subscription, from [`onPersistent()`](/Events/onPersistent/)
A `Promise` that resolves when the subscription is gone.
## Errors
An id you don't hold, because it already ended or another app created it, is reported as not existing, so the call doesn't reveal which subscriptions exist. If the call rejects with any other code, the subscription is still running, and so is any handler it runs on this page.
The promise rejects with `{ message, code }`:
@@ -45,7 +41,7 @@ The promise rejects with `{ message, code }`:
## Examples
### Create a persistent subscription, then end it
<strong class="example-title">Create a persistent subscription, then end it</strong>
```html;events-unsubscribe
<html>
+2 -6
View File
@@ -4,11 +4,9 @@ description: Change the context of a persistent subscription without ending it.
platforms: [websites, apps, nodejs, workers]
---
Changes the `context` of a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
The subscription keeps its `subId`, its handler, and any events it hasn't delivered yet, and later deliveries in the events worker run with the new `context` as `ctx`. Ending the subscription and subscribing again would give it a new `subId` and drop its undelivered events. To change a [schedule's](/Events/onSchedule/) context, use [`updateSchedule()`](/Events/updateSchedule/).
Changes the `context` of a subscription created with [`puter.events.onPersistent()`](/Events/onPersistent/). The subscription keeps its `subId`, its handler, and any events it hasn't delivered yet, and later deliveries in the events worker run with the new `context` as `ctx`. Ending the subscription and subscribing again would give it a new `subId` and drop its undelivered events. To change a [schedule's](/Events/onSchedule/) context, use [`updateSchedule()`](/Events/updateSchedule/).
An app can change only the subscriptions it created. Outside an app, you can change any of yours. A scoped access token, such as the one in a [`getReadURL()`](/FS/getReadURL/) URL, can't change any.
@@ -33,8 +31,6 @@ A `Promise` that resolves to the updated subscription, in the same shape [`puter
A delivery already running when you call `update()` finishes with the old context. A suspended subscription stays suspended and uses the new context once it resumes. If this page runs a function `handler` for the subscription, that handler gets the new context too. Handlers in other open pages keep the context they registered with.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -51,7 +47,7 @@ The promise rejects with `{ message, code }`:
## Examples
### Point a subscription at a new endpoint
<strong class="example-title">Point a subscription at a new endpoint</strong>
```html;events-update
<html>
+7 -34
View File
@@ -4,11 +4,9 @@ description: Move a schedule to a new time, change its context, or edit a notifi
platforms: [websites, apps, nodejs, workers]
---
Changes a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or a notification stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
The schedule keeps its `scheduleId`, its kind and its handler, so ids you saved elsewhere stay valid.
Changes a schedule created with [`puter.events.onSchedule()`](/Events/onSchedule/), or a notification stored to send later with [`puter.notifications.notify()`](/Notifications/notify/#send-it-later). The schedule keeps its `scheduleId`, its kind and its handler, so ids you saved elsewhere stay valid.
An app can change only the schedules it created. An account session can change any of the user's schedules. A scoped access token can't change any. On a website with nobody signed in, the call asks the user to sign in first, as other Puter.js calls do.
@@ -28,36 +26,13 @@ The `scheduleId` from [`onSchedule()`](/Events/onSchedule/), [`notify()`](/Notif
For a schedule from [`onSchedule()`](/Events/onSchedule/), pass new timing, a new `context`, or both:
| Option | Type | Description |
|--------|------|-------------|
| `every` | `Number \| String` | The new interval. A recurring schedule can switch between `every` and `cron`. |
| `cron` | `String` | The new cron expression. A recurring schedule can switch between `every` and `cron`. |
| `at` | `Number \| String \| Date` | The new time for a one-time schedule. An `at` schedule stays a one-time schedule. |
| `context` | `Object \| null` | Replaces the whole context. Pass `null` to clear it. Up to 4 KB serialized, as in [`onSchedule()`](/Events/onSchedule/#parameters). |
| `tz` | `String` | The time zone the `cron` expression runs in. |
| `startAt` | `Number \| String \| Date` | For `every`, the first run. For `cron`, the earliest time the schedule may run. |
| `expiresAt` | `Number \| String \| Date` | The last time the schedule may run. |
| `maxRuns` | `Number` | How many slots the schedule has. |
The timing options are `at`, `every`, `cron`, `tz`, `startAt`, `expiresAt` and `maxRuns`. Any of them replaces the whole timing, so pass exactly one of `at`, `every` or `cron`, together with every other timing option you want to keep. They take the same values as in [`onSchedule()`](/Events/onSchedule/#parameters). Without timing options, the timing stays as it is.
- **Timing.** Any of `at`, `every`, `cron`, `tz`, `startAt`, `expiresAt` and `maxRuns` replaces the whole timing, so pass exactly one of `at`, `every` or `cron`, together with every other timing option you want to keep. They take the same values as in [`onSchedule()`](/Events/onSchedule/#parameters). A recurring schedule can switch between `every` and `cron`, and an `at` schedule stays a one-time schedule. Without timing options, the timing stays as it is.
- `context` (Object | null): Replaces the whole context. Pass `null` to clear it. Up to 4 KB serialized, as in [`onSchedule()`](/Events/onSchedule/#parameters).
For a stored notification, pass a new `sendAt`, new content, or both:
| Option | Type | Description |
|--------|------|-------------|
| `sendAt` | `Number \| String \| Date` | The new time to send it, as in [`notify()`](/Notifications/notify/#parameters). A time within 5 seconds, or in the past, sends it now, with the [retries](/Notifications/notify/#send-it-later) of any stored notification. |
| `title` | `String` | Replaces the stored title. It can't be cleared. |
| `text` | `String` | Replaces the stored text. |
| `icon` | `String` | Replaces the stored icon. |
| `target` | `String` | Replaces the stored target. |
| `data` | `Any` | Replaces the stored data. |
| `group` | `String` | Replaces the stored group. |
| `channel` | `String` | Replaces the stored channel. |
| `sensitive` | `Boolean` | Replaces the stored `sensitive` setting. |
| `priority` | `String` | Replaces the stored priority. |
| `ttl` | `Number` | Replaces the stored `ttl`. |
The content options follow the same rules as in [`notify()`](/Notifications/notify/#parameters). Fields you leave out keep their values. Pass `null` to clear an optional field.
- `sendAt` (Number | String | Date): The new time to send it, as in [`notify()`](/Notifications/notify/#parameters). A time within 5 seconds, or in the past, sends it now, with the [retries](/Notifications/notify/#send-it-later) of any stored notification.
- `title`, `text`, `icon`, `target`, `data`, `group`, `channel`, `sensitive`, `priority`, `ttl`: Replace the stored values, with the same rules as [`notify()`](/Notifications/notify/#parameters). Fields you leave out keep their values. Pass `null` to clear an optional field. The `title` can't be cleared.
The handler and the recipient can't change. Passing `handler`, `handlerName`, `handlerScope`, `handlerHash`, `handlerSource` or `to` rejects with `invalid_request`. To run different code, remove the schedule and create a new one.
@@ -65,8 +40,6 @@ The handler and the recipient can't change. Passing `handler`, `handlerName`, `h
A `Promise` that resolves to the updated schedule, in the shape [`getSchedule()`](/Events/getSchedule/#return-value) returns. Its `nextRunAt` is the next run under the new timing. It describes the context by its key names and a hash, and never includes a stored notification's content. A stored notification whose new `sendAt` is due now is sent during the call, so the schedule can come back already ended.
## Errors
The promise rejects with `{ message, code }`:
| `code` | Meaning |
@@ -98,7 +71,7 @@ The promise rejects with `{ message, code }`:
## Examples
### Move a reminder to a later time
<strong class="example-title">Move a reminder to a later time</strong>
```html;events-update-reminder
<html>
@@ -130,7 +103,7 @@ The promise rejects with `{ message, code }`:
</html>
```
### Move a weekday schedule to another time
<strong class="example-title">Move a weekday schedule to another time</strong>
```html;events-update-cron
<html>
+7 -19
View File
@@ -4,11 +4,9 @@ description: List and destroy the events worker a published handler set stands u
platforms: [websites, apps, nodejs, workers]
---
An **events worker** runs published [handlers](/Events/handlers/), the app's own or one user's in a [user scope](/Events/handlers/#user-scope).
<div class="info">The Events API is in beta. Event shapes, limits, and behavior may change between releases.</div>
It runs them for every event on a subscription with a `handlerName`, whether or not a client is connected, for a [`queue`](/Events/onPersistent/#choosing-a-mode) delivery once no connected client takes it, and for every run of a [schedule](/Events/onSchedule/). Each app has at most one for its own handlers, created when it publishes its first handler. Each user scope is a unit of its own, created when the user's first handler in an app is published, whether by publishing it or by passing an inline `handler`.
An **events worker** runs published [handlers](/Events/handlers/), the app's own or one user's in a [user scope](/Events/handlers/#user-scope). It runs them for every event on a subscription with a `handlerName`, whether or not a client is connected, for a [`queue`](/Events/onPersistent/#choosing-a-mode) delivery once no connected client takes it, and for every run of a [schedule](/Events/onSchedule/). Each app has at most one for its own handlers, created when it publishes its first handler. Each user scope is a unit of its own, created when the user's first handler in an app is published, whether by publishing it or by passing an inline `handler`.
A hosted Puter server may bill each app's events worker as a monthly cost, even if nothing ever delivers to it, and bills a user scope to the user the same way. Use this API to see which apps and scopes have one and remove the ones you don't need.
@@ -30,12 +28,8 @@ puter.events.workers.list()
puter.events.workers.list(options)
```
The `options` object takes these options:
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Apps per page. |
| `cursor` | `String` | The `cursor` from a previous page. Leave it off to start from the first page. |
- `options.limit` (Number): Apps per page.
- `options.cursor` (String): The `cursor` from a previous page. Leave it off to start from the first page.
Resolves to `{ items, cursor, deployable }`:
@@ -50,13 +44,7 @@ puter.events.workers.destroy(appUid)
puter.events.workers.destroy(appUid, options)
```
The `options` object takes these options:
| Option | Type | Description |
|--------|------|-------------|
| `scope` | `String` | Either `'app'` or `'user'`. Defaults to `'app'`. With `'user'`, it removes the signed-in user's own scope of the app. |
Inside an app, `appUid` can only name that app. With an account session, outside an app such as the desktop or Node.js with your account token, `appUid` can name any app you hold a user scope in, and it works even when the server has user-scope handlers turned off.
- `options.scope` (String): `'app'` or `'user'`. Defaults to `'app'`. `'user'` removes the signed-in user's own scope of the app. Inside an app, `appUid` can only name that app. With an account session, outside an app such as the desktop or Node.js with your account token, `appUid` can name any app you hold a user scope in, and it works even when the server has user-scope handlers turned off.
Removes every handler the app has published, or every handler in the user's scope with `scope: 'user'`, the same as calling [`puter.events.handlers.remove()`](/Events/handlers/) on each. Their subscriptions and schedules are suspended with `handler_not_found`, not deleted, and publishing the handlers again resumes them.
@@ -78,9 +66,9 @@ Both methods reject with `{ message, code }`:
| `events_disabled` | Events aren't enabled on this server. |
| `events_failed` | The server sent a response the SDK couldn't read. |
## Examples
## Example
### List your events workers, and destroy one you no longer need
<strong class="example-title">List your events workers, and destroy one you no longer need</strong>
This runs in Node.js signed in with your account token.
@@ -95,7 +83,7 @@ const destroyed = await puter.events.workers.destroy(appUid); // an app you ow
console.log(`removed ${destroyed.removed}, suspended ${destroyed.suspended}`);
```
### Remove the signed-in user's scope of your app
<strong class="example-title">Remove the signed-in user's scope of your app</strong>
The user scope belongs to the user, so it needs no owner step. In your app, name the app itself. With an account session outside an app, name any app you hold a scope in.
+6 -6
View File
@@ -298,14 +298,15 @@ These cloud storage features are supported out of the box when using Puter.js:
- **[`puter.fs.write()`](/FS/write/)** - Write data to a file
- **[`puter.fs.read()`](/FS/read/)** - Read data from a file
- **[`puter.fs.upload()`](/FS/upload/)** - Upload a file from the local system
- **[`puter.fs.readdir()`](/FS/readdir/)** - List contents of a directory
- **[`puter.fs.mkdir()`](/FS/mkdir/)** - Create a directory
- **[`puter.fs.delete()`](/FS/delete/)** - Delete a file or directory
- **[`puter.fs.stat()`](/FS/stat/)** - Get information about a file or directory
- **[`puter.fs.readdir()`](/FS/readdir/)** - List contents of a directory
- **[`puter.fs.rename()`](/FS/rename/)** - Rename a file or directory
- **[`puter.fs.move()`](/FS/move/)** - Move a file or directory
- **[`puter.fs.copy()`](/FS/copy/)** - Copy a file or directory
- **[`puter.fs.move()`](/FS/move/)** - Move a file or directory
- **[`puter.fs.stat()`](/FS/stat/)** - Get information about a file or directory
- **[`puter.fs.space()`](/FS/space/)** - Get the user's storage capacity and usage
- **[`puter.fs.delete()`](/FS/delete/)** - Delete a file or directory
- **[`puter.fs.upload()`](/FS/upload/)** - Upload a file from the local system
- **[`puter.fs.getReadURL()`](/FS/getReadURL/)** - Generate a URL that can be used to read a file
- **[`puter.fs.revokeReadURL()`](/FS/revokeReadURL/)** - Revoke a URL created by `getReadURL()`
- **[`puter.fs.share()`](/FS/share/)** - Give another user access to a file or directory
@@ -314,7 +315,6 @@ These cloud storage features are supported out of the box when using Puter.js:
- **[`puter.fs.listSharedByMe()`](/FS/listSharedByMe/)** - List everything you have shared out
- **[`puter.fs.getShares()`](/FS/getShares/)** - List who has access to an item
- **[`puter.fs.getShareLink()`](/FS/getShareLink/)** - Build a link that opens a file in an app
- **[`puter.fs.space()`](/FS/space/)** - Get the user's storage capacity and usage
## Examples
+7 -13
View File
@@ -30,25 +30,19 @@ Relative paths resolve against the app's root directory. A relative name that lo
The options for the `copy` operation. The following options are supported:
| Option | Type | Description |
|--------|------|-------------|
| `source` | `String` | Path to the file or directory to copy. Required when passing options as the only argument. |
| `destination` | `String` | Path to the destination. Required when passing options as the only argument. |
| `overwrite` | `Boolean` | Whether to overwrite the destination file or directory if it already exists. Defaults to `false`. |
| `newName` | `String` | The new name to use for the copied file or directory. Defaults to `undefined`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file or directory name if it already exists. Defaults to `false`. |
- `source` (String) - Path to the file or directory to copy. Required when passing options as the only argument.
- `destination` (String) - Path to the destination. Required when passing options as the only argument.
- `overwrite` (Boolean) - Whether to overwrite the destination file or directory if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the file or directory name if it already exists. Defaults to `false`.
- `newName` (String) - The new name to use for the copied file or directory. Defaults to `undefined`.
## Return value
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the copied file or directory.
## Errors
If the source file or directory does not exist, the promise will be rejected with an error.
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the copied file or directory. If the source file or directory does not exist, the promise will be rejected with an error.
## Examples
### Copy a file
<strong class="example-title"> Copy a file</strong>
```html;fs-copy
<html>
+5 -7
View File
@@ -25,11 +25,9 @@ If a path is not absolute, it will be resolved relative to the app's root direct
The options for the `delete` operation. The following options are supported:
| Option | Type | Description |
|--------|------|-------------|
| `paths` | `String \| String[]` | A single path or array of paths to delete. Required when passing options as the only argument. |
| `recursive` | `Boolean` | Whether to delete the directory recursively. Defaults to `true`. |
| `descendantsOnly` | `Boolean` | Whether to delete only the descendants of the directory and not the directory itself. Defaults to `false`. |
- `paths` (String | String[]) - A single path or array of paths to delete. Required when passing options as the only argument.
- `recursive` (Boolean) - Whether to delete the directory recursively. Defaults to `true`.
- `descendantsOnly` (Boolean) - Whether to delete only the descendants of the directory and not the directory itself. Defaults to `false`.
## Return value
@@ -41,7 +39,7 @@ as deleting it here, and restoring it does not bring the shares back.
## Examples
### Delete a file
<strong class="example-title">Delete a file</strong>
```html;fs-delete
<html>
@@ -63,7 +61,7 @@ as deleting it here, and restoring it does not bring the shares back.
</html>
```
### Delete a directory
<strong class="example-title">Delete a directory</strong>
```html;fs-delete-directory
<html>
+2 -6
View File
@@ -4,9 +4,7 @@ description: Generate a temporary URL that lets anyone read one file from the us
platforms: [websites, apps, nodejs, workers]
---
Generates a URL that can be used to read a file.
To stop it from working before it expires, revoke it with [`revokeReadURL()`](/FS/revokeReadURL/).
Generates a URL that can be used to read a file. To stop it from working before it expires, revoke it with [`revokeReadURL()`](/FS/revokeReadURL/).
## Syntax
@@ -29,9 +27,7 @@ How long the URL stays valid, in [jsonwebtoken](https://github.com/auth0/node-js
A promise that resolves to a URL string that can be used to read the file.
## Examples
### Get a read URL for a file
## Example
```javascript
const url = await puter.fs.getReadURL("~/myfile.txt");
+11 -15
View File
@@ -4,9 +4,7 @@ description: Build a link that opens a file in an app on Puter, for the people t
platforms: [websites, apps, nodejs, workers]
---
Builds a link that opens a file in an app on Puter.
The link has the form `https://puter.com/app/<appName>?file=<uid>`. Send it to whoever the file is shared with. Following it signs them in if needed. Puter then asks them to allow the app to open the file, and opens the app with the file.
Builds the link that opens a file in an app on Puter, of the form `https://puter.com/app/<appName>?file=<uid>`. Send it to whoever the file is shared with: following it signs them in if needed, then opens the app with the file — after Puter has asked them to allow the app to open it.
The link carries no access of its own. It works for the file's owner, for anyone the file was shared with through [`share()`](/FS/share/), and for any signed-in account once the file is open to **anyone with the link**. For everyone else the file is not found, and the app opens without it.
@@ -32,11 +30,9 @@ The name of the app the link opens the file with. Defaults to the app the code i
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The file. Required when passing options as the only argument, unless `uid` is given. |
| `appName` | `String` | The name of the app the link opens the file with. Same as the `appName` argument. |
| `uid` | `String` | The file, by UID. Can be used instead of `path`. |
- `path` (String) - The file. Required when passing options as the only argument, unless `uid` is given.
- `uid` (String) - The file, by UID. Can be used instead of `path`.
- `appName` (String) - As above.
## Return value
@@ -56,14 +52,9 @@ A file that does not exist, or that you cannot see, rejects the way [`stat()`](/
The app opens on the recipient's Puter, and before it is handed the file Puter shows them what is being asked — which app, which file — and lets them refuse. Refused, the app still opens, just without the file. The app receives the access the recipient has: a file shared read-only opens read-only.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access, or open the file to anyone with the link
- [`puter.fs.getReadURL()`](/FS/getReadURL/) - A URL that reads the file's bytes without signing in
## Examples
### Open a shared file in an app
<strong class="example-title">Open a shared file in an app</strong>
```html;fs-getShareLink
<html>
@@ -83,10 +74,15 @@ The app opens on the recipient's Puter, and before it is handed the file Puter s
</html>
```
### Send a collaborator straight into your app
<strong class="example-title">Send a collaborator straight into your app</strong>
```js
// Inside a Puter app, the link opens the file in this app.
await puter.fs.share('draft.md', 'friend@example.com', 'write');
const link = await puter.fs.getShareLink('draft.md');
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access, or open the file to anyone with the link
- [`puter.fs.getReadURL()`](/FS/getReadURL/) - A URL that reads the file's bytes without signing in
+9 -13
View File
@@ -35,10 +35,8 @@ The path to the file or directory. If `path` is not absolute, it will be resolve
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The item. Required when passing options as the only argument. |
| `uid` | `String` | The item, by UID. Can be used instead of `path`. |
- `path` (String) - The item. Required when passing options as the only argument.
- `uid` (String) - The item, by UID. Can be used instead of `path`.
## Return value
@@ -58,18 +56,11 @@ It also includes **invitations** — shares aimed at an email address with no co
`recipientEmail` is set only for the item's **owner** and for whoever **sent** that invitation; for anyone else the invitation is listed without it. Someone else's invitation is not yours to cancel either, so nothing is lost with the address. An app never sees it, whoever it acts for.
## Errors
If you cannot see the item at all, this rejects the same way a missing file would — it will not confirm that the item exists.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.unshare()`](/FS/unshare/) - Withdraw access
## Examples
### See who can reach a file
<strong class="example-title">See who can reach a file</strong>
```html;fs-getShares
<html>
@@ -90,7 +81,7 @@ If you cannot see the item at all, this rejects the same way a missing file woul
</html>
```
### Withdraw everyone's access
<strong class="example-title">Withdraw everyone's access</strong>
```js
const shares = await puter.fs.getShares('report.txt');
@@ -98,3 +89,8 @@ for (const share of shares) {
await puter.fs.unshare('report.txt', share.holder);
}
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.unshare()`](/FS/unshare/) - Withdraw access
+11 -13
View File
@@ -29,11 +29,9 @@ puter.fs.listShared(options)
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum shares per page. |
| `cursor` | `String` | Continuation token from a previous page. |
| `includeTotal` | `Boolean` | Include the total count in the response. Defaults to `false`. |
- `limit` (Number) - Maximum shares per page.
- `cursor` (String) - Continuation token from a previous page.
- `includeTotal` (Boolean) - Include the total count in the response. Defaults to `false`.
## Return value
@@ -47,14 +45,9 @@ Iterate until `cursor` is absent rather than comparing `items.length` to `limit`
Items shared with you appear at a **masked path**, `/<owner>/<uid>/<name>`, where `<uid>` stands in for wherever the owner keeps the item. Pass that path back to any `puter.fs` method and it resolves normally; what it does not tell you is the folder the item lives in, or what sits beside it. Your own items are never listed here.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item you manage
## Examples
### List everything shared with you
<strong class="example-title">List everything shared with you</strong>
```html;fs-listShared
<html>
@@ -73,7 +66,7 @@ Items shared with you appear at a **masked path**, `/<owner>/<uid>/<name>`, wher
</html>
```
### Page through every share
<strong class="example-title">Page through every share</strong>
```js
let cursor;
@@ -85,7 +78,7 @@ do {
} while (cursor);
```
### Open a file someone shared with you
<strong class="example-title">Open a file someone shared with you</strong>
```js
const page = await puter.fs.listShared();
@@ -95,3 +88,8 @@ if (shared) {
puter.print(await blob.text());
}
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item you manage
+14 -18
View File
@@ -4,9 +4,7 @@ description: List everything you have shared with other users, across all items.
platforms: [websites, apps, nodejs, workers]
---
This method lists everything you have shared out, a page at a time, without naming an item first.
To list the shares on one item you already know, use [`getShares()`](/FS/getShares/). This method lists them when you don't know the item. The listing includes invites to addresses that have no account yet (marked `pending`), items you opened to anyone with the link (marked `anyone`), and, for items you own, shares that a delegate with `manage` access issued on your behalf.
This method lists everything you have shared out, a page at a time, without naming an item first. [`getShares()`](/FS/getShares/) answers the same question for one item you can already point at; this is what answers it when you can't. The listing includes invites to addresses that have no account yet (marked `pending`), items you opened to anyone with the link (marked `anyone`), and — for items you own — shares that a delegate with `manage` access issued on your behalf.
> **What an app sees.** An app never gets more reach than it was given: this
> listing shows an app only the shares on items it can reach in its own right.
@@ -26,12 +24,10 @@ puter.fs.listSharedByMe(options)
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum shares per page. |
| `cursor` | `String` | Continuation token from a previous page. |
| `includeTotal` | `Boolean` | Include the total count in the response. Defaults to `false`. |
| `appUid` | `String` | Narrow the listing to the shares one app issued in your name, or pass `'none'` for the ones you made yourself. An app calling this is bound to its own grants whatever it asks for. |
- `limit` (Number) - Maximum shares per page.
- `cursor` (String) - Continuation token from a previous page.
- `includeTotal` (Boolean) - Include the total count in the response. Defaults to `false`.
- `appUid` (String) - Narrow the listing to the shares one app issued in your name, or pass `'none'` for the ones you made yourself. An app calling this is bound to its own grants whatever it asks for.
## Return value
@@ -45,15 +41,9 @@ Iterate until `cursor` is absent rather than comparing `items.length` to `limit`
Items you own appear at their real path. An item you shared as a delegate (from someone else's folder you hold `manage` on) appears at the same masked path you reach it by.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.listShared()`](/FS/listShared/) - List what others shared with you
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach one item you manage
## Examples
### See everything you have shared
<strong class="example-title">See everything you have shared</strong>
```html
<html>
@@ -75,7 +65,7 @@ Items you own appear at their real path. An item you shared as a delegate (from
</html>
```
### Page through every share you made
<strong class="example-title">Page through every share you made</strong>
```js
let cursor;
@@ -87,7 +77,7 @@ do {
} while (cursor);
```
### Withdraw everything shared on one item
<strong class="example-title">Withdraw everything shared on one item</strong>
```js
const page = await puter.fs.listSharedByMe();
@@ -96,3 +86,9 @@ if (target && !target.pending) {
await puter.fs.unshare(target.path, target.holder);
}
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.listShared()`](/FS/listShared/) - List what others shared with you
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach one item you manage
+7 -9
View File
@@ -25,12 +25,10 @@ If path is not absolute, it will be resolved relative to the app's root director
The options for the `mkdir` operation. The following options are supported:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The directory path to be created if not specified via function parameter. |
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `overwrite` | `Boolean` | Whether to overwrite the directory if it already exists. Defaults to `false`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the directory name if it already exists. Defaults to `false`. |
- `path` (String) The directory path to be created if not specified via function parameter.
- `overwrite` (Boolean) - Whether to overwrite the directory if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the directory name if it already exists. Defaults to `false`.
- `createMissingParents` (Boolean) - Whether to create missing parent directories. Defaults to `false`.
## Return value
@@ -38,7 +36,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
## Examples
### Create a new directory
<strong class="example-title">Create a new directory</strong>
```html;fs-mkdir
<html>
@@ -57,7 +55,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
### Create a directory with duplicate name handling
<strong class="example-title">Create a directory with duplicate name handling</strong>
```html;fs-mkdir-dedupe
<html>
@@ -77,7 +75,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
### Create a new directory with missing parent directories
<strong class="example-title">Create a new directory with missing parent directories</strong>
```html;fs-mkdir-create-missing-parents
<html>
+9 -15
View File
@@ -32,26 +32,20 @@ Without `newName`, the destination is looked up first to tell the two cases apar
The options for the `move` operation. The following options are supported:
| Option | Type | Description |
|--------|------|-------------|
| `source` | `String` | Path to the file or directory to move. Required when passing options as the only argument. |
| `destination` | `String` | Path to the destination. Required when passing options as the only argument. |
| `overwrite` | `Boolean` | Whether to overwrite the destination file or directory if it already exists. Defaults to `false`. |
| `newName` | `String` | The name to give the moved file or directory. When set, `destination` is always treated as the directory to move into. Defaults to the source's own name. |
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file or directory name if it already exists. Defaults to `false`. |
- `source` (String) - Path to the file or directory to move. Required when passing options as the only argument.
- `destination` (String) - Path to the destination. Required when passing options as the only argument.
- `overwrite` (Boolean) - Whether to overwrite the destination file or directory if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the file or directory name if it already exists. Defaults to `false`.
- `newName` (String) - The name to give the moved file or directory. When set, `destination` is always treated as the directory to move into. Defaults to the source's own name.
- `createMissingParents` (Boolean) - Whether to create missing parent directories. Defaults to `false`.
## Return value
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the moved file or directory.
## Errors
If the source file or directory does not exist, the promise will be rejected with an error.
A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the moved file or directory. If the source file or directory does not exist, the promise will be rejected with an error.
## Examples
### Move a file
<strong class="example-title">Move a file</strong>
```html;fs-move
<html>
@@ -82,7 +76,7 @@ If the source file or directory does not exist, the promise will be rejected wit
</html>
```
### Move a file and create missing parent directories
<strong class="example-title">Move a file and create missing parent directories</strong>
```html;fs-move-create-missing-parents
<html>
+6 -6
View File
@@ -25,11 +25,11 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Path to the file to read. Required when passing options as the only argument. |
| `offset` | `Number` | The offset to start reading from. |
| `byte_count` | `Number` | The number of bytes to read from the offset. When omitted with `offset`, reads through the end of the file. |
- `path` (String) - Path to the file to read. Required when passing options as the only argument.
- `offset` (Number) (optional)
The offset to start reading from.
- `byte_count` (Number) (optional)
The number of bytes to read from the offset. When omitted with `offset`, reads through the end of the file.
## Return value
@@ -37,7 +37,7 @@ A `Promise` that will resolve to a `Blob` object containing the contents of the
## Examples
### Read a file
<strong class="example-title">Read a file</strong>
```html;fs-read
<html>
+13 -17
View File
@@ -4,9 +4,7 @@ description: List files and directories in the user's own Puter file system.
platforms: [websites, apps, nodejs, workers]
---
Reads the contents of a directory, returning an array of items (files and directories) within it.
This method is useful for listing all items in a specified directory in the Puter cloud storage.
Reads the contents of a directory, returning an array of items (files and directories) within it. This method is useful for listing all items in a specified directory in the Puter cloud storage.
## Syntax
@@ -27,19 +25,17 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The path to the directory to read. Required when passing options as the only argument. |
| `recursive` | `Boolean` | If `true`, the contents of subdirectories are listed too. Defaults to `false`. |
| `depth` | `Number` | How many levels to descend when `recursive` is `true`. Defaults to `10`, which is also the maximum. |
| `sortBy` | `String` | Sort field. One of `name`, `modified`, `type`, or `size`. Default is `name`. With `recursive`, sorting by `name` orders by full path, so each directory's contents stay together. The other fields sort across the whole subtree. |
| `sortOrder` | `String` | Either `asc` or `desc`. Default is `asc`. |
| `limit` | `Number` | Maximum number of entries to return. |
| `cursor` | `String \| null` | Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one. The cursor pins the sort, so later pages must not request a different `sortBy` or `sortOrder`. |
| `offset` | `Number` | Skips the given number of entries. Prefer `cursor` for paging through large directories. On a `recursive` listing, `offset` is ignored when a `cursor` is passed. Start with `offset`, then follow the returned `cursor`. |
| `includeTotal` | `Boolean` | If `true`, the paginated result includes a `total` count of all entries in the directory. |
| `stream` | `Boolean` | If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`. |
| `uid` | `String` | The UID of the directory to read. |
- `path` (String) - The path to the directory to read. Required when passing options as the only argument.
- `uid` (String) (optional) - The UID of the directory to read.
- `limit` (Number) (optional) - Maximum number of entries to return.
- `offset` (Number) (optional) - Skips the given number of entries. Prefer `cursor` for paging through large directories. On a `recursive` listing, `offset` is ignored when a `cursor` is passed; start with `offset`, then follow the returned `cursor`.
- `sortBy` (String) (optional) - Sort field: `name`, `modified`, `type`, or `size`. Default is `name`. With `recursive`, sorting by `name` orders by full path, so each directory's contents stay together; the other fields sort across the whole subtree.
- `sortOrder` (String) (optional) - `asc` or `desc`. Default is `asc`.
- `recursive` (Boolean) (optional) - If `true`, the contents of subdirectories are listed too. Defaults to `false`.
- `depth` (Number) (optional) - How many levels to descend when `recursive` is `true`. Defaults to `10`, which is also the maximum.
- `cursor` (String | null) (optional) - Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one. The cursor pins the sort, so later pages must not request a different `sortBy`/`sortOrder`.
- `includeTotal` (Boolean) (optional) - If `true`, the paginated result includes a `total` count of all entries in the directory.
- `stream` (Boolean) (optional) - If `true`, the method returns an async iterator of page objects instead of a promise, for use with `for await ... of`. Combine with `limit` to control the page size, or `cursor` to resume from a previous page. Cannot be combined with `offset`. With `includeTotal`, only the first page carries `total`.
## Return value
@@ -67,7 +63,7 @@ for await (const page of puter.fs.readdir({ path: './large-dir', stream: true })
## Examples
### Read a directory
<strong class="example-title">Read a directory</strong>
```html;fs-readdir
<html>
+5 -9
View File
@@ -4,9 +4,7 @@ description: Rename files or directories in the user's own Puter file system.
platforms: [websites, apps, nodejs, workers]
---
Renames a file or directory to a new name.
This method allows you to change the name of a file or directory in the Puter cloud storage.
Renames a file or directory to a new name. This method allows you to change the name of a file or directory in the Puter cloud storage.
## Syntax
@@ -30,11 +28,9 @@ The new name of the file or directory.
The options for the `rename` operation. The following options are supported:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Path to the file or directory to rename. Required when passing options as the only argument. |
| `newName` | `String` | The new name for the file or directory. Required when passing options as the only argument. |
| `uid` | `String` | The UID of the file or directory to rename. Can be used instead of `path`. |
- `path` (String) - Path to the file or directory to rename. Required when passing options as the only argument.
- `uid` (String) - The UID of the file or directory to rename. Can be used instead of `path`.
- `newName` (String) - The new name for the file or directory. Required when passing options as the only argument.
## Return value
@@ -42,7 +38,7 @@ Returns a promise that resolves to the [`FSItem`](/Objects/fsitem) object of the
## Examples
### Rename a file
<strong class="example-title">Rename a file</strong>
```html;fs-rename
<html>
+3 -5
View File
@@ -4,9 +4,7 @@ description: Revoke a URL created by getReadURL(), so it stops serving the file.
platforms: [websites, apps, nodejs, workers]
---
Revokes a URL created by [`getReadURL()`](/FS/getReadURL/), so it immediately stops serving the file.
An app can revoke only URLs it created. The account itself, through its own session or API token, can revoke any of its read URLs. Revoking a URL that is already revoked or has expired resolves without error.
Revokes a URL created by [`getReadURL()`](/FS/getReadURL/), so it immediately stops serving the file. An app can revoke only URLs it created; the account itself, through its own session or API token, can revoke any of its read URLs. Revoking a URL that is already revoked or has expired resolves without error.
## Syntax
@@ -39,9 +37,9 @@ A rejection carries an `Error` with a stable `code`:
| `not_found` | The URL was created by a different app, or belongs to another account. |
| `too_many_requests` | The rate limit was exceeded. See [Rate Limits & Quotas](/rate-limits-and-quotas/). |
## Examples
## Example
### Revoke a read URL
<strong class="example-title">Revoke a read URL</strong>
```html
<html>
+47 -49
View File
@@ -54,13 +54,11 @@ How much access to grant. Defaults to `'read'`.
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Item to share. Required when passing options as the only argument. |
| `recipient` | `String \| Object \| Array` | Who to share with. |
| `mode` | `String` | Access to grant. Defaults to `'read'`. |
| `paths` | `Array` | Several items to share in one call. |
| `uid` | `String` | Item to share, by UID. Can be used instead of `path`. |
- `path` (String) - Item to share. Required when passing options as the only argument.
- `uid` (String) - Item to share, by UID. Can be used instead of `path`.
- `paths` (Array) - Several items to share in one call.
- `recipient` (String | Object | Array) - Who to share with.
- `mode` (String) - Access to grant. Defaults to `'read'`.
## Return value
@@ -146,6 +144,48 @@ if ( share.pending ) {
}
```
## Examples
<strong class="example-title">Share a file with another user</strong>
```html;fs-share
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
(async () => {
// (1) create a file
await puter.fs.write('report.txt', 'Quarterly numbers');
// (2) share it, read-only
const shares = await puter.fs.share('report.txt', 'friend@example.com');
puter.print(`Shared with ${shares[0].holder} as ${shares[0].mode}<br>`);
})()
</script>
</body>
</html>
```
<strong class="example-title">Let someone edit, and let someone else re-share</strong>
```js
// An editor can change the file but cannot pass it on.
await puter.fs.share('report.txt', 'editor@example.com', 'write');
// A manager can edit it AND share it with other people.
await puter.fs.share('report.txt', 'manager@example.com', 'manage');
```
<strong class="example-title">Share one item with several people</strong>
```js
await puter.fs.share({
path: 'report.txt',
recipient: ['a@example.com', 'b@example.com'],
mode: 'read',
});
```
## Live updates
Changes inside a shared item are not pushed to recipients in real time —
@@ -196,45 +236,3 @@ Trash does not bring them back; share it again.
- [`puter.fs.unshare()`](/FS/unshare/) - Withdraw access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item
- [`puter.fs.listShared()`](/FS/listShared/) - See what others have shared with you
## Examples
### Share a file with another user
```html;fs-share
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
(async () => {
// (1) create a file
await puter.fs.write('report.txt', 'Quarterly numbers');
// (2) share it, read-only
const shares = await puter.fs.share('report.txt', 'friend@example.com');
puter.print(`Shared with ${shares[0].holder} as ${shares[0].mode}<br>`);
})()
</script>
</body>
</html>
```
### Let someone edit, and let someone else re-share
```js
// An editor can change the file but cannot pass it on.
await puter.fs.share('report.txt', 'editor@example.com', 'write');
// A manager can edit it AND share it with other people.
await puter.fs.share('report.txt', 'manager@example.com', 'manage');
```
### Share one item with several people
```js
await puter.fs.share({
path: 'report.txt',
recipient: ['a@example.com', 'b@example.com'],
mode: 'read',
});
```
+1 -1
View File
@@ -25,7 +25,7 @@ A `Promise` that resolves to a [`SpaceInfo`](/Objects/spaceinfo/) object with th
## Examples
### Show how much storage the user has used
<strong class="example-title">Show how much storage the user has used</strong>
```html
<html>
+15 -17
View File
@@ -24,16 +24,14 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | Path to the file or directory. Required when passing options as the only argument. |
| `returnSize` | `Boolean` | Whether to return size information. Defaults to `false`. |
| `returnShares` | `Boolean` | Whether to include who the item is shared with, as a `shares` array on the result. Defaults to `false`. |
| `returnSubdomains` | `Boolean` | Whether to return subdomain information. Defaults to `false`. |
| `returnWorkers` | `Boolean` | Whether to return the workers attached to the item. Workers are served alongside subdomains, so this is an alias of `returnSubdomains`. Setting either one returns both. Defaults to `false`. |
| `returnPermissions` | `Boolean` | Whether to return permission information. Defaults to `false`. |
| `returnVersions` | `Boolean` | Whether to return version information. Defaults to `false`. |
| `uid` | `String` | The UID of the file or directory. Can be used instead of `path`. |
- `path` (String) - Path to the file or directory. Required when passing options as the only argument.
- `uid` (String) - The UID of the file or directory. Can be used instead of `path`.
- `returnSubdomains` (Boolean) - Whether to return subdomain information. Defaults to `false`.
- `returnWorkers` (Boolean) - Whether to return the workers attached to the item. Workers are served alongside subdomains, so this is an alias of `returnSubdomains` — setting either one returns both. Defaults to `false`.
- `returnPermissions` (Boolean) - Whether to return permission information. Defaults to `false`.
- `returnVersions` (Boolean) - Whether to return version information. Defaults to `false`.
- `returnSize` (Boolean) - Whether to return size information. Defaults to `false`.
- `returnShares` (Boolean) - Whether to include who the item is shared with, as a `shares` array on the result. Defaults to `false`.
## Return value
@@ -43,14 +41,9 @@ The item carries `is_shared`: `true` when it has been shared with someone, `fals
With `returnShares: true`, the result also carries `shares` — an array of the same share objects [`getShares()`](/FS/getShares/) returns, including access inherited from a parent folder and unclaimed invitations. It is empty unless you own the item or hold `manage` on it, so asking for it never fails a `stat()` you were otherwise allowed to make. An app or API token sees only the shares it issued itself, and an invitation's `recipientEmail` is withheld from everyone but the owner and its sender — see [`getShares()`](/FS/getShares/). Because it does `getShares()`'s work, it also spends from the [share-read limit](/rate-limits-and-quotas/#sharing) on top of `stat()`'s own.
## Related
- [`puter.fs.getShares()`](/FS/getShares/) - List who can reach an item
- [`puter.fs.share()`](/FS/share/) - Grant access
## Examples
### Get information about a file
<strong class="example-title">Get information about a file</strong>
```html;fs-stat
<html>
@@ -74,7 +67,7 @@ With `returnShares: true`, the result also carries `shares` — an array of the
</html>
```
### See whether a file is shared, and with whom
<strong class="example-title">See whether a file is shared, and with whom</strong>
```html;fs-stat-shares
<html>
@@ -95,3 +88,8 @@ With `returnShares: true`, the result also carries `shares` — an array of the
</body>
</html>
```
## Related
- [`puter.fs.getShares()`](/FS/getShares/) - List who can reach an item
- [`puter.fs.share()`](/FS/share/) - Grant access
+10 -12
View File
@@ -39,11 +39,9 @@ Pass **yourself** to leave a share someone else gave you. Pass `{ team: uid }` t
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The item. Required when passing options as the only argument. |
| `recipient` | `String \| Object` | Whose access to withdraw. |
| `uid` | `String` | The item, by UID. Can be used instead of `path`. |
- `path` (String) - The item. Required when passing options as the only argument.
- `uid` (String) - The item, by UID. Can be used instead of `path`.
- `recipient` (String | Object) - Whose access to withdraw.
## Return value
@@ -70,14 +68,9 @@ Withdrawing someone's access also withdraws whatever **they** re-shared of that
Passing an email address that was **invited** but has not yet joined cancels the invitation. Nothing was granted, so nothing is revoked from anyone — the pending share simply stops waiting.
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item
## Examples
### Stop sharing a file
<strong class="example-title">Stop sharing a file</strong>
```html;fs-unshare
<html>
@@ -96,9 +89,14 @@ Passing an email address that was **invited** but has not yet joined cancels the
</html>
```
### Leave a share someone gave you
<strong class="example-title">Leave a share someone gave you</strong>
```js
const me = await puter.auth.getUser();
await puter.fs.unshare('/alice/report.txt', me.username);
```
## Related
- [`puter.fs.share()`](/FS/share/) - Grant access
- [`puter.fs.getShares()`](/FS/getShares/) - See who can reach an item
+13 -16
View File
@@ -28,20 +28,19 @@ The path of the directory to upload the items to. If not set, the items will be
A set of key/value pairs that configure the upload process. The following options are supported:
| Option | Type | Description |
|--------|------|-------------|
| `overwrite` | `Boolean` | Whether to overwrite the destination file if it already exists. Defaults to `false`. |
| `progress` | `Function` | Called with `(operationId, progress)` as bytes are sent, where `progress` is a percentage between `0` and `100`. |
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file name if it already exists. Defaults to `true`. Ignored when `overwrite` is `true`. |
| `generateThumbnails` | `Boolean` | Generate image thumbnails in the browser before uploading. Defaults to `false`. Unsupported files and generation failures are skipped. |
| `thumbnail` | `String` | Optional thumbnail data URL or URL to use when a file has no generated thumbnail. Data URLs exceeding 2 MiB are discarded. |
| `thumbnailGenerator` | `Function` | Optional `(file, context) => string \| undefined` callback (which may also return a promise), called once per file instead of the built-in image generator. Return a thumbnail data URL or URL, or `undefined` to skip. Exceptions are ignored. Call `context.defaultGenerator(file)` to use the built-in image generator. The `context.signal` property is an `AbortSignal` for upload preparation cancellation. Existing one-argument callbacks continue to work. A custom generator enables thumbnail preparation even when `generateThumbnails` is omitted. |
| `init` | `Function` | Called with `(operationId, xhr)` once the request has been created, before it is sent. The `XMLHttpRequest` is passed so you can abort the upload yourself. |
| `start` | `Function` | Called with no arguments when the upload starts sending. |
| `abort` | `Function` | Called with `(operationId)` if the upload is aborted. |
- `overwrite` (Boolean) - Whether to overwrite the destination file if it already exists. Defaults to `false`.
- `dedupeName` (Boolean) - Whether to deduplicate the file name if it already exists. Defaults to `true`. Ignored when `overwrite` is `true`.
- `createMissingParents` (Boolean) - Whether to create missing parent directories. Defaults to `false`.
- `generateThumbnails` (Boolean) - Generate image thumbnails in the browser before uploading. Defaults to `false`. Unsupported files and generation failures are skipped.
- `thumbnailGenerator` (Function) - Optional `(file, context) => string | undefined` callback (which may also return a promise), called once per file instead of the built-in image generator. Return a thumbnail data URL or URL, or `undefined` to skip. Exceptions are ignored. `context.defaultGenerator(file)` delegates to the built-in image generator; `context.signal` is an `AbortSignal` for upload preparation cancellation. Existing one-argument callbacks continue to work. A custom generator enables thumbnail preparation even when `generateThumbnails` is omitted.
- `thumbnail` (String) - Optional thumbnail data URL or URL to use when a file has no generated thumbnail. Data URLs exceeding 2 MiB are discarded.
The `init`, `start`, `progress`, and `abort` callbacks report on the upload as it runs. Their `operationId` argument identifies the upload, so a page running several uploads at once can tell them apart.
The following callbacks report on the upload as it runs. `operationId` identifies the upload, so a page running several uploads at once can tell them apart:
- `init` (Function) - Called with `(operationId, xhr)` once the request has been created, before it is sent. The `XMLHttpRequest` is passed so you can abort the upload yourself.
- `start` (Function) - Called with no arguments when the upload starts sending.
- `progress` (Function) - Called with `(operationId, progress)` as bytes are sent, where `progress` is a percentage between `0` and `100`.
- `abort` (Function) - Called with `(operationId)` if the upload is aborted.
Cancelling through the `init` request handle during thumbnail preparation rejects with `{ code: 'upload_aborted', message: 'Upload aborted.' }` and prevents the upload from starting. Custom generators should stop their work when `context.signal` aborts and impose their own time and resource budgets; the SDK awaits thumbnail preparation before sending files.
@@ -60,8 +59,6 @@ Returns a `Promise` that resolves to:
- A single [`FSItem`](/Objects/fsitem/) object if `items` parameter contains one item
- An array of [`FSItem`](/Objects/fsitem/) objects if `items` parameter contains multiple items
## Errors
If any part of the upload fails, the promise is rejected — it never resolves to a mix of items and errors. The rejection value always carries a `message`, and a `failedItems` array when individual items failed rather than the request as a whole. Each entry in `failedItems` carries the `path`, `message`, and — when the server gave one — the `code` and `status` for that item. A partially failed upload is not rolled back: the items that were written stay written.
When every failed item failed the same way, that `code` and `status` are also set on the rejection value itself, because the cause belongs to the request rather than to any one file. An upload that exceeds the account's storage quota is the common case: it rejects with `code: 'storage_limit_reached'` and `status: 413` however many files were in it.
@@ -88,7 +85,7 @@ When using signed uploads, a separate thumbnail transfer that fails or exceeds f
## Examples
### Upload a file from a file input
<strong class="example-title">Upload a file from a file input</strong>
```html;fs-upload
<html>
+8 -12
View File
@@ -4,9 +4,7 @@ description: Write data to files in the user's own Puter file system.
platforms: [websites, apps, nodejs, workers]
---
Writes data to a specified file path.
This method is useful for creating new files or modifying existing ones in the Puter cloud storage.
Writes data to a specified file path. This method is useful for creating new files or modifying existing ones in the Puter cloud storage.
## Syntax
@@ -32,11 +30,9 @@ The data to write to the file. If omitted, an empty file is created.
The options for the `write` operation. The following options are supported:
| Option | Type | Description |
|--------|------|-------------|
| `createMissingParents` | `Boolean` | Whether to create missing parent directories. Defaults to `false`. |
| `overwrite` | `Boolean` | Whether to overwrite the file if it already exists. Defaults to `true`. |
| `dedupeName` | `Boolean` | Whether to deduplicate the file name if it already exists. Defaults to `false`. |
- `overwrite` (boolean) - Whether to overwrite the file if it already exists. Defaults to `true`.
- `dedupeName` (boolean) - Whether to deduplicate the file name if it already exists. Defaults to `false`.
- `createMissingParents` (boolean) - Whether to create missing parent directories. Defaults to `false`.
#### `file` (File)
@@ -48,7 +44,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
## Examples
### Create a new file containing "Hello, world!"
<strong class="example-title">Create a new file containing "Hello, world!"</strong>
```html;fs-write
<html>
@@ -64,7 +60,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
### Create a new file with input coming from a file input
<strong class="example-title">Create a new file with input coming from a file input</strong>
```html;fs-write-from-input
<html>
@@ -85,7 +81,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
### Create a file with duplicate name handling
<strong class="example-title">Create a file with duplicate name handling</strong>
```html;fs-write-dedupe
<html>
@@ -105,7 +101,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
### Create a new file with missing parent directories
<strong class="example-title">Create a new file with missing parent directories</strong>
```html;fs-write-create-missing-parents
<html>
+2 -2
View File
@@ -188,9 +188,9 @@ These hosting features are supported out of the box when using Puter.js:
- **[`puter.hosting.create()`](/Hosting/create/)** - Create a new hosting deployment
- **[`puter.hosting.list()`](/Hosting/list/)** - List all hosting deployments
- **[`puter.hosting.get()`](/Hosting/get/)** - Get information about a specific deployment
- **[`puter.hosting.update()`](/Hosting/update/)** - Update hosting settings
- **[`puter.hosting.delete()`](/Hosting/delete/)** - Delete a hosting deployment
- **[`puter.hosting.update()`](/Hosting/update/)** - Update hosting settings
- **[`puter.hosting.get()`](/Hosting/get/)** - Get information about a specific deployment
- **[`puter.hosting.attach()`](/Hosting/attach/)** - Let the user connect their own domain to a website
## Examples
+2 -6
View File
@@ -4,9 +4,7 @@ description: Let the user connect one of their own domains to a website hosted o
platforms: [websites, apps]
---
Opens a Puter dialog where the user connects a domain they own, such as `www.example.com`, to one of their websites.
In the dialog, the user can pick a domain already on their account or add a new one. A domain the user picks that currently serves another of their websites moves to this one.
Opens a Puter dialog where the user connects a domain they own, such as `www.example.com`, to one of their websites. In the dialog, the user can pick a domain already on their account or add a new one. A domain the user picks that currently serves another of their websites moves to this one.
When the user adds a new domain, the dialog shows the DNS records to set at their DNS provider. The domain starts serving the website once those records are in place, usually within a few minutes.
@@ -34,8 +32,6 @@ A newly added domain resolves with `status` set to `pending`. Its `records` list
On a website that is cross-origin isolated, the popup can't send its result back to your page, so the promise resolves `null` even if the user goes on to connect a domain in the popup.
## Errors
The promise rejects with an error whose `code` is one of the following:
- `invalid_argument` when `subdomain` is missing or empty.
@@ -44,7 +40,7 @@ The promise rejects with an error whose `code` is one of the following:
## Examples
### Connect a custom domain to a website
<strong class="example-title">Connect a custom domain to a website</strong>
```html;hosting-attach
<html>
+5 -13
View File
@@ -4,9 +4,7 @@ description: Create and host a website from a directory on Puter.
platforms: [websites, apps, nodejs, workers]
---
Creates a new subdomain that will be served by the hosting service.
You must specify a path to a directory that will be served by the subdomain.
Will create a new subdomain that will be served by the hosting service. You must specify a path to a directory that will be served by the subdomain.
## Syntax
@@ -31,22 +29,16 @@ The directory must be one you own. Hosting serves everything under it publicly,
Alternative way to create hosting via options.
| Option | Type | Description |
|--------|------|-------------|
| `subdomain` | `String` | Name of the subdomain you want to create. |
| `root_dir` | `String` | Required. Absolute path to the directory you want to serve. Unlike `dirPath`, this value is not resolved against the app's root directory, so it must be an absolute path. |
- `subdomain` (String) - Name of the subdomain you want to create.
- `root_dir` (String) (required) - Absolute path to the directory you want to serve. Unlike `dirPath`, this value is not resolved against the app's root directory, so it must be an absolute path.
## Return value
A `Promise` that will resolve to a [`Subdomain`](/Objects/subdomain/) object when the subdomain has been created.
## Errors
If a subdomain with the given name already exists, the promise will be rejected with an error. If the path does not exist, the promise will be rejected with an error.
A `Promise` that will resolve to a [`Subdomain`](/Objects/subdomain/) object when the subdomain has been created. If a subdomain with the given name already exists, the promise will be rejected with an error. If the path does not exist, the promise will be rejected with an error.
## Examples
### Create a simple website displaying "Hello world!"
<strong class="example-title">Create a simple website displaying "Hello world!"</strong>
```html;hosting-create
<html>
+3 -9
View File
@@ -4,9 +4,7 @@ description: Delete a subdomain from your account.
platforms: [websites, apps, nodejs, workers]
---
Deletes a subdomain from your account.
The subdomain will no longer be served by the hosting service. If the subdomain has a directory, it will be disconnected from the subdomain. The associated directory will not be deleted.
Deletes a subdomain from your account. The subdomain will no longer be served by the hosting service. If the subdomain has a directory, it will be disconnected from the subdomain. The associated directory will not be deleted.
## Syntax
@@ -22,15 +20,11 @@ A string containing the name of the subdomain you want to delete.
## Return value
A `Promise` that will resolve to an object of the form `{ success: true, uid: <subdomain-uid> }` when the subdomain has been deleted.
## Errors
If a subdomain with the given name does not exist, the promise will be rejected with an error.
A `Promise` that will resolve to an object of the form `{ success: true, uid: <subdomain-uid> }` when the subdomain has been deleted. If a subdomain with the given name does not exist, the promise will be rejected with an error.
## Examples
### Create a random website then delete it
<strong class="example-title">Create a random website then delete it</strong>
```html;hosting-delete
<html>
Loaded 100 of 382 files, more files were not shown because too many files have changed in this diff. Show more