Compare commits

..
Author SHA1 Message Date
jelveh 6c2915c955 Merge remote-tracking branch 'origin/main' into feat/feedback-embed 2026-11-07 01:51:27 -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
jelveh 37e1bf35ca 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:05:24 -07:00
jelveh 52fb91e8e2 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.
2026-11-07 01:05:10 -07:00
jelveh 67621d996a 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.
2026-11-07 00:59:57 -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
275 changed files with 12435 additions and 5239 deletions

No files matched your search

+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
+61 -10
View File
@@ -14,11 +14,25 @@ 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
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
@@ -29,7 +43,7 @@ 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, the embed shows the recommended apps (`RecommendedAppsService`)
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.
@@ -58,11 +72,18 @@ and popups to escape the sandbox.
## Host integration
A first-party app that signs in with puter.js can place `<puter-user-menu>` from
the SDK in its header instead (see `src/puter-js/src/ui/components.md`). It opens
this embed with the signed-in user named and closes it when the app's sign-in
changes. The rest of this section is for a host that builds the iframe itself.
The iframe can be shown whether or not the user is signed in. Create it when
“More apps” is opened, and remove it on close so reopening loads current apps
and preferences. The host owns the modal and close control;
“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.
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
@@ -84,10 +105,14 @@ 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();
});
@@ -99,22 +124,48 @@ localization system.
</script>
```
## Implementation and checks
## Implementation
`createAppBrowser` in `src/gui/src/UI/Dashboard/AppBrowser.js` owns the shared UI
and data behavior; its `guestApps` option is the signed-out list. `TabApps.js`
injects desktop actions. `appsEmbed.js` supplies new-tab launching through
`launchAppInTab` (signed in) and `guestAppLaunchUrl` (signed out) in
`src/gui/src/helpers/appTabLaunch.js`, which build the same app URL as
`launch_app`, and loads only the embed entry, its SDK, and shared styles.
The normal GUI webpack build emits `bundle.min.js` and `apps-embed.min.js`.
`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 when the page is
signed in, framing it in a modal `<dialog>` that stays hidden until the embed
is ready. 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.
## 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
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
```
@@ -27,7 +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 } from './HomepageController.js';
import { embedFrameAncestors, embedHostOrigin } from './HomepageController.js';
// ── Test harness ────────────────────────────────────────────────────
//
@@ -550,3 +550,26 @@ describe('embedFrameAncestors', () => {
).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);
});
});
@@ -61,32 +61,34 @@ 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>`
* 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 the embedding page is named exactly, from the request's referrer. Only a
* single label under `<domain>` qualifies, and not one this server answers
* itself (the API, WebDAV, SDK and native-app hosts).
* 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'
| 'api_base_url'
| '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);
@@ -105,7 +107,16 @@ export function embedFrameAncestors(
!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'";
}
/**
@@ -157,12 +168,20 @@ export class HomepageController extends PuterController {
router.get('/', {}, (req, res) => sendShell(req, res));
router.get('/embed/apps', {}, async (req, res) => {
// SDK bootstrap parameters must not change this page's account or API origin.
// Checked on the raw URL; `req.query` drops pairs past the parser's limit.
/**
* 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('/embed/apps');
return;
res.redirect(path);
return false;
}
res.removeHeader('X-Frame-Options');
res.setHeader(
@@ -170,6 +189,11 @@ export class HomepageController extends PuterController {
`frame-ancestors ${embedFrameAncestors(this.config, req.get('referer'))}`,
);
res.setHeader('Cache-Control', 'no-store');
return true;
};
router.get('/embed/apps', {}, async (req, res) => {
if (!prepareEmbed(req, res, '/embed/apps')) return;
// Shown to visitors without a session; a signed-in embed fetches
// its own list, so a failure here only costs signed-out visitors.
const guestApps = await this.services.recommendedApps
@@ -178,6 +202,20 @@ export class HomepageController extends PuterController {
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'),
),
}),
);
});
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']);
+41 -1
View File
@@ -368,12 +368,52 @@ 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([
['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://editor.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/'],
@@ -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();
},
);
@@ -107,6 +107,31 @@ describe('app browser embed shell', () => {
});
});
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. */
const render = async (
service: PuterHomepageService,
@@ -171,15 +171,50 @@ export class PuterHomepageService extends PuterService {
renderAppBrowserEmbed({
guestApps = [],
}: { guestApps?: Array<Record<string, unknown>> } = {}): 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/'),
guestApps,
}).replace(/</g, '\\u003c');
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">
@@ -190,27 +225,27 @@ 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="${encode(this.#appBrowserEmbedScript())}"></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>`;
}
/**
* The embed's script is built beside the GUI bundle, so it is served from
* 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.
*/
#appBrowserEmbedScript(): string {
#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('apps-embed.min.js', bundle);
const script = new URL(name, bundle);
script.search = bundle.search;
return script.origin === base
? `${script.pathname}${script.search}`
@@ -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),
+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,
+3 -2
View File
@@ -1102,8 +1102,9 @@ interface IConfigOptional {
/** Force the bundled GUI even in dev. Default: false. */
use_bundled_gui: boolean;
/**
* Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. The app
* browser embed loads `apps-embed.min.js` from the same directory.
* 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`. */
+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.convo()`](/AI/convo/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
- **[Realtime WebSocket API](/AI/realtime/)** - 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).
+24 -16
View File
@@ -4,7 +4,9 @@ description: Prepare an OpenAI realtime conversation with optional audio and tex
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.
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.
@@ -21,15 +23,17 @@ await conversation.connect();
## Parameters
#### `options` (Object) (Optional)
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. |
| 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
@@ -64,6 +68,14 @@ The conversation makes up to ten attempts over about a minute. In a browser that
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.
@@ -97,16 +109,10 @@ The optional microphone and speaker helpers require a browser with Web Audio sup
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
### Have a text conversation
A text conversation uses convenience methods for input and streamed output.
```js
@@ -123,6 +129,8 @@ await conversation.connect();
conversation.sendText('Say hello in three words.');
```
### Have a voice conversation
A voice conversation enables the microphone and speaker after connection.
```js
+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>
+3 -1
View File
@@ -4,7 +4,9 @@ description: Connect to OpenAI realtime conversations through Puter without pute
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.
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.
+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.
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>
+8 -4
View File
@@ -4,7 +4,9 @@ description: Remove keys from the user's own key-value store.
platforms: [websites, apps, nodejs, workers]
---
Removes a key from the user's key-value store. Deleting a key that doesn't exist does nothing and resolves the same way.
Removes a key from the user's key-value store.
Deleting a key that doesn't exist does nothing and resolves the same way.
## Syntax
@@ -25,8 +27,10 @@ The key to remove.
The last argument. It takes these properties:
- `handle` (String): Deletes from 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. A key the owner's app keeps private reads as missing through the share, so deleting it resolves to `true` and leaves it in place. See [Sharing with other users](/KV/#sharing-with-other-users).
- `appUuid` (String): Deletes from 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` | Deletes from 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. A key the owner's app keeps private reads as missing through the share, so deleting it resolves to `true` and leaves it in place. See [Sharing with other users](/KV/#sharing-with-other-users). |
| `appUuid` | `String` | Deletes from 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`. |
## Return value
@@ -46,7 +50,7 @@ With `handle`, the promise can reject with these codes:
## Examples
<strong class="example-title">Delete the key 'name'</strong>
### Delete the key 'name'
```html;kv-del
<html>
+5 -3
View File
@@ -29,8 +29,10 @@ The number of seconds until the key is removed. A value of `0` or less expires t
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`. |
## Return value
@@ -56,7 +58,7 @@ To remove a key's TTL instead of setting one, use [`puter.kv.set()`](/KV/set/) o
## Examples
<strong class="example-title">Retrieve the value of a key after a 1-second expiration</strong>
### Retrieve the value of a key after a 1-second expiration
```html;kv-expire
<html>
+5 -3
View File
@@ -29,8 +29,10 @@ The Unix timestamp, in seconds, when the key is removed. Use seconds, not the mi
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`. |
## Return value
@@ -56,7 +58,7 @@ To remove a key's TTL instead of setting one, use [`puter.kv.set()`](/KV/set/) o
## Examples
<strong class="example-title">Retrieve the value of a key after it expires</strong>
### Retrieve the value of a key after it expires
```html;kv-expireAt
<html>
+5 -1
View File
@@ -4,7 +4,9 @@ description: Remove all key-value pairs from the user's own store for your app.
platforms: [websites, apps, nodejs, workers]
---
Removes every key-value pair from the user's key-value store for the current app. It's also available as `puter.kv.clear()`.
Removes every key-value pair from the user's key-value store for the current app.
It's also available as `puter.kv.clear()`.
## Syntax
@@ -31,6 +33,8 @@ Flushing works only on your app's own store. To clear a prefix someone shared wi
## Examples
### Remove every key
```html;kv-flush
<html>
<body>
Loaded 100 of 275 files, more files were not shown because too many files have changed in this diff. Show more