Compare commits

...
Author SHA1 Message Date
jelveh 57ff5db49e Keep an open dialog's buttons whole on a small phone in German
At 320px, German's longer labels pushed the Open button past the screen
edge, since the upload label couldn't shrink and the buttons could. The
upload label now gives way, cut off with an ellipsis.
2026-11-07 20:09:43 -07:00
jelveh a856f91e40 Leave Safari's IME-ending Escape alone at a framed sign-in's account checks
Safari sends the Escape that ends an IME conversion with keyCode 229 and
isComposing false, so it closed the framed sign-in. The auth screens
already check for it.
2026-11-07 20:07:25 -07:00
jelveh 3addbd4dd7 Go back to the save picker on Escape at its replace prompt
Escape closed the alert without an answer, so the save waited on it
forever behind the picker's busy mask. In a frame nothing could close
the picker after that. The alert closing now counts as Cancel.
2026-11-07 20:07:10 -07:00
jelveh 474b36c577 Reopen a refused embed frame in WebKit
WebKit took the refused URL as a fragment navigation of its error page
and loaded nothing, so a frame that reloaded itself fell back to the
popup. The frame is reopened through the server's query redirect, which
keeps the fragment.
2026-11-07 19:30:16 -07:00
jelveh c4ff9f3a93 Keep a popup frame open when a frame for another popup shows
A sign-in replaced a showing picker frame, cancelling the picker, and
the other way round, though their popups have different window names and
stay open together. Only a frame for the same popup is replaced now.
2026-11-07 19:26:31 -07:00
jelveh 8624908dce Share a framed sign-in with a call that differs in request_auth
Implicit auth asks with request_auth, so an explicit signIn() made while
it was open replaced its frame and rejected every puter.* call waiting
on it. Any framed sign-in in progress is now joined.
2026-11-07 19:25:35 -07:00
jelveh 2ee97fe4a7 Say what a picker is for when its popup needs a click to open
When a framed picker falls back to the popup after the click expired,
the consent dialog said the page used Puter for AI and Cloud features,
not that it wanted a file or folder. It now names the picker, as the
push notification dialog does.
2026-11-07 19:03:29 -07:00
jelveh f2b617b0fe Keep a file dialog's buttons on one line on a small phone
On a 320px-wide screen the open picker's Open button wrapped under
Cancel and ran into the screen's edge, and Upload wrapped under its
icon. The buttons now stay on one line, with less side padding up to
480px wide so the save dialog's file name keeps room to show.
2026-11-07 19:01:57 -07:00
jelveh aaa9a5ccd1 Keep a save dialog's file name and buttons on a phone's screen
The save dialog's bottom bar couldn't shrink below the file name's own
width, so on a phone it spilled off both edges: the name's start and
the Save button were cut off. A framed save picker fills the phone, so it
always hit this. The name now shrinks to fit.
2026-11-07 18:59:52 -07:00
jelveh d86d5ade3e Document that one popup frame shows at a time 2026-11-07 18:54:08 -07:00
jelveh fa4ff365cb Close only a context menu on Escape over a file dialog
Escape to dismiss a right-click menu in a file dialog also closed the
dialog, which cancels a picker and, in a framed picker, removes the whole
frame. An open context menu now takes the Escape on its own.
2026-11-07 18:51:56 -07:00
jelveh 3c047d0a61 Share one framed sign-in between calls made while it's open
A double click on a page's sign-in button started a second framed
sign-in, which replaced the first and rejected it as closed while the
user was still signing in. A call made while a framed sign-in with the
same request_auth is open now settles with it.
2026-11-07 18:47:11 -07:00
jelveh 1859aa85a6 Replace a showing popup frame instead of stacking a second one
A double click on a page's picker button framed two GUIs, one over the
other under two scrims, and the user had to cancel twice. A popup reuses
its named window instead. Now a newer popup frame dismisses the one
showing, which settles it as closed.
2026-11-07 18:46:34 -07:00
jelveh e79061e37e Focus a framed save picker's file name as the popup does
A cross-origin frame's focus() does nothing until the page focuses it, and
the page focusing it again resets it, so the framed save picker opened with
nothing focused and typing went nowhere. A framed popup now gets its latest
focus() back whenever the frame gains focus with nothing focused, until the
user presses a key or the pointer in it.
2026-11-07 18:34:27 -07:00
jelveh 97dd7c9d40 Center a popup frame's box with margins so it fills a phone edge to edge
On a phone with a fractional pixel ratio the translate that centered the
full-screen box left it a fraction of a pixel short of the top, so a line
of scrim showed above the sign-in. Margins snap to device pixels.
2026-11-07 18:29:36 -07:00
jelveh 2761ddc99a Keep a popup frame's white backing off its rounded edge in dark mode
The box's white background shared the frame's anti-aliased corner, so a
light arc showed around the dark sign-in. The backing now stops 1px inside
the edge, which leaves the curve to the frame and the scrim.
2026-11-07 18:27:32 -07:00
jelveh daf51a749c Hand a save picker frame its file again after it reloads
The page answered a picker's sendMeFileData once and then stopped
listening. A framed save picker that reloads asks again, and without an
answer it never opened its dialog, so the page waited out the ready
timeout and fell back to the popup. A frame is now answered until it
closes; a popup is still answered once.
2026-11-07 18:09:10 -07:00
jelveh ff56af117e Fall back to the popup when a reopened embed frame never loads
After a refused self-reload the page opens the embed again, but nothing
timed that second start: a stalled request left the loading spinner up
until the user dismissed it, which settled the request as closed instead
of opening the popup. The reopened frame now gets the same ready timeout
as the first start.
2026-11-07 18:06:10 -07:00
jelveh c04e6f3604 Keep a page's own styles off a popup frame's dialog, frame and close button
The dialog, its frame and the close button live in the page's document, so
a page's global dialog, iframe and button rules reached them: a transform
that centers the page's own dialogs moved the overlay half off screen, an
iframe max-width shrank the frame inside its box, and button margins and
min sizes turned the close button into a pill. The dialog and frame now
reset those properties inline, and the close button starts from all:unset.
2026-11-07 18:01:28 -07:00
jelveh 997149fbd8 Fade in a popup frame's scrim and box
The scrim behind a framed sign-in or picker, and the box's white
background, appeared at full opacity in one frame while the GUI's content
faded in over them. Both now fade in briefly, unless the user prefers
reduced motion.
2026-11-07 17:28:23 -07:00
jelveh bacd97b7dd Leave Escape that cancels an IME conversion to the IME in sign-in
In a framed sign-in, Escape pressed to cancel an IME conversion in a
field also closed the sign-in, losing what was typed. The auth screens
and the account checks now leave an Escape mid-composition to the IME,
as the dashboard's text fields do.
2026-11-07 17:27:21 -07:00
jelveh c546b28754 Close a framed sign-in on Escape at its account checks
Escape closed the framed sign-in on its auth screens but did nothing once
signup moved on to confirming the email, phone or card, which show as
windows. Escape there now closes the frame as well, as its close button
does.
2026-11-07 17:20:40 -07:00
jelveh cd9d0bb4ac Open the popup straight away for a page framed by another site
frame-ancestors on the embeds allows only the GUI and the framing page,
so a first-party page inside another site's frame waited about a second
on a refused frame before sign-in or a picker opened the popup, by which
time Safari asks for another click. Such a page opens the popup straight
away now, as it did before the frame.
2026-11-07 17:17:30 -07:00
jelveh 4df7522835 Open a provider picked in a framed sign-in straight in the popup
Picking a provider in the framed sign-in fell back to the sign-in popup,
where the user had to pick the provider again. The frame now hands the
page the provider's start URL for its sign-in, and the page opens the
popup there after checking it is the GUI's OIDC start for that sign-in.
2026-11-07 17:01:24 -07:00
jelveh 545d9b08c3 Prefill a web save picker with the suggested name
The popup and framed save pickers ignored suggestedName and opened with
an empty filename, unlike the save picker an app gets in the desktop.
2026-11-07 16:50:06 -07:00
jelveh 64a2b774ce Frame a GUI popup only at its exact path
Routes match case-insensitively and with a trailing slash, so another
spelling of /embed/<action> was served frameable while the shell booted
the desktop for it. Any other spelling now redirects to the exact path.
2026-11-07 16:49:07 -07:00
jelveh 0061b9e855 Keep scrolling over an embed's scrim from scrolling the page
A wheel or swipe over the scrim around a framed embed chained to the
page behind the modal. The dialog now contains its overscroll.
2026-11-07 16:24:31 -07:00
jelveh a7110610b8 Close a popup frame on Escape from the page too
Once a popup frame was ready, Escape with focus on the page (after a
click on the scrim) only moved focus back into the frame, so it took a
second Escape to close, and none if the frame stopped responding. It
now closes the frame, as Escape inside it does. The feedback embed
still leaves dismissal to the embed.
2026-11-07 16:22:34 -07:00
jelveh 7b640c4cec Let a popup frame fill in texted codes
Signup and the account checks fill a texted code in through WebOTP,
which a cross-origin frame may only use when allowed. Popup frames now
allow otp-credentials, so the code fills in as it does in the popup.
2026-11-07 16:21:46 -07:00
jelveh d2416d326f Expose an embed's loading status only while it shows
The spinner is faded out rather than removed, so assistive tech still
read a Loading status over a frame that was ready. The status is
hidden from it whenever the spinner isn't showing.
2026-11-07 16:21:20 -07:00
jelveh dbc7e8f3cd Name the embed dialog for assistive tech
The modal dialog around a framed embed had no accessible name, so
screen readers announced an unnamed dialog. It is labelled with the
frame's title.
2026-11-07 16:20:52 -07:00
jelveh 95c2cfa520 Remove the picker's consent dialog once answered
The consent dialog a picker shows when its click has expired was
closed but left in the page after Continue or Cancel, one element per
fallback. It is removed now, as the other consent dialogs are.
2026-11-07 16:20:25 -07:00
jelveh 713adff7e2 Correct why a temporary-account sign-in keeps the popup
notes.puter.com and puter.com are the same site, so browsers don't
partition the frame's storage. The popup is kept because only it
creates a temporary account.
2026-11-07 16:19:45 -07:00
jelveh 35510839d4 Reopen a framed embed that reloads itself into a refused frame
A reload or navigation the embed starts itself names the embed as its
referrer, so the server refuses the framing: logging out at an account
gate, a sign-out in another tab, or a reset session left a blank box.
The page now shows its spinner and opens the embed again itself, once
per ready, and falls back as for a refused frame if that fails too.
2026-11-07 16:19:40 -07:00
jelveh 1da2d6d8b5 Take a save picker's file only from the page that asked
The save picker opened a dialog for every showSaveFilePickerPopup
message from any window. In a frame, a sibling frame of the framing
page can reach it, so it could supply the bytes the user then saved,
or stack extra dialogs. The picker now takes the file once, and only
from its opener.
2026-11-07 16:15:19 -07:00
jelveh 178bff56e3 Keep a framed picker on the framing page's user
With several saved accounts, a framed picker could still show the
account picker (no grant yet, or request_auth in its fragment). Picking
another account switched the session inside the frame, and the picker
then ran with the first user's details and the second user's token,
saving that token under the first account. A framed picker already
holds the framing page's user, so it no longer offers to switch, and
its user check no longer writes the boot's shared whoami.
2026-11-07 16:14:00 -07:00
jelveh 5d6975dd6c Skip the frame on subdomains the server refuses to let frame
The SDK framed embeds from any page one label under the GUI origin, but
the server refuses its own subdomains (api, docs, apps, ...). On those,
sign-in and the pickers waited on a refused frame before opening the
popup, which Safari could then block for want of a recent click. They
open the popup straight away now, and the user menu hides Apps there,
as its docs say.
2026-11-07 16:11:59 -07:00
jelveh 1a58d35e43 Focus a framed sign-in once the page focuses the frame
A cross-origin frame's focus() calls do nothing until the framing page
focuses it, so the sign-in opened with focus on the body: keys missed
the form and Escape never reached the dialog. The screen now takes
focus when the frame gains it, unless something already has it.
2026-11-07 16:10:45 -07:00
jelveh 8954baf004 Close a framed sign-in on Escape
The sign-in shows as a page in the frame, which ignored Escape. Escape
now asks the framing page to close it, as its close button does, unless
a request is in flight.
2026-11-07 16:10:41 -07:00
jelveh 012454ad0d Close a framed picker when Escape cancels it
Escape closes only the picker window inside the frame, so the frame now
closes with it. The mismatched-user e2e test waits for sign-in's whoami
before naming another user, which it could otherwise overwrite.
2026-11-07 16:00:17 -07:00
jelveh d4736ffae1 Show sign-in and file pickers in a frame on first-party pages
puter.auth.signIn(), showOpenFilePicker(), showSaveFilePicker() and
showDirectoryPicker() on a page one label under the Puter origin now
show the GUI popup in a frame over the page instead of a window. Every
other page, and any frame that can't serve the request, keeps the popup
exactly as before, so apps need no changes.

/embed/sign-in and /embed/show-{open-file,save-file,directory}-picker
render the normal GUI shell with the framing rules, query redirect and
no-store of /embed/apps, and name the framing page (read from the
referrer, pinned with frame-ancestors) as embed_host_origin. The GUI
runs the popup boot unchanged with that page as window.opener; close()
asks it to remove the frame. Popup parameters come from the fragment
(msg_id, options, request_auth, and user for a picker).

Sign-in has a close button that rejects with auth_window_closed, as
closing the popup does. A federated provider can't be framed, so
choosing one continues in the popup. attempt_temp_user_creation and
cross-origin isolated pages keep the popup.

Pickers frame only for a signed-in page whose user owns the GUI
session; otherwise the GUI reports unavailable and the page opens the
popup, through a consent dialog if the click has expired. The page
keeps its own token rather than adopting the one sent with the answer.

The feedback embed and the new frames share one loading/ready state
machine in guiEmbed.js.
2026-11-07 12:40:24 -07:00
Nariman Jelveh 8c14e7de30 Add account links and Send feedback to <puter-user-menu> (#4536)
The signed-in menu now shows the user's picture, username and email
(hidden when whoami leaves the email out), links to Manage account,
Usage and Open Puter on the GUI origin in a new tab, and Send feedback,
which calls puter.ui.showFeedbackDialog(). Each new item takes a label
attribute like the existing ones. The menu opens on its first item, and
the arrow, Home and End keys move between items.
2026-11-07 11:40:42 -07:00
Filip Kujundžić 84faf5c40c refactor(ai): rename convo API to realtime (#4524) 2026-11-07 10:55:35 -07:00
Rasad Regmi aba2666f26 fix(gui): improve dark mode input visibility (#4450) 2026-11-07 09:32:33 -07:00
tgarver-gdm abe6882de9 Import AGENTS.md from CLAUDE.md so Claude Code loads it (#4529) 2026-11-07 09:21:28 -07:00
jelveh 770af49528 Show a loading scrim while the feedback embed checks the session
The framed feedback dialog stayed hidden until the embed had checked the
GUI session, so on a slow network a click on Send feedback showed
nothing for seconds, and a second click silently resolved false. A
check that takes longer than 200ms now shows a scrim with a spinner over
the page, matching the embed's own scrim, which takes its place once
the dialog is ready. Escape or a click on it cancels, and a refused
session still falls back to the popup.
2026-11-07 02:12:59 -07:00
jelveh 47b4cc1158 Follow the OS theme in the feedback embed on Safari
WebKit gives a frame the color-scheme of its iframe element as its
preferred scheme, and the feedback embed's frame was set to normal, so
Safari in dark mode showed the light dialog. The frame and the embed's
root now both declare light dark: the embed follows the OS in every
engine, and the frame stays transparent because the two match.
2026-11-07 02:12:06 -07:00
Nariman Jelveh e253a7f862 Show the app feedback dialog in a frame on first-party pages (#4534)
* Show the app feedback dialog in a frame on first-party pages

puter.ui.showFeedbackDialog() on a page one label under the Puter origin
now frames /embed/feedback in a modal over the page, instead of opening a
puter.com popup. The embed uses the same framing rules, query redirect,
and host-user binding as /embed/apps, and sends the feedback for the
framing page's origin, which the server reads from the referrer and pins
with frame-ancestors. Without the named user's Puter session, or with an
email still to confirm, the embed reports itself unavailable and the SDK
falls back to the popup, which can sign in. A frame that never answers
(such as one the host's CSP blocks) falls back too.

The embed session check moves out of appsEmbed.js into a shared helper,
and the first-party page check out of <puter-user-menu> into puter.js's
lib, so both embeds use one copy of each.

* Keep the framing page from scrolling behind the feedback embed

A wheel or touch scroll over the feedback embed's scrim chained out of
the frame and scrolled the first-party page underneath the open dialog.
The embed's root now stops overscroll from leaving the frame.

* Name the feedback embed's user from the cached whoami

showFeedbackDialog() on a first-party page fetched /whoami before it
started loading the embed, adding a round trip to every call. It now
uses the user puter.js already cached for the session and asks the API
only when there is none.
2026-11-07 01:57:47 -07:00
Nariman Jelveh af35783df4 Test native app hosts with apps still served natively (#4535)
editor, markus and pdf moved to standard host routing, but the host
redirect and embed framing tests still used editor as their native app,
so they failed. They now use about, and a test checks that editor,
markus and pdf are passed through even with a folder under the native
apps root.
2026-11-07 01:39:45 -07:00
Nariman Jelveh cb214f28cc Open Contact Us as a dashboard dialog in the dashboard (#4533)
The dashboard's Contact Us now uses the dashboard form dialog instead of a
UIWindow: a centered card on desktop and a bottom sheet on phones. Files can
be picked, dropped anywhere over the dialog, or pasted into the message, and
images show a preview. Cmd/Ctrl+Enter sends. The desktop keeps
UIWindowFeedback.
2026-11-07 00:40:45 -07:00
Nariman Jelveh 8ed439e897 Stop the signup screen redrawing when it opens (#4532)
The signup screen showed its email form, then looked up the identity
providers and folded the form away behind "Sign up with email" once they
arrived, a round trip later. Every screen made its own lookup, so moving
from login to signup redrew the card each time.

The provider lookup now happens once per auth flow, so moving between
login and signup draws the providers before the next paint. When signup
is the first screen, its email form stays hidden until the lookup
answers, or for 1.5 seconds if it is slow, and shows when no providers
are offered or the form was opened prefilled.
2026-11-06 23:58:44 -07:00
jelveh 672a704193 Shorten popup Puter branding message
Updates the English translation for `popup_opener_uses_puter` to a shorter single-line message. This removes the extra explanatory text about AI/cloud features and using a Puter account, likely for a cleaner popup prompt.
2026-11-06 23:41:00 -07:00
jelveh 35ae464d86 Tighten signup terms typography
Reduce the signup terms text in the auth dialog to match the tighter dashboard layout. This is a small styling adjustment for the dialog copy to keep it balanced and readable.
2026-11-06 23:37:37 -07:00
jelveh 79f24ed3df Hide the opener notice on the popup login screen
Someone logging in already has a Puter account, so like the account
picker the login screen no longer explains that the site uses Puter.
The signup screen keeps it.
2026-11-06 23:31:49 -07:00
Nariman Jelveh f30d2134b1 Keep profile pictures in the saved account list (#4531)
The account picker reads pictures from the logged_in_users list in
localStorage, but update_auth_data saved that list with an empty profile
and only added the picture in memory once the profile loaded. A picture
reached storage only when a later account switch or sign-out rewrote the
list, so the active account usually showed just its initial.

update_auth_data now keeps the account's saved profile until the fresh
one loads, then saves the user and the account list again. The profile
loads after puter.js holds the new account's token, so a switch can no
longer fetch the previous account's profile, and a profile that arrives
after another account signed in is dropped.

The first-visit migration in globals.js now stores the account list as
JSON instead of "[object Object]".
2026-11-06 23:22:11 -07:00
Nariman Jelveh c24c8589cb Hide the opener notice on the popup account picker (#4530)
Someone choosing from accounts they've already signed in with doesn't need
to be told the site uses Puter. The login and signup screens keep it.
2026-11-06 23:02:18 -07:00
Nariman Jelveh 2f8f81e621 Bind the app browser embed to the host's user and add <puter-user-menu> (#4528)
* Show the app browser embed's session only to the host's signed-in user

/embed/apps now reads the host page's signed-in user from its fragment
(#user=<uuid>) and asks /whoami which user the GUI session belongs to.
It shows the user's apps only when the two match. A host that names no
user, a malformed one, or another user, and a session the API refuses,
get the signed-out view of recommended apps with no SDK and no app
tokens. A failed /whoami check shows the unavailable state. Changing the
fragment reloads the embed.

Hosts pass the uuid from puter.auth.getUser() and remove the iframe when
their own sign-in changes; the doc's example does both.

* Add <puter-user-menu> for first-party apps on Puter subdomains

puter.js registers a <puter-user-menu> element that follows the page's
own puter.js sign-in. Signed out it shows Sign in; signed in it shows the
user's profile picture, or their initial when there is none, with a menu
holding the username and Sign out. On a page one label under the Puter
origin, an Apps button opens /embed/apps in a modal with the signed-in
user named in the fragment, so the app browser shows the Puter session's
apps only to that user. Any change to the page's sign-in closes the app
browser. The element renders nothing outside a top-level page.

Its labels can be set with apps-label, sign-in-label, sign-out-label,
close-label and account-label, and it fires signin and signout events.
It is documented internally in components.md and the embed doc, and is
left out of the public docs because the app browser only works on Puter
subdomains.

* Show <puter-user-menu>'s app browser in a panel under its button

The Apps view and the account menu are now panels that hang under their
button with a caret, closing on Escape, an outside press or the button.
They use the top layer where the browser has one, so a host's transform,
overflow or z-index can't clip or cover them. On screens up to 600px wide
the Apps panel spans the width below the button.

Closing the Apps panel keeps the app browser loaded; a change to the
page's sign-in still discards it. A spinner shows until it loads, and its
colour scheme follows the component's theme, which follows the OS unless
the theme attribute is set.

A temporary account counts as signed out: it gets Sign in, no profile
picture request, and an app browser with no user named. The signin event
carries the signed-in user, and the component exposes the parts
apps-button, avatar, sign-in, menu and apps-panel for host styling.

* Read the user <puter-user-menu> signs in as after the SDK starts its whoami

setAuthToken notifies auth listeners before it starts the new token's
/whoami, so a sign-in on a loaded page showed '?' and opened the app
browser without naming the user.

* Close <puter-user-menu>'s account menu when Tab leaves it

Focus moved on to the page with the menu still open, where Escape no
longer reached it. Tab now closes the menu and moves on from its button.

* Move focus to Sign in after signing out from <puter-user-menu>

The focused menu and avatar disappear on sign-out, which dropped focus
to the page body.

* Show the app browser in the theme <puter-user-menu> forces

Chromium doesn't pass an iframe's color-scheme on to the page inside it,
so a forced theme that differed from the OS showed the app browser in
the OS's theme inside a panel in the forced one. The component now
passes a forced theme as theme= in the fragment, and the embed applies
it to its color-scheme rules.

* Show <puter-user-menu>'s account before its profile picture loads

The avatar and Apps button waited for the /profile request as well as
the user, so a slow profile kept them hidden. The picture is now added
when it arrives.

* Open one sign-in popup at a time from <puter-user-menu>

Clicking Sign in again while its popup is still open opened another popup each time. Further clicks are ignored until the sign-in finishes or its popup is closed. A cross-origin isolated page can't see its popup close, so it keeps the old behavior rather than locking the button.

* Keep <puter-user-menu>'s Apps button unshaded after a tap closes it

Touch screens keep :hover on the last tapped element, so tapping the Apps button to close the panel left it shaded as if the panel were still open. Hover shading now applies only where the device can hover; the open state still shades the button everywhere.

* Show <puter-user-menu>'s Sign in pressed and its account hovered

Sign in had no pressed state and the account button no hover state, so neither responded to the pointer. Sign in now takes the pressed look of Puter's other primary buttons, and the account button shows its open-menu ring on hover where the device can hover.

* Show a spinner in the app browser embed until its apps arrive

The embed stayed blank while it checked the session with /whoami and loaded the SDK. <puter-user-menu> hides its own spinner once the embed's page loads, so its panel went blank for that whole time. The empty embed now shows the same spinner in the same place until it renders its apps or its unavailable message.
2026-11-06 22:18:38 -07:00
Nariman Jelveh 7d02c7f622 Offer a custom domain when publishing a folder from the dashboard (#4527)
* Offer a custom domain when publishing a folder from the dashboard

The Files tab's Publish Website dialog has a "Use a custom domain" switch.
It appears only when the server has custom domains. Turned on, it asks for
the domain, with the monthly price and suggestions from the domains already
on the account. Picking one of those moves it to the new site instead of
adding it again.

Publishing creates the site, then adds the domain. The done screen shows the
live address and the domain's status with the DNS records to set, each with
a Copy button, and a Check Status button. A failure after the site is live
keeps the site: the address locks, and the button retries only the domain.
A domain held by another account shows its ownership record to verify.

On a plan without custom domains, the switch shows an upgrade prompt in
place of the field and opens the upgrade flow where the deployment has one.
Once the plan changes, the field unlocks in place.

The /custom-domains request, error wording, price format and status-check
merge move to helpers/customDomains.js, shared with the desktop's attach
dialog.

* Name the served and forwarding domains the right way round in the redirect note

The note reads "served on {first}, forwarded from {second}", but both the
publish dialog and the attach dialog passed the root domain first.

* Fit DNS record labels of any length in the publish dialog

The label column was a fixed 44px, so a longer translation ("Pangalan")
ran under the field beside it. Each record card is now one grid whose label
column grows to its longest label, keeping the name and value aligned.

* Run one domain action at a time on the publish done screen

Check Status and the switch to www each disabled only themselves, so both
could be in flight and a slow status check could redraw the root domain
over the www one it had just become.

* Keep focus on the custom domain switch when it shows the upgrade prompt

Turning the switch on moved focus to Upgrade, so a second Space meant to
turn it back off opened the upgrade flow instead. The prompt follows the
switch in tab order.

* Finish with the live site when the plan can't add its domain

Once the site was live, a 402 from adding the domain left the button
reading Add Domain, and pressing it said to turn the switch off "to publish
without one". The button now reads Done and finishes with the site; an
upgrade brings the add back.

* Keep the ownership record and the Verify step in step while typing

Any edit hid the claim's TXT record for good, but the button went back to
Verify and Add as soon as the claimed hostname was typed again, asking to
verify a record no longer on screen. Both now follow the typed hostname.

* Keep the publish done screen up through a stray backdrop click when it lists DNS records

The records to set at the DNS provider appear only on this screen; a click
outside the card while switching to the provider's tab threw them away.
Done, Escape and the close button still close it.

* Listen for plan changes only once the publish dialog has offered the upgrade

Every website publish dialog added a window listener that held its closed
dialog until the next plan change, which may never come. The dialog is
modal, so the plan can only change after its Upgrade button opened the flow;
the listener is added then.

* Keep the upgrade prompt's text beside its icon on phones

Wrapping put the text on its own line under the icon, leaving the icon
alone on the first row; now only the button wraps.

* Drop "After publishing" from the domain hint once the site is live

When adding the domain needed another try, the hint still promised DNS
records "after publishing" for a site already published; it now keeps
only the price.

* Announce publish domain checks in a status region that stays on screen

Each check redrew the domain section, status line included, so its result
landed in a brand-new live region that screen readers don't announce, while
the redrawn records sat in the done screen's status region. The summary is
now redrawn on its own, outside the announcements.
2026-11-06 20:06:30 -07:00
Nariman Jelveh d2bbe2b5e2 Ignore Explorer responses for a folder the window has left (#4526)
Each refresh of an item container now takes an id, and only the newest
refresh may write to the container or its window. Before, a slow stat for
the folder a window had left could point the window back at it, so New
folder, Paste and Upload went to the old folder while the window showed
the new one. A listing that arrived just before navigating away added its
rows to the new folder, and returning to a folder while its first listing
was in flight rendered every row twice. The stat in update_window_path
also skips its writes once the window has moved to another path.
2026-11-06 18:28:25 -07:00
Nariman Jelveh 3ff70ef97f Remove web apps from native host redirects
Allow the `editor`, `markus`, and `pdf` subdomains to use standard host routing.
2026-11-06 17:20:22 -07:00
Nariman Jelveh f791024b2e Support dark mode in the desktop context menu (#4525)
The desktop context menu (UIContextMenu) stayed white with dark text when
the OS was in dark mode, even though the dashboard around it turns dark.
It now follows prefers-color-scheme like the dashboard: a dark translucent
surface, light text, and dark variants for dividers, the open-submenu and
blurred highlights, the submenu chevron, monochrome icons, and the mobile
action sheet.
2026-11-06 16:01:08 -07:00
Nariman Jelveh cce9718b45 Stop the sign-in page jumping when the iOS keyboard opens
A sign-in page already fills the screen, so it no longer shrinks itself
to the area above an on-screen keyboard. On iOS that resize fought the
browser's own pan to the focused field and the form moved up and down
as the keyboard opened. Dialogs still fit above the keyboard.
2026-11-06 15:40:36 -07:00
Nariman Jelveh 9758ada36e Keep the wallpaper off sign-in pages and drop the OIDC-only signup notice
Signed out, /action/login, /action/signup, /action/password-recovery and
the sign-in page for returning visitors, app landings and share links no
longer load the wallpaper behind them, and the page covers the screen at
once instead of fading in over whatever was there.

The signup screen no longer explains that only providers are offered when
email signup is closed; it just shows the provider buttons.
2026-11-06 15:30:57 -07:00
Nariman Jelveh 37dcee78f0 Move login, signup, account picker, password recovery and 2FA to dashboard-style dialogs (#4522)
* Move login, signup, account picker, password recovery and 2FA to dashboard-style dialogs

The sign-in surfaces were separate UIWindows that opened over each other
(login, then a recovery window over it, then a 2FA window over that). They
are now screens of one dashboard-style card built on mountDashboardOverlay,
the same shell, fields, buttons and status line as the dashboard's account
dialogs. Screens replace each other in place, with Back, and keep what was
typed.

- Page presentation for cover pages and sign-in popups: an opaque page with
  a centered card, filling the screen on phones and in popups. Dialog
  presentation elsewhere: dimmed backdrop, centered card, bottom sheet on
  phones.
- Each call site keeps whether it could be dismissed, its promise contract,
  OIDC gating in popups, Turnstile, the honeypot, bonus codes, the
  post-signup verification gates, reauth auth_id, and redirect handling.
- Keys typed in the card no longer reach the desktop's document shortcuts.
- A second sign-in prompt joins the open flow instead of stacking a card.
- Server messages render as text; prefilled values are encoded.

* Show the signup screen's errors above the provider buttons

The status line lived inside the email form, which hides behind the
provider buttons (or for good, when only provider signups are open), so
an error the screen opened with, like a refused provider signup, was
never shown.

* Cover the page with a new account's checks when signup was a page

Signup as a page (a sign-in popup, /action/signup) closes its card for
the email, phone and card checks; they opened as floating windows over
an empty backdrop instead of covering the page as they did before.

* Give the auth card's Back and close bar a background once it scrolls

On a short screen the card's content scrolled under the bare Back and
close buttons, which then sat on top of it: the Back chevron covered the
edge of a provider button and took its taps. Once the showing screen is
scrolled, the bar turns opaque with a divider, as the footer has; at
rest nothing changes.

* Raise a failed session-cookie sync alert above the sign-in card

Signing in waits on this alert with the auth card still up. The card
sits above every ordinary window, so the alert opened underneath it and
the login spun forever. It now opens in the stay-on-top band.

* Keep focus where it is when a second sign-in prompt joins the card

A prompt that joins the open auth card focused the screen's first
field, so one arriving while the user typed their password sent the
rest of it into the username field. It now only brings focus back when
it has left the card.

* Keep focus in the auth card while its form is busy

Submitting disabled the focused field, which dropped focus to the page,
so keys pressed while the request was in flight (Delete, Enter, letters)
reached the desktop's document shortcuts.

* Keep focus in the auth card when its backdrop is pressed

A press on the dimmed backdrop (or a page's background) that didn't
dismiss the card moved focus to the page, so the next keys went to the
desktop's document shortcuts and Tab could leave the card.

* Point the Turnstile migration note at the new signup screen

UIWindowSignup no longer exists; the widget renders in UI/Auth/UIAuthSignup.js.

* Reload after sign-in when only the URL's hash would change

On a dashboard tab (/#files) the redirect after a login or signup was
the same page with a hash, so location.replace only scrolled: the new
account was signed in but the page never reloaded, and the card stayed
up, busy, until closed.

* Span the screen with the auth bottom sheet on wider phones

The card's 400px cap outranked the dashboard sheet's full width, so on
phones between 401 and 600px wide the sheet left gaps on both sides.

* Return focus to the auth form when a request fails

A busy card parks focus on itself while its fields are locked. When the
server refused a signup, focus stayed there, so Enter did nothing and the
user had to tab back in. Ending busy now hands focus back to the control
that had it, once that control is enabled again.

* Keep the current account when a login is dismissed mid-request

Closing the auth card while its login request was out still signed the
browser in to the other account and reloaded once the server answered,
though the caller had already been told the user dismissed it. A login
that answers after the card closed is now dropped.

* Make the auth card's logo a link where it leads somewhere

On a cover page the Puter logo was an image with a click handler: no
keyboard access, no name for screen readers, no middle-click. It is now a
link named Puter. Everywhere else the logo is marked decorative, since the
title beside it names the screen.

* Return to the login screen when signing in fails after a 2FA code

If storing the new session failed after a verified code, the error went
to the hidden login screen while the code screen stayed up, busy, with
its boxes locked. The card now goes back to the login screen first.

* Hand the session cookie back when a login is dismissed mid-request

The server sets the session cookie as soon as it accepts a login or a
second-factor code. Dropping an answer that arrived after the card closed
kept the page on its account while the cookie had moved to the other one,
so cookie-gated actions (password, 2FA) applied to that account and the
next load picked up its token. The cookie is now synced back to the
account the page is signed in as.

* Keep padded notices inside the auth page's column

On a phone-width page or in a sign-in popup, every direct child of the
auth body is stretched to the column's width. The overlay sits outside
.dashboard, so it isn't border-box, and the padded error line and bonus
notice came out wider than the fields and scrolled the page sideways.

* Keep the recovery-code field one size when it takes focus

On phones the generic dialog-input and phone input rules outranked the
recovery-code field's style until it was focused, so tapping it grew the
text from 16-17px to 20px and shifted the screen. The field's rule now
carries the same weight as theirs, like the code boxes beside it.

* Show the provider buttons' hover in dark mode

The hover shade was the sidebar background, which in dark mode is one
step off the card's, so Google, Apple and the other sign-in buttons gave
no feedback under the pointer. Dark mode now uses the hover shade.

* Theme the signup bonus notice with the auth card

The notice kept the old signup window's fixed pastel colors, which stood
out as a light box on the card in dark mode. It now uses the dashboard's
success and danger colors, which follow the color scheme.

* Keep a new account's email check from closing without an answer

A signup that needs its email confirmed takes the auth card down and
waits on the confirmation window, whose ✕ closed it without ever
answering. In a sign-in popup reached from the account picker that left
an empty popup with nothing to pick. The check now stays until the code
is confirmed, like the phone and card checks and the boot-time email
check.
2026-11-06 15:20:08 -07:00
Daniel Salazar 162398a827 test: fix coverage line mapping, puter.js coverage OOM, and flaky backend tests (#4523)
- lowerDecoratorsPlugin dropped esbuild's source map, so coverage and
  stack traces reported transformed lines. Pass the external map through.
- puter.js node runner kept a ~6 MB `__coverage__` per vm context and ran
  out of heap. Contexts now share one object; workerd merges as it goes.
  report-coverage skips its comparison when the PR leg failed.
- CI-only test/hook timeouts of 20 s / 60 s.
- setupTestServer disables the database-liveness health check, whose
  `SELECT 1` landed in query-counting tests.
- LocalWorkerService.shutdown asserts the timer shutdown arms instead of
  the global fake-timer count.
- userHandlers worker test waits for posts by label.
- AppStore stats test pins the clock so rows don't cross midnight UTC.
- Realtime backpressure test waits up to 5 s for holds to settle.
2026-11-06 12:30:36 -07:00
jelveh 6785b4d9cc Reorder recommended apps and drop terminal
Updates `RECOMMENDED_APP_NAMES` to prioritize core productivity apps (`word-processor`, `spreadsheet`, `presentation`, `whiteboard`, `pdf-editor`) immediately after `builder`, and removes `terminal` from the recommended list.
2026-11-06 09:05:33 -07:00
Nariman Jelveh d2acdafaed Show recommended apps in the app browser embed without a session (#4517)
* Show recommended apps in the app browser embed without a session

/embed/apps only worked for a signed-in user; without a session it showed
an unavailable state. The route now puts the recommended apps
(RecommendedAppsService) in the page's config as guestApps, and when the
embed finds no session it shows those, without loading puter.js or reading
installed apps, folders, or saved order. 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>.
Signed-in behavior is unchanged.

createAppBrowser takes a guestApps option for this, and appTabLaunch's
URL building is shared between launchAppInTab and the new
guestAppLaunchUrl.

* Show the app browser embed's error state when the session lookup fails

Only a 401 from /get-gui-token now means there is no session. A rate
limit or server error shows the unavailable state, as before, instead of
the signed-out list of recommended apps.

* Let the app browser embed find no session when storage is refused

Reading local storage can throw when the browser blocks site data. The
embed now falls back to the session cookie, as it does for empty
storage, so a visitor without a session sees the recommended apps
instead of the unavailable state.

* Fix the app browser embed doc's broken sentence about puterOrigin
2026-11-06 07:48:11 -07:00
Reynaldi Chernando 6a46363d6d reorder api sections (#4519) 2026-11-06 17:30:22 +07:00
Reynaldi Chernando 2de9d509e8 docs layout cleanup (#4518) 2026-11-06 16:22:48 +07:00
Nariman Jelveh 763742dbc0 fix(embed): read the app browser's session from the cookie when its storage is empty (#4516)
Safari keys a framed origin's local storage by the top-level origin, so the
app browser embedded on a sibling subdomain finds no auth_token_v2 and shows
"Apps are unavailable". The session cookie is still sent there, so the embed
now falls back to /get-gui-token and keeps the token in memory.
2026-11-05 23:41:38 -07:00
Daniel Salazar 7f0cd1689b fix(embed): only sibling subdomains not served by core can frame the app browser (#4515)
/embed/apps now names the referring origin in frame-ancestors only when it
is exactly one label under the domain and that label is not one the server
answers itself (api, dav, js, www, native-app hosts) or the host of
api_base_url. Nested subdomains are refused too.

The query-string redirect now checks the raw URL instead of the parsed
query, so every request carrying a query string is redirected.
2026-11-05 23:10:34 -07:00
Daniel Salazar 9d22f39928 Ask for notification permission from Puter's dialog when the click has expired (#4514)
On a website, puter.notifications.enable() threw user_gesture_required
without prompting once the calling click's activation was gone: after
puter.auth.signIn() or requestPermission() opened a popup in the same
click, after a few seconds of awaited work, or when called on load. Apps
that ignored the error showed nothing.

It now shows Puter's consent dialog in that case and asks the browser
from its Continue click; Cancel resolves false. Calls made while an ask
is open share it. PuterDialog gets an onContinue option and a show()
that launch() also uses. Inside Puter's own desktop page the call still
throws, since it always runs from a click.

The push guide also notes that Chrome stops showing the prompt after
three dismissals and that its quieter messaging shows a bell icon.
2026-11-05 23:10:06 -07:00
Nariman Jelveh ef185c04ca Open apps from the dashboard's Home tab at their own URL (#4513)
Recently used apps on the Home tab opened /app/<name> in a new tab, which
loads the desktop and launches the app from there. They now open the way
Apps tab tiles do: a new tab at the app's index_url through launch_app's
newTab, or in this page when the browser refuses the tab. The Apps tab's
open-window lookup moves to helpers/focusAppWindow.js so both share it,
and the shared launch lives in helpers/dashboardAppLaunch.js, outside the
app browser so the embed bundle doesn't pull in launch_app.
2026-11-05 21:30:52 -07:00
Nariman Jelveh dec7d1fd96 Load the app browser embed's script from beside the GUI bundle (#4511)
The embed page always loaded /dist/apps-embed.min.js from the server,
while the GUI bundle and the embed build are published to gui_bundle's
location (a CDN in production). The server's /dist copy can be stale, so
the embed ran an old build. It now loads apps-embed.min.js from
gui_bundle's directory, keeping /dist when gui_bundle isn't set.
2026-11-05 21:07:05 -07:00
316 changed files with 16515 additions and 5815 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/convoLive.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/realtimeLive.test.ts
env:
CI: 'true'
PUTER_TEST_AI_OPENAI_API_KEY: ${{ secrets.PUTER_TEST_AI_OPENAI_API_KEY }}
+6 -2
View File
@@ -176,7 +176,10 @@ 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
@@ -186,6 +189,7 @@ 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:
@@ -193,7 +197,7 @@ jobs:
path: coverage-base
- name: Report coverage on PR
if: steps.base-coverage.outcome == 'success'
if: steps.pr-coverage.outcome == 'success' && steps.base-coverage.outcome == 'success'
uses: davelosert/vitest-coverage-report-action@v2
with:
name: puter.js SDK
@@ -202,7 +206,7 @@ jobs:
json-summary-compare-path: coverage-base/coverage-summary.json
- name: Report coverage on PR (no base comparison)
if: steps.base-coverage.outcome != 'success'
if: steps.pr-coverage.outcome == 'success' && steps.base-coverage.outcome != 'success'
uses: davelosert/vitest-coverage-report-action@v2
with:
name: puter.js SDK
+4 -1
View File
@@ -159,7 +159,9 @@ 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. 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.
**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 `).
### Function page layout
@@ -200,6 +202,7 @@ 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
+149 -28
View File
@@ -14,24 +14,50 @@ 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`.
## Session and framing
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 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.
The route's `Content-Security-Policy: frame-ancestors` allows the GUI origin and
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
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
`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
@@ -46,14 +72,22 @@ and popups to escape the sandbox.
## Host integration
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.
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.
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.
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;
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.
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.
```html
<button id="more-apps" type="button">More apps</button>
@@ -71,10 +105,14 @@ frame labels using the host app's localization system.
const container = document.querySelector('#apps-frame');
const trigger = document.querySelector('#more-apps');
trigger.addEventListener('click', () => {
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)}`;
const frame = document.createElement('iframe');
frame.title = 'Your apps';
frame.src = new URL('/embed/apps', puterOrigin).href;
frame.src = url.href;
container.replaceChildren(frame);
dialog.showModal();
});
@@ -86,20 +124,103 @@ frame labels using the host app's localization system.
</script>
```
## Implementation and checks
## Implementation
`createAppBrowser` in `src/gui/src/UI/Dashboard/AppBrowser.js` owns the shared UI
and data behavior. `TabApps.js` injects desktop actions. `appsEmbed.js` supplies
new-tab launching through `launchAppInTab` in `src/gui/src/helpers/appTabLaunch.js`,
which builds the same app URL as `launch_app`, 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.
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.
## Checks
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
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
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
```
@@ -27,6 +27,7 @@ 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 ────────────────────────────────────────────────────
//
@@ -529,3 +530,46 @@ 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,13 +22,29 @@ 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.
*/
export const FRAMED_POPUP_ACTIONS = [
'sign-in',
'show-open-file-picker',
'show-save-file-picker',
'show-directory-picker',
] as const;
/** Longest description/og:description/twitter:description on `/app/<name>`. */
export const APP_META_DESCRIPTION_MAX = 150;
@@ -57,31 +73,37 @@ 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'
>;
/**
* `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.
* 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).
*/
export function embedFrameAncestors(
config: Pick<
IConfig,
| 'origin'
| 'domain'
| 'static_hosting_domain'
| 'static_hosting_domain_alt'
| 'private_app_hosting_domain'
| 'private_app_hosting_domain_alt'
>,
export function embedHostOrigin(
config: EmbedFramingConfig,
referer: string | undefined,
): string {
): string | null {
const gui = new URL(config.origin ?? `https://${config.domain}`);
let parent: URL;
try {
parent = new URL(referer ?? '');
} catch {
return "'self'";
return null;
}
const host = parent.hostname.toLowerCase();
const label = subdomainLabelOf(host, config.domain);
const hostingDomains = [
config.static_hosting_domain,
config.static_hosting_domain_alt,
@@ -93,9 +115,20 @@ export function embedFrameAncestors(
const allowed =
parent.protocol === gui.protocol &&
parent.port === gui.port &&
host.endsWith(`.${config.domain.toLowerCase()}`) &&
label !== undefined &&
!isReservedSubdomain(label) &&
host !== new URL(config.api_base_url).hostname &&
!hostingDomains.some((d) => host === d || host.endsWith(`.${d}`));
return allowed ? `'self' ${parent.origin}` : "'self'";
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'";
}
/**
@@ -132,6 +165,7 @@ export class HomepageController extends PuterController {
res: express.Response,
metaOverrides: Partial<PageMeta> = {},
launch: LaunchOptions = {},
popupFrame?: PopupFrame,
) => {
const meta = { ...defaultMeta(req), ...metaOverrides };
const actor =
@@ -140,18 +174,27 @@ export class HomepageController extends PuterController {
actor?: Parameters<typeof homepage.send>[0]['actor'];
}
).actor ?? null;
await homepage.send({ req, res, actor }, meta, launch);
await homepage.send({ req, res, actor }, meta, launch, popupFrame);
};
// -- Root + path-aliased shell routes ------------------------
router.get('/', {}, (req, res) => sendShell(req, res));
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;
/**
* 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;
}
res.removeHeader('X-Frame-Options');
res.setHeader(
@@ -159,9 +202,61 @@ export class HomepageController extends PuterController {
`frame-ancestors ${embedFrameAncestors(this.config, req.get('referer'))}`,
);
res.setHeader('Cache-Control', 'no-store');
res.send(homepage.renderAppBrowserEmbed());
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 }));
});
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));
@@ -187,9 +187,9 @@ describe('createUserSubdomainNotFound', () => {
});
it('passes through reserved subdomains (api, js, native apps, etc.)', () => {
// `api`, `js`, `dav`, `docs`, `developer`, `editor`, `pdf`,
// `api`, `js`, `dav`, `docs`, `developer`, `about`, `apps`,
// `puter-app-icons`, etc. all pass through.
for (const sub of ['api', 'js', 'docs', 'editor', 'puter-app-icons']) {
for (const sub of ['api', 'js', 'docs', 'about', '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, 'editor', 'assets'), { recursive: true });
mkdirSync(nodePath.join(root, 'about', 'assets'), { recursive: true });
writeFileSync(
nodePath.join(root, 'editor', 'index.html'),
'<h1>editor</h1>',
nodePath.join(root, 'about', 'index.html'),
'<h1>about</h1>',
);
writeFileSync(
nodePath.join(root, 'editor', 'assets', 'app.js'),
nodePath.join(root, 'about', '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', 'editor'],
subdomains: ['com', 'example', 'about'],
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', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/index.html',
}),
);
@@ -915,17 +915,24 @@ describe('createNativeAppStatic', () => {
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);
});
// `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 when there is no subdomain at all', async () => {
const { next } = await runStatic(
@@ -939,13 +946,13 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/index.html',
}),
);
expect(out.sent).toEqual({
path: '/index.html',
root: nodePath.join(root, 'editor'),
root: nodePath.join(root, 'about'),
});
expect(next).not.toHaveBeenCalled();
});
@@ -954,11 +961,11 @@ describe('createNativeAppStatic', () => {
const { out } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'EDITOR'],
subdomains: ['localhost', 'puter', 'ABOUT'],
path: '/index.html',
}),
);
expect(out.sent?.root).toBe(nodePath.join(root, 'editor'));
expect(out.sent?.root).toBe(nodePath.join(root, 'about'));
});
it('serves docs out of its dist/ subdirectory, not the app root', async () => {
@@ -979,7 +986,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/assets',
originalUrl: '/assets?v=2',
}),
@@ -995,7 +1002,7 @@ describe('createNativeAppStatic', () => {
const { out } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/assets/',
}),
);
@@ -1007,7 +1014,7 @@ describe('createNativeAppStatic', () => {
const { out, next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/nope.html',
}),
);
@@ -1019,7 +1026,7 @@ describe('createNativeAppStatic', () => {
const { next } = await runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/index.html',
}),
new Error('send failed'),
@@ -1032,7 +1039,7 @@ describe('createNativeAppStatic', () => {
runStatic(
withRoot(),
staticReq({
subdomains: ['localhost', 'puter', 'editor'],
subdomains: ['localhost', 'puter', 'about'],
path: '/../../etc/passwd',
}),
),
@@ -27,15 +27,7 @@ import { HttpError, isHttpError } from '../HttpError';
import { isLocalWorkerHost } from './localWorkerProxy';
/** Native-app subdomains served via `nativeAppStatic`. */
const NATIVE_APP_SUBDOMAINS = [
'about',
'developer',
'docs',
'editor',
'markus',
'pdf',
'apps',
] as const;
const NATIVE_APP_SUBDOMAINS = ['about', 'developer', 'docs', 'apps'] as const;
/** Subset served out of a `dist/` subdirectory rather than the app root. */
const NATIVE_APPS_WITH_DIST = new Set(['docs', 'developer']);
@@ -111,6 +103,10 @@ 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.
@@ -123,7 +119,7 @@ export const addClaimedSubdomain = (
if (typeof name !== 'string' || !SUBDOMAIN_LABEL.test(name)) {
throw new Error(`Invalid subdomain label: ${JSON.stringify(name)}`);
}
if (name === 'www' || RESERVED_SUBDOMAINS.has(name)) {
if (isReservedSubdomain(name)) {
throw new Error(`Subdomain '${name}' is reserved`);
}
if (claims.has(name)) {
+115 -2
View File
@@ -352,6 +352,10 @@ 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}`,
@@ -364,9 +368,114 @@ 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',
])('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/'])(
'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],
@@ -379,8 +488,12 @@ describe('PuterServer host header validation', () => {
expect(res.headers['content-security-policy']).toBe("frame-ancestors 'self'");
});
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', {
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`, {
host: `puter.localhost:${port}`,
});
expect(res.status).toBe(302);
@@ -27,17 +27,16 @@ 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,11 +144,22 @@ const createInline = async (
return String(response.body.subId);
};
const delivered = (count = 1): Promise<void> =>
vi.waitFor(() => expect(sinkPosts.length).toBeGreaterThanOrEqual(count), {
timeout: 30_000,
interval: 50,
});
/**
* 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)!,
);
};
beforeAll(async () => {
env = await setupPuterTestEnv({
@@ -255,14 +266,11 @@ describe('an inline handler in a user scope, end to end', () => {
await env.server.services.fs.touch(holder.id, {
path: `${holder.anchor}/note.txt`,
});
await delivered();
const [post] = await delivered('inline');
expect(sinkPosts[0]).toMatchObject({
label: 'inline',
path: `${holder.anchor}/note.txt`,
});
expect(post.path).toBe(`${holder.anchor}/note.txt`);
const { actor } = await env.server.services.auth.authenticate(
sinkPosts[0].token!,
post.token!,
);
expect(actor!.user?.id).toBe(holder.id);
expect(actor!.effectiveApp?.uid).toBe(appUid);
@@ -297,14 +305,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`,
});
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,
// 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!,
);
expect(runAs).toEqual(new Set(holders.map((h) => h.id)));
expect(actor!.user!.id).toBe(holders[i].id);
}
create.mockRestore();
},
);
@@ -63,13 +63,28 @@ 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,
apiOrigin: 'https://api.deployment.test', sdkUrl, guestApps: [],
});
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({
@@ -80,6 +95,41 @@ 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,6 +48,15 @@ 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;
@@ -167,15 +176,54 @@ export class PuterHomepageService extends PuterService {
this.#guiParams[key] = val;
}
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');
/** `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');
return `<!DOCTYPE html>
<html lang="en">
@@ -186,16 +234,33 @@ 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/apps-embed.css">
<link rel="stylesheet" href="/css/${stylesheet}">
</head>
<body>
<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>
<main id="${rootId}"${rootClass ? ` class="${rootClass}"` : ''}></main>
<script type="application/json" id="${rootId}-config">${configJson}</script>
<script defer src="${encode(this.#embedScript(script))}"></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 (
@@ -247,6 +312,7 @@ 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;
@@ -271,6 +337,7 @@ export class PuterHomepageService extends PuterService {
{ req, actor: actor ?? null },
meta,
launchOptions,
popupFrame,
);
res.send(html);
}
@@ -281,6 +348,7 @@ 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';
@@ -326,6 +394,8 @@ 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,7 +78,10 @@ describe('LocalWorkerService shutdown disposal', () => {
disposals[0].mockImplementationOnce(async () => {
await held;
});
vi.useFakeTimers();
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');
try {
let finished = false;
const draining = Promise.resolve(service.onServerShutdown()).then(
@@ -86,12 +89,13 @@ 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();
}
@@ -2860,8 +2860,12 @@ 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 vi.waitFor(async () =>
await settled(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(64 * 10_896_000),
@@ -2890,7 +2894,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 vi.waitFor(() =>
await settled(() =>
expect(
recorded.mock.calls
.flatMap(([, rows]) => rows)
@@ -2906,13 +2910,13 @@ describe('OpenAIRealtimeRelayService relay', () => {
.filter((row) => row.usageType.includes('transcription_'))
.reduce((sum, row) => sum + row.costOverride!, 0),
).toBe(640);
await vi.waitFor(async () =>
await settled(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(2 * 10_896_000),
);
c.ws.close();
await vi.waitFor(async () =>
await settled(async () =>
expect(
await server.services.metering.getOutstandingHolds(actor),
).toBe(0),
+3 -3
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.convo()`](../../../docs/src/AI/convo.md).
it through [`puter.ai.realtime()`](../../../docs/src/AI/realtime.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.md).
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime-websocket.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.convo({ output: ['text'] });
const conversation = await puter.ai.realtime({ output: ['text'] });
conversation.on('error', (event) => console.error(event));
conversation.on('text', ({ delta }) => console.log(delta));
conversation.on('turn.done', () => conversation.close());
+9 -4
View File
@@ -1542,18 +1542,22 @@ describe('AppStore detailed stats', () => {
let db;
const APP_UID = `app-stats-${Date.now()}`;
const nowSeconds = Math.floor(Date.now() / 1000);
// 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);
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; the repeat shares a timestamp so it is always same-hour.
// Two users in one hour. Windows end at now, exclusive.
for (const [userId, offset] of [
[1, 0],
[1, 0],
[1, 60],
[1, 60],
[2, 120],
]) {
await db.write(
@@ -1564,6 +1568,7 @@ describe('AppStore detailed stats', () => {
});
afterAll(async () => {
vi.useRealTimers();
await server?.shutdown();
});
+3
View File
@@ -154,6 +154,9 @@ 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,12 +256,7 @@ 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';
}
/**
@@ -1106,7 +1101,11 @@ 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`. */
/**
* 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.
*/
gui_bundle: string;
/** Override the GUI CSS path when bundled. Default: `/dist/bundle.min.css`. */
gui_css: string;
@@ -1393,7 +1392,8 @@ 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>[];
+10 -3
View File
@@ -37,6 +37,9 @@ 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`.
@@ -103,9 +106,11 @@ export const lowerDecoratorsPlugin = {
loader: 'ts',
target: 'es2024',
sourcefile: id,
sourcemap: 'inline',
sourcemap: 'external',
});
return { code: result.code, map: null };
// Without the map, coverage and stack traces report esbuild's
// output lines instead of the source's.
return { code: result.code, map: result.map };
},
};
@@ -145,7 +150,9 @@ export default defineConfig(({ mode }) => ({
hookTimeout: pgmockTimeoutMs,
fileParallelism: false,
}
: {}),
: isCi
? ciTimeouts
: {}),
coverage: {
provider: 'v8',
reporter: isCi
+13 -5
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">${cleanTitle}</a>`;
html += `<a href="#" class="toc-link toc-level-1" data-level="1">${breakAfterDots(cleanTitle)}</a>`;
for ( const heading of headings ) {
html += `<a href="#${heading.slug}" class="toc-link toc-level-${heading.level}" data-level="${heading.level}">${heading.text}</a>`;
html += `<a href="#${heading.slug}" class="toc-link toc-level-${heading.level}" data-level="${heading.level}">${breakAfterDots(heading.text)}</a>`;
}
html += '</nav>';
@@ -457,10 +457,12 @@ 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">`;
// context menu
// 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>`;
html += generateMenuHTML();
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>`;
html += '</div>';
// Platform compatibility badges
html += generatePlatformCompatibilityHTML(frontMatter);
html += '<hr class="hr-inset">';
@@ -852,6 +854,12 @@ 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 of 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<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
@@ -1,143 +0,0 @@
---
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,6 +22,8 @@ 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>
+6 -2
View File
@@ -43,13 +43,15 @@ 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.
@@ -64,6 +66,8 @@ 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
@@ -0,0 +1,126 @@
---
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.
+129 -102
View File
@@ -1,124 +1,151 @@
---
title: Realtime WebSocket API (Beta)
description: Connect to OpenAI realtime conversations through Puter without puter.js.
title: puter.ai.realtime()
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
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.
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.
**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.convo()`](/AI/convo/).
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime-websocket/).
## 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:
## Syntax
```js
import WebSocket from 'ws';
const conversation = await puter.ai.realtime(options = {});
await conversation.connect();
```
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));
## Parameters
socket.on('message', (data) => {
const event = JSON.parse(data.toString());
#### `options` (Object) (Optional)
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();
The options object accepts these fields.
| 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. |
## 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.
## 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.
```js
const conversation = await puter.ai.realtime({
output: ['text'],
instructions: 'Keep replies short.',
});
socket.on('error', console.error);
socket.on('close', (code, reason) => console.log(code, reason.toString()));
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.');
```
## Events, audio, and interruption
### Have a voice conversation
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.
A voice conversation enables the microphone and speaker after connection.
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.
```js
const conversation = await puter.ai.realtime();
conversation.on('transcript', ({ role, text }) => console.log(role, text));
conversation.on('error', (event) => console.error(event));
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`.
await conversation.connect();
await conversation.speaker.start();
await conversation.microphone.start();
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.
// To interrupt a response and submit a replacement text turn:
await conversation.interrupt();
conversation.sendText('Actually, make it Wednesday.');
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
}
// When the user ends the conversation:
conversation.close();
```
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
<strong class="example-title">List engines for a specific provider</strong>
### List engines for a specific provider
```html;ai-txt2speech-list-engines
<html>
@@ -73,7 +73,7 @@ Example response:
</html>
```
<strong class="example-title">List engines using options object</strong>
### List engines using options object
```js
const engines = await puter.ai.txt2speech.listEngines({ provider: 'elevenlabs' });
+6 -4
View File
@@ -4,7 +4,9 @@ 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
@@ -52,7 +54,7 @@ Example response (with `provider: 'all'`):
## Examples
<strong class="example-title">List voices for a provider</strong>
### List voices for a provider
```html;ai-txt2speech-list-voices
<html>
@@ -71,7 +73,7 @@ Example response (with `provider: 'all'`):
</html>
```
<strong class="example-title">List all default (AWS Polly) voices</strong>
### List all default (AWS Polly) voices
```js
const voices = await puter.ai.txt2speech.listVoices();
@@ -81,7 +83,7 @@ for (const voice of voices) {
}
```
<strong class="example-title">List Gemini voices</strong>
### List Gemini voices
```js
const voices = await puter.ai.txt2speech.listVoices({ provider: 'gemini' });
+3 -1
View File
@@ -4,7 +4,9 @@ description: Convert text to speech with AI using multiple languages, voices, an
platforms: [websites, apps, nodejs, workers]
---
Converts text into speech using AI. Supports multiple languages and voices.
Converts text into speech using AI.
It 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.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.update()`](/Apps/update/)** - Update application settings
- **[`puter.apps.delete()`](/Apps/delete/)** - Delete an application
- **[`puter.apps.checkName()`](/Apps/checkName/)** - Check whether an app name is available
## Examples
+4 -2
View File
@@ -4,7 +4,9 @@ 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
@@ -24,7 +26,7 @@ A `Promise` that will resolve to an object describing the name's availability.
## Examples
<strong class="example-title">Check a name before creating the app</strong>
### Check a name before creating the app
```html
<html>
+17 -13
View File
@@ -4,7 +4,9 @@ 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
@@ -39,17 +41,19 @@ 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:
- `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.
| 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`. |
## Return value
@@ -57,7 +61,7 @@ A `Promise` that will resolve to the [`CreateAppResult`](/Objects/createappresul
## Examples
<strong class="example-title">Create an app pointing to example.com</strong>
### Create an app pointing to example.com
```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
<strong class="example-title">Create a random app then delete it</strong>
### Create a random app then delete it
```html;app-delete
<html>
+9 -6
View File
@@ -4,7 +4,9 @@ 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
@@ -19,13 +21,14 @@ puter.apps.get(name, options)
The name of the app to get.
### options (optional)
#### `options` (Object) (optional)
An object containing the following properties:
- `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).
| 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). |
## Return value
@@ -33,7 +36,7 @@ A `Promise` that will resolve to the [`App`](/Objects/app/) object with the give
## Examples
<strong class="example-title">Create a random app then get it</strong>
### Create a random app then get it
```html;app-get
<html>
+13 -15
View File
@@ -4,7 +4,9 @@ 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
@@ -19,19 +21,15 @@ puter.apps.list(options)
An object containing the following properties:
- `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`.
| 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). |
## Return value
@@ -57,7 +55,7 @@ for await (const page of puter.apps.list({ stream: true })) {
## Examples
<strong class="example-title">Create 3 random apps and then list them</strong>
### Create 3 random apps and then list them
```html;app-list
<html>
+14 -11
View File
@@ -17,16 +17,19 @@ The name of the app to update.
#### `attributes` (required)
An object containing the attributes to update. The object can contain the following properties:
- `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.
| 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. |
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.
@@ -35,7 +38,7 @@ A `Promise` that will resolve to the [`App`](/Objects/app/) object that was upda
## Examples
<strong class="example-title">Create a random app then change its title</strong>
### Create a random app then change its title
```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.signOut()`](/Auth/signOut/)** - Sign out the current 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.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
+3 -1
View File
@@ -29,7 +29,9 @@ The id of the application.
A `Promise` that resolves to a [`DetailedAppUsage`](/Objects/detailedappusage) object containing resource usage statistics for the given application.
## Example
## Examples
### Get an app's usage
```html
<html>
+3 -1
View File
@@ -26,7 +26,9 @@ None
A `Promise` that resolves to a [`MonthlyUsage`](/Objects/monthlyusage) object containing the user's monthly usage information.
## Example
## Examples
### Get the user's monthly usage
```html;auth-get-monthly-usage
<html>
+7 -3
View File
@@ -4,7 +4,9 @@ description: Read a user's profile, returning null when it is not available.
platforms: [websites, apps, nodejs, workers]
---
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.
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.
## Syntax
@@ -15,7 +17,7 @@ puter.auth.getProfile(username);
## Parameters
### `username` (optional)
#### `username` (optional)
The username to look up. Defaults to the signed-in user.
@@ -25,7 +27,9 @@ 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.
## Example
## Examples
### Show the user's profile
```html
<html>
+7 -3
View File
@@ -4,7 +4,9 @@ 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
@@ -15,7 +17,7 @@ puter.auth.getProfilePicture(username);
## Parameters
### `username` (optional)
#### `username` (optional)
The username to look up. Defaults to the signed-in user.
@@ -27,7 +29,9 @@ 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.
## Example
## Examples
### Show the user's profile picture
```html
<html>
+3 -1
View File
@@ -20,7 +20,9 @@ None
A promise that resolves to a [`User`](/Objects/user) object containing the user's basic information.
## Example
## Examples
### Get the signed-in user
```html;auth-get-user
<html>
+3 -1
View File
@@ -20,7 +20,9 @@ None
Returns `true` if the user is signed in, `false` otherwise.
## Example
## Examples
### Check whether the user is signed in
```html;auth-is-signed-in
<html>
+12 -7
View File
@@ -4,7 +4,9 @@ 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.
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.
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.
@@ -27,11 +29,12 @@ puter.auth.signIn(options)
#### `options` (optional)
`options` is an object with the following properties:
An object with the following properties:
- `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.
| 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. |
Each call completes from its own sign-in window, including when multiple calls run at once.
@@ -39,7 +42,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.
## Rejection
## Errors
The promise will reject with an object containing an `error` code and a human-readable `msg` in the following cases:
@@ -53,7 +56,9 @@ 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.
## Example
## Examples
### Sign in from a button click
```html;auth-sign-in
<html>
+3 -1
View File
@@ -22,7 +22,9 @@ 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.
## Example
## Examples
### Sign the user out
```html;auth-sign-out
<html>
+18 -8
View File
@@ -5,7 +5,9 @@ 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
@@ -15,19 +17,27 @@ puter.auth.updateProfile(patch);
## Parameters
### `patch` (required)
#### `patch` (required)
An object with any of these fields:
- `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.
| 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. |
Any other field is rejected.
## Return value
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:
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:
| `code` | Meaning |
| --------------------------- | ----------------------------------------------------- |
@@ -37,9 +47,9 @@ A promise that resolves to the stored [`UserProfile`](/Objects/userprofile). It
| `profile_picture_too_large` | `picture` is over the size limit |
| `profile_field_too_long` | `displayName` or `bio` is over its length limit |
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.
## Examples
## Example
### Change the user's display name
```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
+11 -7
View File
@@ -4,7 +4,9 @@ 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.
@@ -23,9 +25,11 @@ The message id from `puter.email.list()`. Looks up the inbox.
#### `options` (Object)
- `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`.
| 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`. |
## Return value
@@ -45,7 +49,7 @@ Rejects with an object carrying a `code`:
## Examples
<strong class="example-title">Read the newest message in the inbox</strong>
### Read the newest message in the inbox
```html
<html>
@@ -66,7 +70,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Save every attachment of a message to the user's Documents</strong>
### Save every attachment of a message to the user's Documents
```html
<html>
@@ -89,7 +93,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Download the raw message</strong>
### Download the raw message
```html
<html>
+12 -8
View File
@@ -4,7 +4,9 @@ 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/):
@@ -23,10 +25,12 @@ puter.email.list(options)
#### `options` (Object) (optional)
- `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.
| 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. |
`offset` and `includeTotal` are not supported for mailboxes; passing either rejects with `invalid_request`.
@@ -45,7 +49,7 @@ Rejects with an object carrying a `code`:
## Examples
<strong class="example-title">List the ten newest messages</strong>
### List the ten newest messages
```html
<html>
@@ -64,7 +68,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Walk the whole sent folder with a cursor</strong>
### Walk the whole sent folder with a cursor
```html
<html>
@@ -86,7 +90,7 @@ Rejects with an object carrying a `code`:
</html>
```
<strong class="example-title">Stream pages</strong>
### Stream pages
```html
<html>
+30 -20
View File
@@ -4,7 +4,9 @@ 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>
@@ -31,21 +33,25 @@ A plain-text body. Shorthand for `text`; use the options form for anything else.
#### `options` (Object)
- `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.
| 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`.
## Return value
@@ -56,7 +62,11 @@ 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; 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.
## Errors
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:
@@ -90,7 +100,7 @@ Sends are rate-limited per calling account; the numbers are on [Rate Limits and
## Examples
<strong class="example-title">Send a plain-text notification from a worker</strong>
### Send a plain-text notification from a worker
```js
// The worker is the caller, so its owner is billed and rate-limited.
@@ -104,7 +114,7 @@ router.post('/api/alert', async ({ request }) => {
});
```
<strong class="example-title">Let the user pay for their own sends</strong>
### Let the user pay for their own sends
```js
// The user's session makes the call; the worker's token authorizes it.
@@ -122,7 +132,7 @@ router.post('/api/receipt', async ({ request, user }) => {
});
```
<strong class="example-title">Attach a file and show an inline image</strong>
### Attach a file and show an inline image
```js
// The uid of a file in the worker owner's storage, e.g. from
+26 -20
View File
@@ -4,9 +4,11 @@ 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>
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`.
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.
@@ -25,11 +27,13 @@ puter.events.fetch(options)
#### `options` (Object) (required)
- `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.
| 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. |
## Return value
@@ -42,18 +46,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:
@@ -74,6 +78,8 @@ 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 |
@@ -89,7 +95,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Catch up on everything missed</strong>
### Catch up on everything missed
```html;events-fetch
<html>
@@ -118,7 +124,7 @@ The promise rejects with `{ message, code }`:
</html>
```
<strong class="example-title">Read the missed ones, then keep listening</strong>
### Read the missed ones, then keep listening
```html;events-fetch-then-listen
<html>
+6 -2
View File
@@ -4,9 +4,11 @@ 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>
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 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.
@@ -26,6 +28,8 @@ 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 |
@@ -38,7 +42,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Check when a stored notification goes out</strong>
### Check when a stored notification goes out
```html;events-get-schedule
<html>
+14 -7
View File
@@ -4,9 +4,11 @@ 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** 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 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:
@@ -97,9 +99,14 @@ 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.
- `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.
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. |
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.
@@ -184,7 +191,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`.
<strong class="example-title">Publish into the user's scope, list it, then remove it</strong>
### Publish into the user's scope, list it, then remove it
```js
const published = await puter.events.handlers.publish(
@@ -203,7 +210,7 @@ for (const handler of await puter.events.handlers.list({ scope: 'user' })) {
await puter.events.handlers.remove('digest', { scope: 'user' });
```
<strong class="example-title">Publish a handler, list it, then remove it</strong>
### Publish a handler, list it, then remove it
```js
const published = await puter.events.handlers.publish(
@@ -224,7 +231,7 @@ const removed = await puter.events.handlers.remove('ingestUpload', { appUid });
console.log(removed.removed, removed.suspended);
```
<strong class="example-title">Deploy a whole set from a build step</strong>
### Deploy a whole set from a build step
```js
const published = await puter.events.handlers.publishAll([
+13 -7
View File
@@ -4,9 +4,11 @@ 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>
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.
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.
@@ -22,10 +24,12 @@ puter.events.list(options)
#### `options` (Object) (optional)
- `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.
| 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. |
## Return value
@@ -40,6 +44,8 @@ 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 |
@@ -51,7 +57,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">List everything this account is watching</strong>
### List everything this account is watching
```html;events-list
<html>
@@ -78,7 +84,7 @@ The promise rejects with `{ message, code }`:
</html>
```
<strong class="example-title">Find the ones that stopped, and why</strong>
### Find the ones that stopped, and why
```html;events-list-suspended
<html>
+11 -5
View File
@@ -4,9 +4,11 @@ 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>
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.
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.
@@ -24,9 +26,11 @@ puter.events.listSchedules(options)
#### `options` (Object) (optional)
- `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.
| 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. |
## Return value
@@ -40,6 +44,8 @@ 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 |
@@ -53,7 +59,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">List every schedule, page by page</strong>
### List every schedule, page by page
```html;events-list-schedules
<html>
+4 -2
View File
@@ -4,9 +4,11 @@ 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>
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.
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.
@@ -25,7 +27,7 @@ A `Promise` that resolves when the subscription is gone. It never rejects. Calli
## Examples
<strong class="example-title">Watch a directory, then stop watching it</strong>
### Watch a directory, then stop watching it
```html;events-off
<html>
+13 -7
View File
@@ -4,9 +4,11 @@ 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>
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.
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.
@@ -28,9 +30,11 @@ Called with `{ event }` for each delivery. See [The event](/Events/subjects/#the
#### `options` (Object) (optional)
- `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`.
| 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`. |
## Return value
@@ -47,6 +51,8 @@ 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 |
@@ -98,7 +104,7 @@ If the connection is down when this happens, or drops before `onError` is called
## Examples
<strong class="example-title">Watch a directory and print what changes</strong>
### Watch a directory and print what changes
```html;events-watch-folder
<html>
@@ -130,7 +136,7 @@ If the connection is down when this happens, or drops before `onError` is called
</html>
```
<strong class="example-title">React to a file that does not exist yet</strong>
### React to a file that does not exist yet
```html;events-watch-missing
<html>
@@ -163,7 +169,7 @@ If the connection is down when this happens, or drops before `onError` is called
</html>
```
<strong class="example-title">Watch this app's key-value store</strong>
### Watch this app's key-value store
```html;events-watch-kv
<html>
+78 -72
View File
@@ -4,9 +4,11 @@ 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>
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.
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.
@@ -23,17 +25,78 @@ puter.events.onPersistent(options)
#### `options` (Object) (required)
- `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.
| 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.
## Background delivery needs consent
@@ -163,68 +226,11 @@ 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.
<strong class="example-title">Watch a folder with an inline handler</strong>
### Watch a folder with an inline handler
```js
await puter.perms.request('backgroundEvents');
@@ -242,7 +248,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.
<strong class="example-title">Watch a folder with a handler the app's owner published</strong>
### Watch a folder with a handler the app's owner published
Publish once as the developer to ship one shared handler to every user.
@@ -267,7 +273,7 @@ const sub = await puter.events.onPersistent({
await puter.events.unsubscribe(sub.subId);
```
<strong class="example-title">Bind to the exact source you wrote against</strong>
### Bind to the exact source you wrote against
```js
const handler = ({ event, ctx }) => console.log(ctx.label, event.path);
+95 -89
View File
@@ -4,11 +4,13 @@ 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>
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.
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.
@@ -29,20 +31,87 @@ puter.events.onSchedule(options)
Give exactly one of `every`, `cron` or `at`.
- `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/).
| 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`. |
### Times
## 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
The `at`, `startAt` and `expiresAt` options each take one of these:
@@ -144,15 +213,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.
@@ -208,74 +277,11 @@ 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.
<strong class="example-title">Run a handler on weekday mornings in the user's time zone</strong>
### Run a handler on weekday mornings in the user's time zone
```js
// Deploy script, run as the app's developer
@@ -308,7 +314,7 @@ const schedule = await puter.events.onSchedule({
if (schedule.nextRunAt !== null) console.log(`next digest at ${new Date(schedule.nextRunAt).toString()}`);
```
<strong class="example-title">Run once, an hour from now</strong>
### Run once, an hour from now
```js
const reminder = await puter.events.onSchedule({
@@ -324,7 +330,7 @@ await puter.events.updateSchedule(reminder.scheduleId, { at: Date.now() + 2 * 60
await reminder.off();
```
<strong class="example-title">Run every 6 hours, on the hour, 28 times</strong>
### Run every 6 hours, on the hour, 28 times
```js
await puter.events.onSchedule({
+6 -2
View File
@@ -4,9 +4,11 @@ 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>
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 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/).
@@ -30,6 +32,8 @@ 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 }`:
@@ -45,7 +49,7 @@ It rejects with `{ message, code }`:
## Examples
<strong class="example-title">Cancel a notification, then read it</strong>
### Cancel a notification, then read it
```html;events-remove-schedule
<html>
+22 -20
View File
@@ -4,9 +4,11 @@ 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>
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.
[`onLocal()`](/Events/onLocal/) and [`onPersistent()`](/Events/onPersistent/) take the same subjects and deliver the same events.
## Syntax
@@ -149,30 +151,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/).
+6 -2
View File
@@ -4,9 +4,11 @@ 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>
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/).
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.
@@ -26,6 +28,8 @@ 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 }`:
@@ -41,7 +45,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Create a persistent subscription, then end it</strong>
### Create a persistent subscription, then end it
```html;events-unsubscribe
<html>
+6 -2
View File
@@ -4,9 +4,11 @@ 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>
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/).
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.
@@ -31,6 +33,8 @@ 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 |
@@ -47,7 +51,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Point a subscription at a new endpoint</strong>
### Point a subscription at a new endpoint
```html;events-update
<html>
+34 -7
View File
@@ -4,9 +4,11 @@ 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>
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.
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.
@@ -26,13 +28,36 @@ The `scheduleId` from [`onSchedule()`](/Events/onSchedule/), [`notify()`](/Notif
For a schedule from [`onSchedule()`](/Events/onSchedule/), pass new timing, a new `context`, or both:
- **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).
| 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.
For a stored notification, pass a new `sendAt`, new content, or both:
- `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.
| 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.
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.
@@ -40,6 +65,8 @@ 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 |
@@ -71,7 +98,7 @@ The promise rejects with `{ message, code }`:
## Examples
<strong class="example-title">Move a reminder to a later time</strong>
### Move a reminder to a later time
```html;events-update-reminder
<html>
@@ -103,7 +130,7 @@ The promise rejects with `{ message, code }`:
</html>
```
<strong class="example-title">Move a weekday schedule to another time</strong>
### Move a weekday schedule to another time
```html;events-update-cron
<html>
+19 -7
View File
@@ -4,9 +4,11 @@ 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>
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`.
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.
@@ -28,8 +30,12 @@ puter.events.workers.list()
puter.events.workers.list(options)
```
- `options.limit` (Number): Apps per page.
- `options.cursor` (String): The `cursor` from a previous page. Leave it off to start from the first page.
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. |
Resolves to `{ items, cursor, deployable }`:
@@ -44,7 +50,13 @@ puter.events.workers.destroy(appUid)
puter.events.workers.destroy(appUid, options)
```
- `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.
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.
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.
@@ -66,9 +78,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. |
## Example
## Examples
<strong class="example-title">List your events workers, and destroy one you no longer need</strong>
### List your events workers, and destroy one you no longer need
This runs in Node.js signed in with your account token.
@@ -83,7 +95,7 @@ const destroyed = await puter.events.workers.destroy(appUid); // an app you ow
console.log(`removed ${destroyed.removed}, suspended ${destroyed.suspended}`);
```
<strong class="example-title">Remove the signed-in user's scope of your app</strong>
### Remove the signed-in user's scope of your app
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.
+8 -8
View File
@@ -298,15 +298,14 @@ 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.mkdir()`](/FS/mkdir/)** - Create a directory
- **[`puter.fs.readdir()`](/FS/readdir/)** - List contents of a directory
- **[`puter.fs.rename()`](/FS/rename/)** - Rename 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.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.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.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
@@ -315,6 +314,7 @@ 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
+13 -7
View File
@@ -30,19 +30,25 @@ 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:
- `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`.
| 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`. |
## Return value
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.
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.
## Examples
<strong class="example-title"> Copy a file</strong>
### Copy a file
```html;fs-copy
<html>
+7 -5
View File
@@ -25,9 +25,11 @@ 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:
- `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`.
| 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`. |
## Return value
@@ -39,7 +41,7 @@ as deleting it here, and restoring it does not bring the shares back.
## Examples
<strong class="example-title">Delete a file</strong>
### Delete a file
```html;fs-delete
<html>
@@ -61,7 +63,7 @@ as deleting it here, and restoring it does not bring the shares back.
</html>
```
<strong class="example-title">Delete a directory</strong>
### Delete a directory
```html;fs-delete-directory
<html>
+6 -2
View File
@@ -4,7 +4,9 @@ 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
@@ -27,7 +29,9 @@ 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.
## Example
## Examples
### Get a read URL for a file
```javascript
const url = await puter.fs.getReadURL("~/myfile.txt");
+15 -11
View File
@@ -4,7 +4,9 @@ description: Build a link that opens a file in an app on Puter, for the people t
platforms: [websites, apps, nodejs, workers]
---
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.
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.
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.
@@ -30,9 +32,11 @@ The name of the app the link opens the file with. Defaults to the app the code i
An object with the following properties:
- `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.
| 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`. |
## Return value
@@ -52,9 +56,14 @@ 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
<strong class="example-title">Open a shared file in an app</strong>
### Open a shared file in an app
```html;fs-getShareLink
<html>
@@ -74,15 +83,10 @@ The app opens on the recipient's Puter, and before it is handed the file Puter s
</html>
```
<strong class="example-title">Send a collaborator straight into your app</strong>
### Send a collaborator straight into your app
```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
+13 -9
View File
@@ -35,8 +35,10 @@ The path to the file or directory. If `path` is not absolute, it will be resolve
An object with the following properties:
- `path` (String) - The item. Required when passing options as the only argument.
- `uid` (String) - The item, by UID. Can be used instead of `path`.
| 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`. |
## Return value
@@ -56,11 +58,18 @@ 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
<strong class="example-title">See who can reach a file</strong>
### See who can reach a file
```html;fs-getShares
<html>
@@ -81,7 +90,7 @@ If you cannot see the item at all, this rejects the same way a missing file woul
</html>
```
<strong class="example-title">Withdraw everyone's access</strong>
### Withdraw everyone's access
```js
const shares = await puter.fs.getShares('report.txt');
@@ -89,8 +98,3 @@ 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
+13 -11
View File
@@ -29,9 +29,11 @@ puter.fs.listShared(options)
An object with the following properties:
- `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`.
| 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`. |
## Return value
@@ -45,9 +47,14 @@ 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
<strong class="example-title">List everything shared with you</strong>
### List everything shared with you
```html;fs-listShared
<html>
@@ -66,7 +73,7 @@ Items shared with you appear at a **masked path**, `/<owner>/<uid>/<name>`, wher
</html>
```
<strong class="example-title">Page through every share</strong>
### Page through every share
```js
let cursor;
@@ -78,7 +85,7 @@ do {
} while (cursor);
```
<strong class="example-title">Open a file someone shared with you</strong>
### Open a file someone shared with you
```js
const page = await puter.fs.listShared();
@@ -88,8 +95,3 @@ 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
+18 -14
View File
@@ -4,7 +4,9 @@ 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. [`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.
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.
> **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.
@@ -24,10 +26,12 @@ puter.fs.listSharedByMe(options)
An object with the following properties:
- `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.
| 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. |
## Return value
@@ -41,9 +45,15 @@ 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
<strong class="example-title">See everything you have shared</strong>
### See everything you have shared
```html
<html>
@@ -65,7 +75,7 @@ Items you own appear at their real path. An item you shared as a delegate (from
</html>
```
<strong class="example-title">Page through every share you made</strong>
### Page through every share you made
```js
let cursor;
@@ -77,7 +87,7 @@ do {
} while (cursor);
```
<strong class="example-title">Withdraw everything shared on one item</strong>
### Withdraw everything shared on one item
```js
const page = await puter.fs.listSharedByMe();
@@ -86,9 +96,3 @@ 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
+9 -7
View File
@@ -25,10 +25,12 @@ 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:
- `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`.
| 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`. |
## Return value
@@ -36,7 +38,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
## Examples
<strong class="example-title">Create a new directory</strong>
### Create a new directory
```html;fs-mkdir
<html>
@@ -55,7 +57,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a directory with duplicate name handling</strong>
### Create a directory with duplicate name handling
```html;fs-mkdir-dedupe
<html>
@@ -75,7 +77,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a new directory with missing parent directories</strong>
### Create a new directory with missing parent directories
```html;fs-mkdir-create-missing-parents
<html>
+15 -9
View File
@@ -32,20 +32,26 @@ 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:
- `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`.
| 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`. |
## Return value
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.
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.
## Examples
<strong class="example-title">Move a file</strong>
### Move a file
```html;fs-move
<html>
@@ -76,7 +82,7 @@ A `Promise` that will resolve to the [`FSItem`](/Objects/fsitem) object of the m
</html>
```
<strong class="example-title">Move a file and create missing parent directories</strong>
### Move a file and create missing parent directories
```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:
- `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.
| 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. |
## Return value
@@ -37,7 +37,7 @@ A `Promise` that will resolve to a `Blob` object containing the contents of the
## Examples
<strong class="example-title">Read a file</strong>
### Read a file
```html;fs-read
<html>
+17 -13
View File
@@ -4,7 +4,9 @@ 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
@@ -25,17 +27,19 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
- `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`.
| 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. |
## Return value
@@ -63,7 +67,7 @@ for await (const page of puter.fs.readdir({ path: './large-dir', stream: true })
## Examples
<strong class="example-title">Read a directory</strong>
### Read a directory
```html;fs-readdir
<html>
+9 -5
View File
@@ -4,7 +4,9 @@ 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
@@ -28,9 +30,11 @@ The new name of the file or directory.
The options for the `rename` operation. The following options are supported:
- `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.
| 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`. |
## Return value
@@ -38,7 +42,7 @@ Returns a promise that resolves to the [`FSItem`](/Objects/fsitem) object of the
## Examples
<strong class="example-title">Rename a file</strong>
### Rename a file
```html;fs-rename
<html>
+5 -3
View File
@@ -4,7 +4,9 @@ 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
@@ -37,9 +39,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/). |
## Example
## Examples
<strong class="example-title">Revoke a read URL</strong>
### Revoke a read URL
```html
<html>
+49 -47
View File
@@ -54,11 +54,13 @@ How much access to grant. Defaults to `'read'`.
An object with the following properties:
- `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'`.
| 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`. |
## Return value
@@ -144,48 +146,6 @@ 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 —
@@ -236,3 +196,45 @@ 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
<strong class="example-title">Show how much storage the user has used</strong>
### Show how much storage the user has used
```html
<html>
+17 -15
View File
@@ -24,14 +24,16 @@ If `path` is not absolute, it will be resolved relative to the app's root direct
An object with the following properties:
- `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`.
| 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`. |
## Return value
@@ -41,9 +43,14 @@ 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
<strong class="example-title">Get information about a file</strong>
### Get information about a file
```html;fs-stat
<html>
@@ -67,7 +74,7 @@ With `returnShares: true`, the result also carries `shares` — an array of the
</html>
```
<strong class="example-title">See whether a file is shared, and with whom</strong>
### See whether a file is shared, and with whom
```html;fs-stat-shares
<html>
@@ -88,8 +95,3 @@ 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
+12 -10
View File
@@ -39,9 +39,11 @@ Pass **yourself** to leave a share someone else gave you. Pass `{ team: uid }` t
An object with the following properties:
- `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.
| 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`. |
## Return value
@@ -68,9 +70,14 @@ 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
<strong class="example-title">Stop sharing a file</strong>
### Stop sharing a file
```html;fs-unshare
<html>
@@ -89,14 +96,9 @@ Passing an email address that was **invited** but has not yet joined cancels the
</html>
```
<strong class="example-title">Leave a share someone gave you</strong>
### Leave a share someone gave you
```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
+16 -13
View File
@@ -28,19 +28,20 @@ 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:
- `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.
| 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. |
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.
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.
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.
@@ -59,6 +60,8 @@ 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.
@@ -85,7 +88,7 @@ When using signed uploads, a separate thumbnail transfer that fails or exceeds f
## Examples
<strong class="example-title">Upload a file from a file input</strong>
### Upload a file from a file input
```html;fs-upload
<html>
+12 -8
View File
@@ -4,7 +4,9 @@ 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
@@ -30,9 +32,11 @@ 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:
- `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`.
| 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`. |
#### `file` (File)
@@ -44,7 +48,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
## Examples
<strong class="example-title">Create a new file containing "Hello, world!"</strong>
### Create a new file containing "Hello, world!"
```html;fs-write
<html>
@@ -60,7 +64,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a new file with input coming from a file input</strong>
### Create a new file with input coming from a file input
```html;fs-write-from-input
<html>
@@ -81,7 +85,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a file with duplicate name handling</strong>
### Create a file with duplicate name handling
```html;fs-write-dedupe
<html>
@@ -101,7 +105,7 @@ Returns a `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of t
</html>
```
<strong class="example-title">Create a new file with missing parent directories</strong>
### Create a new file with missing parent directories
```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.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.update()`](/Hosting/update/)** - Update hosting settings
- **[`puter.hosting.delete()`](/Hosting/delete/)** - Delete a hosting deployment
- **[`puter.hosting.attach()`](/Hosting/attach/)** - Let the user connect their own domain to a website
## Examples
+6 -2
View File
@@ -4,7 +4,9 @@ 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.
@@ -32,6 +34,8 @@ 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.
@@ -40,7 +44,7 @@ The promise rejects with an error whose `code` is one of the following:
## Examples
<strong class="example-title">Connect a custom domain to a website</strong>
### Connect a custom domain to a website
```html;hosting-attach
<html>
+13 -5
View File
@@ -4,7 +4,9 @@ description: Create and host a website from a directory on Puter.
platforms: [websites, apps, nodejs, workers]
---
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.
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.
## Syntax
@@ -29,16 +31,22 @@ The directory must be one you own. Hosting serves everything under it publicly,
Alternative way to create hosting via options.
- `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.
| 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. |
## Return value
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.
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.
## Examples
<strong class="example-title">Create a simple website displaying "Hello world!"</strong>
### Create a simple website displaying "Hello world!"
```html;hosting-create
<html>
+9 -3
View File
@@ -4,7 +4,9 @@ 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
@@ -20,11 +22,15 @@ 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. 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.
## Errors
If a subdomain with the given name does not exist, the promise will be rejected with an error.
## Examples
<strong class="example-title">Create a random website then delete it</strong>
### Create a random website then delete it
```html;hosting-delete
<html>
+9 -3
View File
@@ -4,7 +4,9 @@ description: Get information on a subdomain hosted on Puter.
platforms: [websites, apps, nodejs, workers]
---
Returns a subdomain. If the subdomain does not exist, the promise will be rejected with an error.
Returns a subdomain.
If the subdomain does not exist, the promise will be rejected with an error.
## Syntax
@@ -17,11 +19,15 @@ puter.hosting.get(subdomain)
A string containing the name of the subdomain you want to retrieve.
## Return value
A `Promise` that will resolve to a [`Subdomain`](/Objects/subdomain/) object when the subdomain has been retrieved. If a subdomain with the given name 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 retrieved.
## Errors
If a subdomain with the given name does not exist, the promise will be rejected with an error.
## Examples
<strong class="example-title">Get a subdomain</strong>
### Get a subdomain
```html;hosting-get
<html>
+11 -7
View File
@@ -4,7 +4,9 @@ description: List all subdomains in your Puter account.
platforms: [websites, apps, nodejs, workers]
---
Returns an array of all subdomains in the user's subdomains that this app has access to. If the user has no subdomains, the array will be empty.
Returns an array of all subdomains in the user's subdomains that this app has access to.
If the user has no subdomains, the array will be empty.
## Syntax
```js
@@ -18,11 +20,13 @@ puter.hosting.list(options)
An object with the following optional properties:
- `limit` (Number): Maximum number of subdomains to return in a single call.
- `offset` (Number): Skips the given number of subdomains. Prefer `cursor` for paging through large lists.
- `cursor` (String | null): Opts into paginated results. Pass `null` for the first page, then the `cursor` from each page to fetch the next one.
- `includeTotal` (Boolean): If `true`, the paginated result includes a `total` count.
- `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`.
| Option | Type | Description |
|--------|------|-------------|
| `limit` | `Number` | Maximum number of subdomains 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. |
| `offset` | `Number` | Skips the given number of subdomains. Prefer `cursor` for paging through large lists. |
## Return value
A `Promise` that will resolve to an array of all [`Subdomain`](/Objects/subdomain/) objects belonging to the user that this app has access to.
@@ -49,7 +53,7 @@ Worker-backed subdomains are never included in the results — pages and `total`
## Examples
<strong class="example-title">Create 3 random websites and then list them</strong>
### Create 3 random websites and then list them
```html;hosting-list
<html>
+6 -2
View File
@@ -24,11 +24,15 @@ A string containing the path to the directory you want to serve.
## Return value
A `Promise` that will resolve to a [`Subdomain`](/Objects/subdomain/) object when the subdomain has been updated. If a subdomain with the given name does not exist, 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 updated.
## Errors
If a subdomain with the given name does not exist, the promise will be rejected with an error. If the path does not exist, the promise will be rejected with an error.
## Examples
<strong class="example-title">Update a subdomain to point to a new directory</strong>
### Update a subdomain to point to a new directory
```html;hosting-update
<html>
+3 -3
View File
@@ -215,15 +215,15 @@ These Key-Value Store features are supported out of the box when using Puter.js:
- **[`puter.kv.set()`](/KV/set/)** - Set a key-value pair
- **[`puter.kv.get()`](/KV/get/)** - Get a value by key
- **[`puter.kv.del()`](/KV/del/)** - Delete a key-value pair
- **[`puter.kv.list()`](/KV/list/)** - List keys in ascending or descending order
- **[`puter.kv.incr()`](/KV/incr/)** - Increment a numeric value
- **[`puter.kv.decr()`](/KV/decr/)** - Decrement a numeric value
- **[`puter.kv.update()`](/KV/update/)** - Update values by path
- **[`puter.kv.add()`](/KV/add/)** - Add values to an existing key
- **[`puter.kv.remove()`](/KV/remove/)** - Remove values by path
- **[`puter.kv.update()`](/KV/update/)** - Update values by path
- **[`puter.kv.del()`](/KV/del/)** - Delete a key-value pair
- **[`puter.kv.expire()`](/KV/expire/)** - Set key expiration in seconds
- **[`puter.kv.expireAt()`](/KV/expireAt/)** - Set key expiration timestamp
- **[`puter.kv.list()`](/KV/list/)** - List keys in ascending or descending order
- **[`puter.kv.flush()`](/KV/flush/)** - Clear all data
- **[`puter.kv.share()`](/KV/share/)** - Share the keys under a prefix with another user
- **[`puter.kv.unshare()`](/KV/unshare/)** - Stop a share, as its owner or its holder
+4 -2
View File
@@ -4,7 +4,9 @@ description: Returns the maximum key size (in bytes) for the key-value store.
platforms: [websites, apps, nodejs, workers]
---
The largest key the key-value store accepts, in bytes. It's `1024` (1 KB). A key is measured in UTF-8 bytes, so a key with non-ASCII characters fits fewer characters. Through a share's `handle`, a key can be at most 768 bytes.
The largest key the key-value store accepts, in bytes.
It's `1024` (1 KB). A key is measured in UTF-8 bytes, so a key with non-ASCII characters fits fewer characters. Through a share's `handle`, a key can be at most 768 bytes.
## Syntax
@@ -14,7 +16,7 @@ puter.kv.MAX_KEY_SIZE
## Examples
<strong class="example-title">Get the max key size</strong>
### Get the max key size
```html
<html>
+4 -2
View File
@@ -4,7 +4,9 @@ description: Returns the maximum value size (in bytes) for the key-value store.
platforms: [websites, apps, nodejs, workers]
---
The largest value the key-value store accepts, in bytes. It's `408576` (399 KB). A value is measured as the UTF-8 bytes of `JSON.stringify(value)`, so a string's quotes and escapes count.
The largest value the key-value store accepts, in bytes.
It's `408576` (399 KB). A value is measured as the UTF-8 bytes of `JSON.stringify(value)`, so a string's quotes and escapes count.
## Syntax
@@ -14,7 +16,7 @@ puter.kv.MAX_VALUE_SIZE
## Examples
<strong class="example-title">Get the max value size</strong>
### Get the max value size
```html
<html>
+9 -5
View File
@@ -4,7 +4,9 @@ description: Add values to an existing key or nested path in the user's own key-
platforms: [websites, apps, nodejs, workers]
---
Adds values to the list stored at a key. When you pass an array, its elements are appended to that list. When you pass an object, each of its keys is a path, and its value is added to the list at that path. A missing or expired key starts from an empty list, or for a path map, an object holding an empty list at each path.
Adds values to the list stored at a key.
When you pass an array, its elements are appended to that list. When you pass an object, each of its keys is a path, and its value is added to the list at that path. A missing or expired key starts from an empty list, or for a path map, an object holding an empty list at each path.
## Syntax
@@ -42,8 +44,10 @@ A plain object is read as a path map, never appended as an element. To append an
The last argument. It takes these properties:
- `handle` (String): Works on data another user shared with you, using the `handle` from [`puter.kv.listShared()`](/KV/listShared/). The key is then relative to the shared prefix, and the share needs `write` access. See [Sharing with other users](/KV/#sharing-with-other-users).
- `appUuid` (String): Works on another app's data, which the user let your app reach with [`puter.perms.request('appData', …)`](/Perms/appData/). It can't be combined with `handle`.
| Option | Type | Description |
|--------|------|-------------|
| `handle` | `String` | Works on data another user shared with you, using the `handle` from [`puter.kv.listShared()`](/KV/listShared/). The key is then relative to the shared prefix, and the share needs `write` access. See [Sharing with other users](/KV/#sharing-with-other-users). |
| `appUuid` | `String` | Works on another app's data, which the user let your app reach with [`puter.perms.request('appData', …)`](/Perms/appData/). It can't be combined with `handle`. |
Pass `optConfig` after `value`, as in `puter.kv.add('tags', ['new'], { handle })`. An object in the place of `value` is read as a path map.
@@ -77,7 +81,7 @@ A rejection carries an `Error` with a stable `code`:
## Examples
<strong class="example-title">Append to an array stored at a key</strong>
### Append to an array stored at a key
```html;kv-add-array
<html>
@@ -100,7 +104,7 @@ A rejection carries an `Error` with a stable `code`:
</html>
```
<strong class="example-title">Add values to an array inside an object</strong>
### Add values to an array inside an object
```html;kv-add
<html>
+9 -5
View File
@@ -4,7 +4,9 @@ description: Decrement numeric values in the user's own key-value store by a spe
platforms: [websites, apps, nodejs, workers]
---
Decrements the value of a key. A missing or expired key starts from 0 and loses any TTL it had, and a live key keeps its TTL. The call rejects if the target holds anything other than a number, including a numeric string. The target is the whole value, or with a path map, the field at each path.
Decrements the value of a key.
A missing or expired key starts from 0 and loses any TTL it had, and a live key keeps its TTL. The call rejects if the target holds anything other than a number, including a numeric string. The target is the whole value, or with a path map, the field at each path.
## Syntax
@@ -37,8 +39,10 @@ Paths support dot notation, array indexes at any level (`[0]`, `items[0]`, or `s
The last argument. It takes these properties:
- `handle` (String): Works on data another user shared with you, using the `handle` from [`puter.kv.listShared()`](/KV/listShared/). The key is then relative to the shared prefix, and the share needs `write` access. See [Sharing with other users](/KV/#sharing-with-other-users).
- `appUuid` (String): Works on another app's data, which the user let your app reach with [`puter.perms.request('appData', …)`](/Perms/appData/). It can't be combined with `handle`.
| Option | Type | Description |
|--------|------|-------------|
| `handle` | `String` | Works on data another user shared with you, using the `handle` from [`puter.kv.listShared()`](/KV/listShared/). The key is then relative to the shared prefix, and the share needs `write` access. See [Sharing with other users](/KV/#sharing-with-other-users). |
| `appUuid` | `String` | Works on another app's data, which the user let your app reach with [`puter.perms.request('appData', …)`](/Perms/appData/). It can't be combined with `handle`. |
Pass `optConfig` after `amount`, as in `puter.kv.decr('stats', 1, { handle })`. An object in the place of `amount` is read as a path map.
@@ -72,7 +76,7 @@ A rejection carries an `Error` with a stable `code`:
## Examples
<strong class="example-title">Decrement the value of a key</strong>
### Decrement the value of a key
```html;kv-decr
<html>
@@ -87,7 +91,7 @@ A rejection carries an `Error` with a stable `code`:
</html>
```
<strong class="example-title">Decrement a property within an object value</strong>
### Decrement a property within an object value
```html;kv-decr-nested
<html>
Loaded 100 of 316 files, more files were not shown because too many files have changed in this diff. Show more