mirror of
https://github.com/HeyPuter/puter.git
synced 2026-08-24 23:17:23 +00:00
Sync Puter.js types and docs (#3194)
* AI chat types * ai voice types * update tts docs and jsdoc * stt types and docs * txt2img docs and types * txt2vid and img2txt * apps * signin * perms * fs * kv * hosting * workers * net * ui * jsdoc
This commit is contained in:
@@ -33,7 +33,7 @@ An object containing the following properties:
|
||||
- `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 specific model's temperature is used.
|
||||
- `tools` (Array) (Optional) - Function definitions the AI can call. See [Function Calling](#function-calling) for details.
|
||||
- `reasoning_effort` / `reasoning.effort` (String) (Optional) - Controls how much effort reasoning models spend thinking. Supported values: `none`, `minimal`, `low`, `medium`, `high`, and `xhigh`. Lower values give faster responses with less reasoning. OpenAI models only.
|
||||
- `text` / `text_verbosity` (String) (Optional) - Controls how long or short responses are. Supported values: `low`, `medium`, and `high`. Lower values give shorter responses. OpenAI models only.
|
||||
- `verbosity` / `text.verbosity` (String) (Optional) - Controls how long or short responses are. Supported values: `low`, `medium`, and `high`. Lower values give shorter responses. OpenAI models only.
|
||||
|
||||
#### `testMode` (Boolean) (Optional)
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ puter.ai.img2txt({ source: image, ...options })
|
||||
|
||||
#### `image` / `source` (String|File|Blob) (required)
|
||||
|
||||
A string containing the URL or Puter path, or a `File`/`Blob` object containing the source image or file. When calling with an options object, pass it as `{ source: ... }`.
|
||||
A string containing the URL or Puter path, or a `File`/`Blob` object containing the source image or file. When calling with an options object, pass it as `{ source: ... }`. Maximum input size at 10MB.
|
||||
|
||||
#### `testMode` (Boolean) (Optional)
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ Fine-tune how transcription runs.
|
||||
- `chunking_strategy` (String): Required for `gpt-4o-transcribe-diarize` inputs longer than 30 seconds (recommend `"auto"`).
|
||||
- `known_speaker_names` / `known_speaker_references` (Array): Optional diarization references encoded as data URLs.
|
||||
- `extra_body` (Object): Forwarded verbatim to the OpenAI API for experimental flags.
|
||||
- `stream` (Boolean): Reserved for future streaming support. Currently rejected when `true`.
|
||||
- `stream` (Boolean): Reserved for future streaming support. Streaming is not currently supported.
|
||||
- `test_mode` (Boolean): When `true`, returns a sample response without using credits. Defaults to `false`.
|
||||
|
||||
**xAI-specific options** (when `provider: 'xai'`):
|
||||
@@ -65,8 +65,8 @@ When `true`, skips the live API call and returns a static sample transcript so y
|
||||
|
||||
Returns a `Promise` that resolves to either:
|
||||
|
||||
- A string (when `response_format: "text"` or you pass a shorthand `source` with no options), or
|
||||
- An object of [`Speech2TxtResult`](/Objects/speech2txtresult) containing the transcription payload (including diarization segments, timestamps, etc., depending on the selected model and format).
|
||||
- A string (when `response_format: "text"`), or
|
||||
- An object of [`Speech2TxtResult`](/Objects/speech2txtresult) containing the transcription payload (including diarization segments, timestamps, etc., depending on the selected model and format). This is the default, including when you pass a bare `source` with no options.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -79,7 +79,7 @@ Returns a `Promise` that resolves to either:
|
||||
<script>
|
||||
(async () => {
|
||||
const transcript = await puter.ai.speech2txt('https://assets.puter.site/example.mp3');
|
||||
puter.print('Transcript:', transcript.text ?? transcript);
|
||||
puter.print('Transcript:', transcript.text);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -32,14 +32,7 @@ Common aliases are also accepted (e.g. `'eleven'`, `'google'`, `'grok'`).
|
||||
|
||||
## Return value
|
||||
|
||||
A `Promise` that resolves to an array of engine objects. Each object contains:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | `String` | Engine/model identifier |
|
||||
| `name` | `String` | Human-readable engine name |
|
||||
| `provider` | `String` | Provider this engine belongs to |
|
||||
| `pricing_per_million_chars` | `Number` | Cost per million characters (may be absent) |
|
||||
A `Promise` that resolves to an array of [`TTSEngine`](/Objects/ttsengine) objects.
|
||||
|
||||
Example response:
|
||||
|
||||
|
||||
@@ -26,19 +26,7 @@ When `options` is a plain string it is treated as an `engine` filter for the def
|
||||
|
||||
## Return value
|
||||
|
||||
A `Promise` that resolves to an array of voice objects. Each object contains:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | `String` | Voice identifier to pass to `txt2speech()` |
|
||||
| `name` | `String` | Human-readable voice name |
|
||||
| `provider` | `String` | Provider this voice belongs to |
|
||||
| `language` | `Object` | `{ name, code }` language info (may be absent) |
|
||||
| `description` | `String` | Short description of the voice (may be absent) |
|
||||
| `category` | `String` | Voice category, e.g. `'premade'` (may be absent) |
|
||||
| `labels` | `Object` | Provider-specific labels (may be absent) |
|
||||
| `supported_models` | `Array` | Model IDs this voice works with (may be absent) |
|
||||
| `supported_engines` | `Array` | Engine types this voice supports (may be absent) |
|
||||
A `Promise` that resolves to an array of [`TTSVoice`](/Objects/ttsvoice) objects.
|
||||
|
||||
Example response:
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ Available when `provider: 'xai'`:
|
||||
| `language` | `String` | BCP-47 language code. Defaults to `'en'`. Supports `'auto'` for auto-detection and 20+ languages |
|
||||
| `output_format` | `String` | Output codec. Available: `'mp3'` (default), `'wav'`, `'pcm'`, `'mulaw'`, `'alaw'` |
|
||||
|
||||
Text supports inline speech tags like `[pause]`, `[laugh]` and wrapping tags like `<whisper>text</whisper>` for expressive delivery. Maximum 15,000 characters per request.
|
||||
Text supports inline speech tags like `[pause]`, `[laugh]` and wrapping tags like `<whisper>text</whisper>` for expressive delivery.
|
||||
|
||||
For more details, see the [xAI TTS documentation](https://x.ai/news/grok-stt-and-tts-apis).
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ The name of the app to delete.
|
||||
|
||||
## Return value
|
||||
|
||||
A `Promise` that will resolve to an object `{ success: true }` indicating whether the deletion was successful.
|
||||
A `Promise` that will resolve to an object `{ success: true, uid: <app uid> }` indicating whether the deletion was successful, along with the `uid` of the deleted app.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -33,6 +33,16 @@ puter.auth.signIn(options)
|
||||
|
||||
A `Promise` that will resolve to a [`SignInResult`](/Objects/signinresult/) object when the user has signed in.
|
||||
|
||||
## Rejection
|
||||
|
||||
The promise will reject with an object containing an `error` code and a human-readable `msg` in the following cases:
|
||||
|
||||
- `popup_blocked`: The sign-in popup was blocked by the browser. This usually happens when `signIn()` is not called from a user action (such as a click event).
|
||||
|
||||
- `auth_window_closed`: The user closed the sign-in window (or cancelled the consent dialog) without completing the sign-in process.
|
||||
|
||||
The promise may also reject with the failure response returned by the authentication window itself.
|
||||
|
||||
## Example
|
||||
|
||||
```html;auth-sign-in
|
||||
|
||||
@@ -19,9 +19,9 @@ puter.fs.getReadURL(path, expiresIn)
|
||||
|
||||
The path to the file to read.
|
||||
|
||||
#### `expiresIn` (Number) (Optional)
|
||||
#### `expiresIn` (String | Number) (Optional)
|
||||
|
||||
The number of milliseconds until the URL expires. If not provided, the URL will expire in 24 hours.
|
||||
How long the URL stays valid, in [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken#usage) duration format: a string like `'24h'`, `'30d'`, or `'1h'` (units: `s`, `m`, `h`, `d`, `w`, `y`), or a number of seconds. If not provided, defaults to `'24h'`.
|
||||
|
||||
## Return value
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ 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 `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`.
|
||||
|
||||
## Return value
|
||||
|
||||
@@ -63,9 +63,9 @@ The API provides comprehensive hosting management features including creating, r
|
||||
let site_3 = puter.randName();
|
||||
|
||||
// (2) Create 3 empty websites with the subdomains we generated
|
||||
await puter.hosting.create(site_1);
|
||||
await puter.hosting.create(site_2);
|
||||
await puter.hosting.create(site_3);
|
||||
await puter.hosting.create(site_1, '.');
|
||||
await puter.hosting.create(site_2, '.');
|
||||
await puter.hosting.create(site_3, '.');
|
||||
|
||||
// (3) Get all subdomains
|
||||
let sites = await puter.hosting.list();
|
||||
@@ -97,11 +97,11 @@ The API provides comprehensive hosting management features including creating, r
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`);
|
||||
|
||||
// (2) Delete the website using delete()
|
||||
const site2 = await puter.hosting.delete(site.subdomain);
|
||||
await puter.hosting.delete(site.subdomain);
|
||||
puter.print('Website deleted<br>');
|
||||
|
||||
// (3) Try to retrieve the website (should fail)
|
||||
@@ -131,7 +131,7 @@ The API provides comprehensive hosting management features including creating, r
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site<br>`);
|
||||
|
||||
// (2) Create a random directory
|
||||
@@ -144,7 +144,7 @@ The API provides comprehensive hosting management features including creating, r
|
||||
puter.print(`Changed subdomain's root directory to "${dir.path}"<br>`);
|
||||
|
||||
// (4) Delete the app (cleanup)
|
||||
await puter.hosting.delete(updatedSite.subdomain)
|
||||
await puter.hosting.delete(subdomain)
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
@@ -165,7 +165,7 @@ The API provides comprehensive hosting management features including creating, r
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`);
|
||||
|
||||
// (2) Retrieve the website using get()
|
||||
|
||||
@@ -4,13 +4,12 @@ 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. Optionally, you can specify a path to a directory that will be served by the subdomain.
|
||||
Will create a new subdomain that will be served by the hosting service. You must specify a path to a directory that will be served by the subdomain.
|
||||
|
||||
## Syntax
|
||||
|
||||
```js
|
||||
puter.hosting.create(subdomain, dirPath)
|
||||
puter.hosting.create(subdomain)
|
||||
puter.hosting.create(options)
|
||||
```
|
||||
|
||||
@@ -20,16 +19,16 @@ puter.hosting.create(options)
|
||||
|
||||
A string containing the name of the subdomain you want to create.
|
||||
|
||||
#### `dirPath` (String) (optional)
|
||||
#### `dirPath` (String) (required)
|
||||
|
||||
A string containing the path to the directory you want to serve. If not specified, the subdomain will be created without a directory.
|
||||
A string containing the path to the directory you want to serve.
|
||||
|
||||
#### `options` (Object) (optional)
|
||||
|
||||
Alternative way to create hosting via options.
|
||||
|
||||
- `subdomain` (String) - Name of the subdomain you want to create.
|
||||
- `root_dir` (String) (optional) - Path to the directory you want to serve, similar to `dirPath`.
|
||||
- `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
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ A string containing the name of the subdomain you want to delete.
|
||||
|
||||
## Return value
|
||||
|
||||
A `Promise` that will resolve to `true` 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. If a subdomain with the given name does not exist, the promise will be rejected with an error.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -34,11 +34,11 @@ A `Promise` that will resolve to `true` when the subdomain has been deleted. If
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`);
|
||||
|
||||
// (2) Delete the website using delete()
|
||||
const site2 = await puter.hosting.delete(site.subdomain);
|
||||
await puter.hosting.delete(site.subdomain);
|
||||
puter.print('Website deleted<br>');
|
||||
|
||||
// (3) Try to retrieve the website (should fail)
|
||||
|
||||
@@ -31,7 +31,7 @@ A `Promise` that will resolve to a [`Subdomain`](/Objects/subdomain/) object whe
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`);
|
||||
|
||||
// (2) Retrieve the website using get()
|
||||
|
||||
@@ -33,9 +33,9 @@ A `Promise` that will resolve to an array of all [`Subdomain`](/Objects/subdomai
|
||||
let site_3 = puter.randName();
|
||||
|
||||
// (2) Create 3 empty websites with the subdomains we generated
|
||||
await puter.hosting.create(site_1);
|
||||
await puter.hosting.create(site_2);
|
||||
await puter.hosting.create(site_3);
|
||||
await puter.hosting.create(site_1, '.');
|
||||
await puter.hosting.create(site_2, '.');
|
||||
await puter.hosting.create(site_3, '.');
|
||||
|
||||
// (3) Get all subdomains
|
||||
let sites = await puter.hosting.list();
|
||||
|
||||
@@ -4,13 +4,12 @@ description: Update a subdomain to point to a new directory.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
Updates a subdomain to point to a new directory. If directory is not specified, the subdomain will be disconnected from its directory.
|
||||
Updates a subdomain to point to a new directory.
|
||||
|
||||
## Syntax
|
||||
|
||||
```js
|
||||
puter.hosting.update(subdomain, dirPath)
|
||||
puter.hosting.update(subdomain)
|
||||
```
|
||||
|
||||
## Parameters
|
||||
@@ -19,9 +18,9 @@ puter.hosting.update(subdomain)
|
||||
|
||||
A string containing the name of the subdomain you want to update.
|
||||
|
||||
#### `dirPath` (String) (optional)
|
||||
#### `dirPath` (String) (required)
|
||||
|
||||
A string containing the path to the directory you want to serve. If not specified, the subdomain will be disconnected from its directory.
|
||||
A string containing the path to the directory you want to serve.
|
||||
|
||||
## Return value
|
||||
|
||||
@@ -39,7 +38,7 @@ A `Promise` that will resolve to a [`Subdomain`](/Objects/subdomain/) object whe
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site<br>`);
|
||||
|
||||
// (2) Create a random directory
|
||||
@@ -52,7 +51,7 @@ A `Promise` that will resolve to a [`Subdomain`](/Objects/subdomain/) object whe
|
||||
puter.print(`Changed subdomain's root directory to "${dir.path}"<br>`);
|
||||
|
||||
// (4) Delete the app (cleanup)
|
||||
await puter.hosting.delete(updatedSite.subdomain)
|
||||
await puter.hosting.delete(subdomain)
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -21,7 +21,7 @@ The key to add values to.
|
||||
|
||||
#### `value` (String | Number | Boolean | Object | Array) (optional)
|
||||
|
||||
The value to add to the key.
|
||||
The value to add to the key. Defaults to `1` when omitted.
|
||||
|
||||
#### `pathAndValue` (Object) (optional)
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ puter.kv.flush()
|
||||
None
|
||||
|
||||
## Return value
|
||||
A `Promise` that will resolve to `true` when the key-value store has been flushed (emptied). The promise will never reject.
|
||||
A `Promise` that will resolve to `true` when the key-value store has been flushed (emptied), or reject with an error on failure.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ description: Get the value stored in a key from key-value store.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
When passed a key, will return that key's value, or `null` if the key does not exist.
|
||||
When passed a key, will return that key's value, or `undefined` if the key does not exist.
|
||||
|
||||
## Syntax
|
||||
```js
|
||||
@@ -16,7 +16,7 @@ puter.kv.get(key)
|
||||
A string containing the name of the key you want to retrieve the value of.
|
||||
|
||||
## Return value
|
||||
A `Promise` that will resolve to the key's value. If the key does not exist, it will resolve to `null`.
|
||||
A `Promise` that will resolve to the key's value. If the key does not exist, it will resolve to `undefined`.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ When passed a key and a value, will add it to the user's key-value store, or upd
|
||||
```js
|
||||
puter.kv.set(key, value)
|
||||
puter.kv.set(key, value, expireAt)
|
||||
puter.kv.set({ key, value, expireAt })
|
||||
puter.kv.set([ { key, value, expireAt }, ... ])
|
||||
puter.kv.set({ items: [ { key, value, expireAt }, ... ] })
|
||||
```
|
||||
|
||||
## Parameters
|
||||
@@ -29,6 +32,12 @@ A string containing the value you want to give the key you are creating/updating
|
||||
|
||||
A number containing when the key should expire in timestamp seconds.
|
||||
|
||||
#### `items` (Array) (batch only)
|
||||
|
||||
An array of `{ key, value, expireAt? }` objects, set in a single request. Each `key` is required and follows the same **1 KB** key / **400 KB** value limits. You can pass the array directly (`set([...])`) or wrapped in an object (`set({ items: [...] })`).
|
||||
|
||||
You may also pass a single object instead of positional arguments: `set({ key, value, expireAt })`.
|
||||
|
||||
## Return value
|
||||
|
||||
A `Promise` that will resolves to `true` when the key-value pair has been created or the existing key's value has been updated.
|
||||
@@ -49,3 +58,22 @@ A `Promise` that will resolves to `true` when the key-value pair has been create
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
<strong class="example-title">Set multiple key-value pairs at once</strong>
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
await puter.kv.set([
|
||||
{ key: 'name', value: 'Puter Smith' },
|
||||
{ key: 'age', value: 21 },
|
||||
]);
|
||||
puter.print('Batch set complete');
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
@@ -10,7 +10,8 @@ Update one or more paths within the value stored at a key. You can update nested
|
||||
|
||||
```js
|
||||
puter.kv.update(key, pathAndValueMap)
|
||||
puter.kv.update(key, pathAndValueMap, ttlSeconds)
|
||||
puter.kv.update(key, pathAndValueMap, ttl)
|
||||
puter.kv.update({ key, pathAndValueMap, ttl })
|
||||
```
|
||||
|
||||
## Parameters
|
||||
@@ -23,7 +24,7 @@ The key to update.
|
||||
|
||||
An object where each key is a dot-separated path (for example, `"profile.name"`) and each value is the new value for that path.
|
||||
|
||||
#### `ttlSeconds` (Number) (optional)
|
||||
#### `ttl` (Number) (optional)
|
||||
|
||||
Time-to-live for the key, in seconds.
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ Fired when the socket encounters an error. The close event is fired shortly afte
|
||||
##### Parameters
|
||||
|
||||
- `callback` (Function) The callback to fire when an error occurs.
|
||||
- `reason` (`string`) A user readable error reason.
|
||||
- `error` (`Error`) An `Error` object describing what went wrong. The human-readable reason is available on `error.message`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -103,8 +103,8 @@ Fired when the socket encounters an error. The close event is fired shortly afte
|
||||
socket.on("data", (data) => {
|
||||
puter.print(decoder.decode(data), { code: true });
|
||||
})
|
||||
socket.on("error", (reason) => {
|
||||
puter.print("Socket errored with the following reason: ", reason);
|
||||
socket.on("error", (error) => {
|
||||
puter.print("Socket errored with the following reason: ", error.message);
|
||||
})
|
||||
socket.on("close", (hadError)=> {
|
||||
puter.print("Socket closed. Was there an error? ", hadError);
|
||||
|
||||
@@ -84,7 +84,7 @@ Fired when the socket encounters an error. The close event is fired shortly afte
|
||||
##### Parameters
|
||||
|
||||
- `callback` (Function) The callback to fire when an error occurs.
|
||||
- `reason` (`string`) A user readable error reason.
|
||||
- `error` (`Error`) An `Error` object describing what went wrong. The human-readable reason is available on `error.message`.
|
||||
|
||||
The encryption is done by [rustls-wasm](https://github.com/MercuryWorkshop/rustls-wasm/).
|
||||
|
||||
@@ -105,8 +105,8 @@ The encryption is done by [rustls-wasm](https://github.com/MercuryWorkshop/rustl
|
||||
socket.on("tlsdata", (data) => {
|
||||
puter.print(decoder.decode(data), { code: true });
|
||||
})
|
||||
socket.on("error", (reason) => {
|
||||
puter.print("Socket errored with the following reason: ", reason);
|
||||
socket.on("error", (error) => {
|
||||
puter.print("Socket errored with the following reason: ", error.message);
|
||||
})
|
||||
socket.on("tlsclose", (hadError)=> {
|
||||
puter.print("Socket closed. Was there an error? ", hadError);
|
||||
|
||||
@@ -17,6 +17,8 @@ Various object types and classes that represent different entities in the Puter
|
||||
- **[MonthlyUsage](/Objects/monthlyusage/)** - Represents user's monthly resource usage information
|
||||
- **[Speech2TxtResult](/Objects/speech2txtresult/)** - Represents speech-to-text transcription results
|
||||
- **[Subdomain](/Objects/subdomain/)** - Represents a subdomain
|
||||
- **[TTSEngine](/Objects/ttsengine/)** - Represents an available text-to-speech engine/model
|
||||
- **[TTSVoice](/Objects/ttsvoice/)** - Represents an available text-to-speech voice
|
||||
- **[ToolCall](/Objects/toolcall/)** - Represents a tool invocation request
|
||||
- **[User](/Objects/user/)** - Represents a Puter user
|
||||
- **[WorkerDeployment](/Objects/workerdeployment/)** - Represents a worker deployment result
|
||||
|
||||
@@ -69,11 +69,12 @@ __Syntax__
|
||||
|
||||
```js
|
||||
app.users()
|
||||
app.users(pageSize)
|
||||
```
|
||||
|
||||
__Parameters__
|
||||
|
||||
None.
|
||||
- `pageSize` (Number) (optional): The number of users to retrieve per page. Default is 100.
|
||||
|
||||
__Return value__
|
||||
|
||||
|
||||
@@ -16,3 +16,9 @@ An object containing the chat message data.
|
||||
- `content` (String) - The content of the message.
|
||||
|
||||
- `tool_calls` (Array) - An optional array of [`ToolCall`](/Objects/toolcall) objects if the model wants to call tools.
|
||||
|
||||
- `tool_call_id` (String) - An optional identifier linking this message to the tool call it responds to.
|
||||
|
||||
- `cache_control` (Object) - An optional object controlling prompt caching for this message. Contains a `type` (String) property.
|
||||
|
||||
- `images` (Array) - An array of image content objects associated with the message. Each object contains a `type` (String) and an `image_url` object with a `url` (String) property.
|
||||
|
||||
@@ -5,8 +5,44 @@ description: The ChatResponseChunk object containing a chunk of streaming chat r
|
||||
|
||||
The `ChatResponseChunk` object containing a chunk of streaming chat response data.
|
||||
|
||||
Each chunk has a `type` indicating its kind. The other attributes that are present depend on that `type`.
|
||||
|
||||
## Attributes
|
||||
|
||||
#### `type` (String)
|
||||
|
||||
The kind of chunk. One of:
|
||||
|
||||
- `"text"` - A portion of the response text.
|
||||
- `"reasoning"` - A portion of the model's reasoning/thinking output.
|
||||
- `"tool_use"` - A tool/function the model wants to call.
|
||||
- `"extra_content"` - Provider-specific metadata.
|
||||
- `"usage"` - Token usage totals, emitted as the final chunk.
|
||||
|
||||
#### `text` (String)
|
||||
|
||||
A string containing a portion of the chat response text in streaming mode.
|
||||
A portion of the chat response text. Present on `text` chunks.
|
||||
|
||||
#### `reasoning` (String)
|
||||
|
||||
A portion of the model's reasoning output. Present on `reasoning` chunks.
|
||||
|
||||
#### `id` (String)
|
||||
|
||||
The unique identifier for the tool call. Present on `tool_use` chunks.
|
||||
|
||||
#### `name` (String)
|
||||
|
||||
The name of the function/tool to call. Present on `tool_use` chunks.
|
||||
|
||||
#### `input` (Object)
|
||||
|
||||
The parsed arguments for the tool call. Present on `tool_use` chunks.
|
||||
|
||||
#### `extra_content`
|
||||
|
||||
Provider-specific metadata attached to the stream.
|
||||
|
||||
#### `usage` (Object)
|
||||
|
||||
An object containing token usage totals. Present on the final `usage` chunk.
|
||||
|
||||
+220
-18
@@ -4,7 +4,7 @@ description: An FSItem object represents a file or a directory in the file syste
|
||||
---
|
||||
|
||||
|
||||
An `FSItem` object represents a file or a directory in the file system of a Puter.
|
||||
An `FSItem` object represents a file or a directory in the file system of a Puter.
|
||||
|
||||
## Attributes
|
||||
|
||||
@@ -12,10 +12,6 @@ An `FSItem` object represents a file or a directory in the file system of a Pute
|
||||
|
||||
A string containing the unique identifier of the item. This is a unique identifier generated by Puter when the item is created.
|
||||
|
||||
#### `uid` (String)
|
||||
|
||||
This is an alias for `id`.
|
||||
|
||||
#### `name` (String)
|
||||
|
||||
A string containing the name of the item.
|
||||
@@ -24,18 +20,10 @@ A string containing the name of the item.
|
||||
|
||||
A string containing the path of the item. This is the path of the item relative to the root directory of the file system.
|
||||
|
||||
#### `is_dir` (Boolean)
|
||||
#### `isDir` (Boolean)
|
||||
|
||||
A boolean value indicating whether the item is a directory. If this is set to `true`, the item is a directory. If this is set to `false`, the item is a file.
|
||||
|
||||
#### `parent_id` (String)
|
||||
|
||||
A string containing the unique identifier of the parent directory of the item.
|
||||
|
||||
#### `parent_uid` (String)
|
||||
|
||||
This is an alias for `parent_id`.
|
||||
|
||||
#### `created` (Integer)
|
||||
|
||||
An integer containing the Unix timestamp of the date and time when the item was created.
|
||||
@@ -48,13 +36,227 @@ An integer containing the Unix timestamp of the date and time when the item was
|
||||
|
||||
An integer containing the Unix timestamp of the date and time when the item was last accessed.
|
||||
|
||||
|
||||
#### `size` (Integer)
|
||||
|
||||
An integer containing the size of the item in bytes. If the item is a directory, this will be `null`.
|
||||
|
||||
## Methods
|
||||
|
||||
#### `writable` (Boolean)
|
||||
### `read()`
|
||||
|
||||
A boolean value indicating whether the item is writable. If this is set to `true`, the item is writable. If this is set to `false`, the item is not writable. If the item is a directory and `writable` is `false`, it means new items cannot be added to the directory;
|
||||
however, it is possible that subdirectories may be writable or contain writable files.
|
||||
Reads the contents of the file.
|
||||
|
||||
__Syntax__
|
||||
|
||||
```js
|
||||
fsitem.read()
|
||||
```
|
||||
|
||||
__Parameters__
|
||||
|
||||
None.
|
||||
|
||||
__Return value__
|
||||
|
||||
A `Promise` that resolves to a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) containing the contents of the file.
|
||||
|
||||
__Example__
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
await puter.fs.write('hello.txt', 'Hello, world!');
|
||||
const item = await puter.fs.stat('hello.txt');
|
||||
const blob = await item.read();
|
||||
puter.print(await blob.text());
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### `write()`
|
||||
|
||||
Writes data to the file, overwriting its existing contents.
|
||||
|
||||
__Syntax__
|
||||
|
||||
```js
|
||||
fsitem.write(data)
|
||||
```
|
||||
|
||||
__Parameters__
|
||||
|
||||
- `data` (String | File | Blob) (required): The data to write to the file.
|
||||
|
||||
__Return value__
|
||||
|
||||
A `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of the written file.
|
||||
|
||||
__Example__
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
await puter.fs.write('hello.txt', 'Hello, world!');
|
||||
const item = await puter.fs.stat('hello.txt');
|
||||
await item.write('Updated contents!');
|
||||
puter.print('File updated');
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### `rename()`
|
||||
|
||||
Renames the item.
|
||||
|
||||
__Syntax__
|
||||
|
||||
```js
|
||||
fsitem.rename(newName)
|
||||
```
|
||||
|
||||
__Parameters__
|
||||
|
||||
- `newName` (String) (required): The new name for the item.
|
||||
|
||||
__Return value__
|
||||
|
||||
A `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of the renamed item.
|
||||
|
||||
__Example__
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
await puter.fs.write('hello.txt', 'Hello, world!');
|
||||
const item = await puter.fs.stat('hello.txt');
|
||||
await item.rename('renamed.txt');
|
||||
puter.print('File renamed');
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### `delete()`
|
||||
|
||||
Deletes the item.
|
||||
|
||||
__Syntax__
|
||||
|
||||
```js
|
||||
fsitem.delete()
|
||||
```
|
||||
|
||||
__Parameters__
|
||||
|
||||
None.
|
||||
|
||||
__Return value__
|
||||
|
||||
A `Promise` that resolves once the item has been deleted.
|
||||
|
||||
__Example__
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
await puter.fs.write('hello.txt', 'Hello, world!');
|
||||
const item = await puter.fs.stat('hello.txt');
|
||||
await item.delete();
|
||||
puter.print('File deleted');
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### `mkdir()`
|
||||
|
||||
Creates a new subdirectory inside the item. The item must be a directory, otherwise an error is thrown.
|
||||
|
||||
__Syntax__
|
||||
|
||||
```js
|
||||
fsitem.mkdir(name)
|
||||
```
|
||||
|
||||
__Parameters__
|
||||
|
||||
- `name` (String) (required): The name of the subdirectory to create.
|
||||
|
||||
__Return value__
|
||||
|
||||
A `Promise` that resolves to the [`FSItem`](/Objects/fsitem) object of the created directory.
|
||||
|
||||
__Example__
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
const dirname = puter.randName();
|
||||
await puter.fs.mkdir(dirname);
|
||||
const dir = await puter.fs.stat(dirname);
|
||||
await dir.mkdir('subdir');
|
||||
puter.print(`Created subdir inside ${dirname}`);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### `readdir()`
|
||||
|
||||
Lists the contents of the item. The item must be a directory, otherwise an error is thrown.
|
||||
|
||||
__Syntax__
|
||||
|
||||
```js
|
||||
fsitem.readdir()
|
||||
```
|
||||
|
||||
__Parameters__
|
||||
|
||||
None.
|
||||
|
||||
__Return value__
|
||||
|
||||
A `Promise` that resolves to an array of [`FSItem`](/Objects/fsitem) objects, one for each item in the directory.
|
||||
|
||||
__Example__
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
const dirname = puter.randName();
|
||||
await puter.fs.mkdir(dirname);
|
||||
await puter.fs.write(dirname + '/hello.txt', 'Hello, world!');
|
||||
const dir = await puter.fs.stat(dirname);
|
||||
const children = await dir.readdir();
|
||||
children.forEach((child) => puter.print(child.name + '<br>'));
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
@@ -18,3 +18,16 @@ A string containing the detected or specified language of the audio.
|
||||
#### `segments` (Array)
|
||||
|
||||
An optional array of segment objects containing detailed transcription information.
|
||||
|
||||
#### `duration` (Number)
|
||||
|
||||
An optional duration of the audio in seconds. Provider-dependent (e.g. returned by xAI).
|
||||
|
||||
#### `words` (Array)
|
||||
|
||||
An optional array of per-word timestamp objects. Provider-dependent (e.g. returned by xAI). Each word has:
|
||||
|
||||
- `text` (String): The transcribed word.
|
||||
- `start` (Number): Start time of the word in seconds.
|
||||
- `end` (Number): End time of the word in seconds.
|
||||
- `speaker` (String): Detected speaker, present when `diarize: true`.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: TTSEngine
|
||||
description: The TTSEngine object describing an available text-to-speech engine/model.
|
||||
---
|
||||
|
||||
The `TTSEngine` object describes a text-to-speech engine/model available from a provider, including pricing metadata where available. Arrays of these objects are returned by [`puter.ai.txt2speech.listEngines()`](/AI/txt2speech.listEngines).
|
||||
|
||||
## Attributes
|
||||
|
||||
#### `id` (String)
|
||||
|
||||
The engine/model identifier.
|
||||
|
||||
#### `name` (String)
|
||||
|
||||
A human-readable engine name.
|
||||
|
||||
#### `provider` (String)
|
||||
|
||||
The provider this engine belongs to, e.g. `'aws-polly'`, `'openai'`, `'elevenlabs'`, `'gemini'`, `'xai'`.
|
||||
|
||||
#### `pricing_per_million_chars` (Number)
|
||||
|
||||
An optional cost per million characters. May be absent when the provider does not expose pricing.
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
title: TTSVoice
|
||||
description: The TTSVoice object describing an available text-to-speech voice.
|
||||
---
|
||||
|
||||
The `TTSVoice` object describes a text-to-speech voice available from a provider, including metadata such as language, category, and supported models/engines. Arrays of these objects are returned by [`puter.ai.txt2speech.listVoices()`](/AI/txt2speech.listVoices).
|
||||
|
||||
## Attributes
|
||||
|
||||
#### `id` (String)
|
||||
|
||||
The voice identifier to pass to [`puter.ai.txt2speech()`](/AI/txt2speech).
|
||||
|
||||
#### `name` (String)
|
||||
|
||||
A human-readable voice name.
|
||||
|
||||
#### `provider` (String)
|
||||
|
||||
The provider this voice belongs to, e.g. `'aws-polly'`, `'openai'`, `'elevenlabs'`, `'gemini'`, `'xai'`.
|
||||
|
||||
#### `language` (Object)
|
||||
|
||||
An optional object describing the voice's language. Contains a `name` (String) and a `code` (String) property. May be absent.
|
||||
|
||||
#### `description` (String)
|
||||
|
||||
An optional short description of the voice. May be absent.
|
||||
|
||||
#### `category` (String)
|
||||
|
||||
An optional voice category, e.g. `'premade'`. May be absent.
|
||||
|
||||
#### `labels` (Object)
|
||||
|
||||
An optional object of provider-specific labels. May be absent.
|
||||
|
||||
#### `supported_models` (Array)
|
||||
|
||||
An optional array of model IDs (Strings) this voice works with. May be absent.
|
||||
|
||||
#### `supported_engines` (Array)
|
||||
|
||||
An optional array of engine types (Strings) this voice supports. May be absent.
|
||||
@@ -27,6 +27,8 @@ An array of objects that define the buttons to be displayed in the alert dialog.
|
||||
A set of key/value pairs that configure the alert dialog.
|
||||
|
||||
* `type` (String): Visual style of the alert dialog. One of `primary`, `success`, `info`, `warning`, or `danger`.
|
||||
* `body_icon` (String): Icon URL shown in the dialog body. Takes precedence over `icon`.
|
||||
* `icon` (String): Icon URL shown in the dialog body, used when `body_icon` is not set.
|
||||
|
||||
|
||||
## Return value
|
||||
|
||||
@@ -27,6 +27,9 @@ A set of key/value pairs that configure the window.
|
||||
* `title` (String): title of the window.
|
||||
* `width` (Float): width of window in pixels.
|
||||
|
||||
## Return value
|
||||
A `Promise` that resolves to a window handle object with an `id` (String) property identifying the created window. This `id` can be passed as the `window_id` argument to the `setWindow*` methods.
|
||||
|
||||
## Examples
|
||||
```html
|
||||
<html>
|
||||
|
||||
@@ -29,6 +29,15 @@ Name of the app. If not provided, a new instance of the current app will be laun
|
||||
#### `options.args` (Object)
|
||||
Arguments to pass to the app.
|
||||
|
||||
#### `options.file_paths` (Array<String>)
|
||||
Paths of existing files to open with the launched app.
|
||||
|
||||
#### `options.items` (Array<[`FSItem`](/Objects/fsitem)>)
|
||||
`FSItem` objects to open with the launched app.
|
||||
|
||||
#### `options.pseudonym` (String)
|
||||
A pseudonym to launch the app under.
|
||||
|
||||
## Return value
|
||||
A `Promise` that will resolve to an [`AppConnection`](/Objects/AppConnection) once the app is launched.
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ An object that configures the notification.
|
||||
- `title` (string): Title shown in the notification.
|
||||
- `text` (string): Body text shown under the title.
|
||||
- `icon` (string): Icon URL or Puter icon name (for example `bell.svg`).
|
||||
- `type` (string): Visual style used to pick a default icon and accent color when no `icon` is provided. One of `info`, `success`, `warning`, `error`, or `default`.
|
||||
- `duration` (number): Time in milliseconds before the notification auto-dismisses. Defaults to `5000`; set to `0` to keep it until dismissed.
|
||||
- `round_icon` (boolean): If `true`, renders the icon as a circle. `roundIcon` is accepted as an alias.
|
||||
- `uid` (string): Optional ID to associate with the notification.
|
||||
- `value` (any): Optional value stored on the notification element.
|
||||
|
||||
@@ -45,6 +45,16 @@ Sent on app startup, and whenever the user's desktop theme on Puter is changed.
|
||||
}
|
||||
```
|
||||
|
||||
#### `connection`
|
||||
Sent when another app requests a connection to your app. The value passed to `handler` is:
|
||||
```js
|
||||
{
|
||||
conn, // (AppConnection) Connection to the app that initiated the request
|
||||
accept, // (Function) Call accept(value) to accept the connection; `value` is sent back to the requester
|
||||
reject, // (Function) Call reject(value) to reject the connection; `value` is sent back to the requester
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```html
|
||||
|
||||
@@ -6,6 +6,8 @@ platforms: [apps]
|
||||
|
||||
Specify a function to execute when the one or more items have been opened. Items can be opened via a variety of methods such as: drag and dropping onto the app, double-clicking on an item, right-clicking on an item and choosing an app from the 'Open With...' submenu.
|
||||
|
||||
**Deprecated** This handler also fires when items are dropped onto the app. New code should handle the `drop` event for drag-and-drop instead.
|
||||
|
||||
**Note** `onItemsOpened` is not called when items are opened using `showOpenFilePicker()`.
|
||||
|
||||
## Syntax
|
||||
|
||||
@@ -23,7 +23,7 @@ A string to be displayed as a placeholder in the input field. If not set, the in
|
||||
|
||||
|
||||
## Return value
|
||||
A `Promise` that resolves to the value of the input field when the user presses the OK button. If the user presses the Cancel button, the promise will resolve to `null`.
|
||||
A `Promise` that resolves to the value of the input field when the user presses the OK button. If the user presses the Cancel button, the promise will resolve to `false`.
|
||||
|
||||
## Examples
|
||||
```html;ui-prompt
|
||||
|
||||
@@ -11,18 +11,26 @@ Presents the user with a file picker dialog allowing them to specify where and w
|
||||
```js
|
||||
puter.ui.showSaveFilePicker()
|
||||
puter.ui.showSaveFilePicker(content, suggestedName)
|
||||
puter.ui.showSaveFilePicker(content, suggestedName, type)
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
#### `content` (String) (Optional)
|
||||
#### `content` (Optional)
|
||||
|
||||
The data to write to the chosen file.
|
||||
The data to write to the chosen file. The expected value depends on `type`:
|
||||
- When `type` is omitted, `content` is the file data to write.
|
||||
- When `type` is `'url'`, `content` is a URL (string or `URL`) whose contents are saved.
|
||||
- When `type` is `'move'` or `'copy'`, `content` is the source path of an existing file to move or copy.
|
||||
|
||||
#### `suggestedName` (String) (Optional)
|
||||
|
||||
The default file name to pre-fill in the dialog.
|
||||
|
||||
#### `type` (String) (Optional)
|
||||
|
||||
How `content` should be interpreted. One of `'url'`, `'move'`, or `'copy'`. If omitted and `content` is a `URL` object, it is auto-detected as `'url'`.
|
||||
|
||||
## Return value
|
||||
|
||||
A `Promise` that resolves to an [`FSItem`](/Objects/fsitem) describing the saved file. If the user cancels, the promise stays pending.
|
||||
|
||||
@@ -14,17 +14,27 @@ A worker is tied to its **name**: you create it **once** and keep that name. To
|
||||
|
||||
```js
|
||||
puter.workers.create(workerName, filePath)
|
||||
puter.workers.create(workerName, filePath, appName)
|
||||
puter.workers.create(workerName, filePath, options)
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
<div class="info">Workers cannot be larger than <strong>10MB</strong>.</div>
|
||||
|
||||
#### `workerName` (String)(Required)
|
||||
The name for the worker. It can contain letters, numbers, hyphens, and underscores.
|
||||
|
||||
#### `filePath` (String)(Required)
|
||||
The path to a JavaScript file in your Puter account that contains your [router](../router) code.
|
||||
|
||||
<div class="info">Workers cannot be larger than <strong>10MB</strong>.</div>
|
||||
#### `appName` (String)(Optional)
|
||||
The name of an existing app in your account to associate the worker with. When provided, the worker is bound to that app and no sandbox app is created.
|
||||
|
||||
#### `options` (Object)(Optional)
|
||||
An alternative to `appName` for controlling the worker's sandbox.
|
||||
|
||||
- `sandbox` (Boolean)(Optional) - Whether to run the worker inside an isolated sandbox app. Defaults to `true`. When omitted (or `true`) and you are authenticated with a user token, a dedicated `sandbox-<workerName>` app is created (or reused) to own the worker. Pass `false` to opt out.
|
||||
|
||||
## Return Value
|
||||
|
||||
|
||||
@@ -18,9 +18,9 @@ puter.workers.exec(workerURL, options)
|
||||
|
||||
## Parameters
|
||||
|
||||
#### `workerURL` (String)(Required)
|
||||
#### `workerURL` (String | URL | Request)(Required)
|
||||
|
||||
The URL of the worker to execute.
|
||||
The worker to execute. Accepts the same input as the Fetch API's first argument: a URL string, a [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) object, or a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. When a `Request` object is provided, its options (method, headers, body, etc.) are used and the `options` argument can be omitted.
|
||||
|
||||
#### `options` (Object)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<script>
|
||||
(async () => {
|
||||
const transcript = await puter.ai.speech2txt('https://assets.puter.site/example.mp3');
|
||||
puter.print('Transcript:', transcript.text ?? transcript);
|
||||
puter.print('Transcript:', transcript.text);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`);
|
||||
|
||||
// (2) Delete the website using delete()
|
||||
const site2 = await puter.hosting.delete(site.subdomain);
|
||||
await puter.hosting.delete(site.subdomain);
|
||||
puter.print('Website deleted<br>');
|
||||
|
||||
// (3) Try to retrieve the website (should fail)
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
document.write(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`);
|
||||
|
||||
// (2) Retrieve the website using get()
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
(async () => {
|
||||
// (1) Create a random website
|
||||
let subdomain = puter.randName();
|
||||
const site = await puter.hosting.create(subdomain)
|
||||
const site = await puter.hosting.create(subdomain, '.')
|
||||
puter.print(`Website hosted at: ${site.subdomain}.puter.site<br>`);
|
||||
|
||||
// (2) Create a random directory
|
||||
@@ -18,7 +18,7 @@
|
||||
puter.print(`Changed subdomain's root directory to "${dir.path}"<br>`);
|
||||
|
||||
// (4) Delete the app (cleanup)
|
||||
await puter.hosting.delete(updatedSite.subdomain)
|
||||
await puter.hosting.delete(subdomain)
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -1258,6 +1258,20 @@ let sidebar = [
|
||||
source: '/Objects/subdomain.md',
|
||||
path: '/Objects/subdomain',
|
||||
},
|
||||
{
|
||||
title: '<code>TTSEngine</code>',
|
||||
title_tag: 'TTSEngine',
|
||||
icon: '/assets/img/object.svg',
|
||||
source: '/Objects/ttsengine.md',
|
||||
path: '/Objects/ttsengine',
|
||||
},
|
||||
{
|
||||
title: '<code>TTSVoice</code>',
|
||||
title_tag: 'TTSVoice',
|
||||
icon: '/assets/img/object.svg',
|
||||
source: '/Objects/ttsvoice.md',
|
||||
path: '/Objects/ttsvoice',
|
||||
},
|
||||
{
|
||||
title: '<code>ToolCall</code>',
|
||||
title_tag: 'ToolCall',
|
||||
|
||||
Vendored
+220
-12
@@ -1,9 +1,17 @@
|
||||
export type AIMessageContent = string | { image_url?: { url: string } } | { video_url?: { url: string } } | Record<string, unknown>;
|
||||
|
||||
export interface ImageContent {
|
||||
type: string;
|
||||
image_url: { url: string };
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
role?: string;
|
||||
content: AIMessageContent | AIMessageContent[];
|
||||
tool_calls?: ToolCall[];
|
||||
tool_call_id?: string;
|
||||
cache_control?: { type: string };
|
||||
images: ImageContent[];
|
||||
}
|
||||
|
||||
export interface ToolCall {
|
||||
@@ -11,18 +19,55 @@ export interface ToolCall {
|
||||
function: { name: string, arguments: string };
|
||||
}
|
||||
|
||||
export interface Tool {
|
||||
type: string;
|
||||
function: { name: string, description: string, parameters: object, strict?: boolean };
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for a chat completion request.
|
||||
*/
|
||||
export interface ChatOptions {
|
||||
/** The model to use for the completion. Defaults to `gpt-5-nano` if not specified. */
|
||||
model?: string;
|
||||
/** Sampling temperature between 0 and 2. Lower values are more focused and deterministic, higher values more random. Defaults to the model's own default. */
|
||||
temperature?: number;
|
||||
max_tokens?: number;
|
||||
vision?: boolean;
|
||||
driver?: string;
|
||||
tools?: unknown;
|
||||
/** The provider to route the request through. */
|
||||
provider?: string;
|
||||
/** Function/tool definitions the model can call. See Function Calling. */
|
||||
tools?: Tool[];
|
||||
response?: unknown;
|
||||
reasoning?: unknown;
|
||||
/**
|
||||
* Controls how much effort reasoning models spend thinking. Flat form.
|
||||
* Accepted values: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`
|
||||
* (availability varies by model; default `medium` on newer GPT-5.x models).
|
||||
* Reasoning models only.
|
||||
*/
|
||||
reasoning_effort?: string;
|
||||
text?: unknown;
|
||||
verbosity?: unknown;
|
||||
/**
|
||||
* Nested form of `reasoning_effort`. The `effort` value accepts the same
|
||||
* values as `reasoning_effort`. Reasoning models only.
|
||||
*/
|
||||
reasoning?: { effort: string};
|
||||
/**
|
||||
* Controls how long or short responses are. Flat form. Accepted values:
|
||||
* `low`, `medium`, `high`. Reasoning models only.
|
||||
*/
|
||||
verbosity?: string;
|
||||
/**
|
||||
* Nested form of `verbosity` — it lives under `text`. The `verbosity` value
|
||||
* accepts the same values as `verbosity`. Reasoning models only.
|
||||
*/
|
||||
text?: { verbosity: string};
|
||||
/**
|
||||
* Controls image output for image-capable models.
|
||||
* - `aspect_ratio`: aspect ratio of the generated image, e.g. `"16:9"`, `"1:1"`, `"9:16"`.
|
||||
* - `image_size`: output quality/resolution; must be one of the model's supported quality levels.
|
||||
*/
|
||||
image_config?: { aspect_ratio: string, image_size: string };
|
||||
}
|
||||
|
||||
export interface StreamingChatOptions extends ChatOptions {
|
||||
@@ -34,9 +79,27 @@ export interface ChatResponse {
|
||||
choices?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* A single chunk of a streaming chat response. Each chunk has a `type`
|
||||
* discriminator; which other fields are present depends on that `type`.
|
||||
*/
|
||||
export interface ChatResponseChunk {
|
||||
/** The kind of chunk: `"text"`, `"reasoning"`, `"tool_use"`, `"extra_content"`, or `"usage"`. */
|
||||
type: string;
|
||||
/** Text delta. Present on `"text"` chunks. */
|
||||
text?: string;
|
||||
/** Reasoning/thinking delta. Present on `"reasoning"` chunks. */
|
||||
reasoning?: string;
|
||||
/** Tool call id. Present on `"tool_use"` chunks. */
|
||||
id?: string;
|
||||
/** Tool/function name. Present on `"tool_use"` chunks. */
|
||||
name?: string;
|
||||
/** Parsed tool call arguments. Present on `"tool_use"` chunks. */
|
||||
input?: unknown;
|
||||
/** Provider-specific extra metadata. */
|
||||
extra_content?: unknown;
|
||||
/** Token usage totals. Present on the final `"usage"` chunk. */
|
||||
usage?: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface Img2TxtOptions {
|
||||
@@ -53,36 +116,93 @@ export interface Img2TxtOptions {
|
||||
}
|
||||
|
||||
export interface Txt2ImgOptions {
|
||||
/** Text description of the image to generate. */
|
||||
prompt?: string;
|
||||
/**
|
||||
* Image model to use (provider-specific). Defaults to `'gpt-image-1-mini'`
|
||||
* (OpenAI), or `'grok-2-image'` when `provider` is `'xai'`.
|
||||
*/
|
||||
model?: string;
|
||||
/**
|
||||
* Image quality / output size tier. Interpretation is provider- and
|
||||
* model-specific:
|
||||
* - OpenAI GPT models: `'high'` | `'medium'` | `'low'` (default `'low'`);
|
||||
* `gpt-image-2` also accepts `'auto'`.
|
||||
* - OpenAI DALL-E 3: `'hd'` | `'standard'` (default `'standard'`).
|
||||
* - Gemini: output size tier `'512'` | `'1K'` | `'2K'` | `'4K'`
|
||||
* (availability varies by model).
|
||||
*/
|
||||
quality?: string;
|
||||
/**
|
||||
* An input image for image-to-image generation. Replicate expects a URL;
|
||||
* Gemini expects a base64-encoded image.
|
||||
*/
|
||||
input_image?: string;
|
||||
/**
|
||||
* Multiple input images for image-to-image / multi-image generation.
|
||||
* Gemini expects base64-encoded images; Replicate expects image URLs.
|
||||
*/
|
||||
input_images?: string[];
|
||||
/**
|
||||
* MIME type of the input image(s), e.g. `'image/png'`. Used as a fallback
|
||||
* when the type cannot be auto-detected (Gemini).
|
||||
*/
|
||||
input_image_mime_type?: string;
|
||||
driver?: string;
|
||||
provider?: string;
|
||||
service?: string;
|
||||
/**
|
||||
* Aspect ratio as `{ w, h }` (e.g. `{ w: 16, h: 9 }`). Supported by OpenAI,
|
||||
* Gemini, and Replicate.
|
||||
*/
|
||||
ratio?: { w: number; h: number };
|
||||
/** Width of the image to generate, in pixels (Together). Default `1024`. */
|
||||
width?: number;
|
||||
/** Height of the image to generate, in pixels (Together). Default `1024`. */
|
||||
height?: number;
|
||||
/** Alternative way to specify the aspect ratio (Together). */
|
||||
aspect_ratio?: string;
|
||||
/**
|
||||
* Number of generation/inference steps (Together, default `20`; Replicate
|
||||
* `flux-schnell`).
|
||||
*/
|
||||
steps?: number;
|
||||
/** Seed used for generation; reuse to reproduce results (Together, Replicate). */
|
||||
seed?: number;
|
||||
/** Prompt describing what NOT to guide the image generation toward (Together). */
|
||||
negative_prompt?: string;
|
||||
/** Number of image results to generate (Together). Default `1`. */
|
||||
n?: number;
|
||||
/** URL of an input image for models that support it (Together). */
|
||||
image_url?: string;
|
||||
/** Base64-encoded input image for image-to-image generation (Together). */
|
||||
image_base64?: string;
|
||||
/** URL of a mask image for inpainting (Together). */
|
||||
mask_image_url?: string;
|
||||
/** Base64-encoded mask image for inpainting (Together). */
|
||||
mask_image_base64?: string;
|
||||
/** How strongly the prompt influences the output (Together). */
|
||||
prompt_strength?: number;
|
||||
/** When `true`, disables the safety checker (Together, Replicate). */
|
||||
disable_safety_checker?: boolean;
|
||||
/**
|
||||
* Format of the image response. Together: `'base64'` | `'url'`. Replicate:
|
||||
* output format, e.g. `'webp'` | `'jpg'` | `'png'`.
|
||||
*/
|
||||
response_format?: string;
|
||||
/** When `true`, returns a sample image without using credits. */
|
||||
test_mode?: boolean;
|
||||
/**
|
||||
* When set, the generated image is saved to this path on the Puter
|
||||
* filesystem. Relative paths resolve against the app's data directory
|
||||
* (`~/AppData/<appID>/`) when called from an app, or `~/` otherwise. The
|
||||
* caller must have write permission to the destination.
|
||||
*/
|
||||
puter_output_path?: string;
|
||||
}
|
||||
|
||||
export interface Txt2VidOptions {
|
||||
prompt?: string;
|
||||
provider?: string;
|
||||
driver?: string;
|
||||
model?: string;
|
||||
seconds?: number;
|
||||
@@ -92,7 +212,7 @@ export interface Txt2VidOptions {
|
||||
// OpenAI options
|
||||
size?: string;
|
||||
resolution?: string;
|
||||
input_reference?: File;
|
||||
input_reference?: File | string;
|
||||
|
||||
// TogetherAI options
|
||||
width?: number;
|
||||
@@ -108,27 +228,119 @@ export interface Txt2VidOptions {
|
||||
frame_images?: Array<{ input_image: string; frame: number }>;
|
||||
metadata?: Record<string, unknown>;
|
||||
puter_output_path?: string;
|
||||
|
||||
last_frame?: string;
|
||||
}
|
||||
|
||||
export interface Txt2SpeechOptions {
|
||||
/** Text to synthesize. Must be less than 3000 characters. */
|
||||
text?: string;
|
||||
/** Language code. For AWS Polly defaults to `'en-US'`; for xAI a BCP-47 code defaulting to `'en'` (supports `'auto'`). */
|
||||
language?: string;
|
||||
/** Voice ID used for synthesis (provider-specific). Defaults to `'Joanna'` (aws-polly), `'alloy'` (openai), `'21m00Tcm4TlvDq8ikWAM'` (elevenlabs), `'Kore'` (gemini), `'eve'` (xai). */
|
||||
voice?: string;
|
||||
/** AWS Polly synthesis engine: `'standard'` (default), `'neural'`, `'long-form'`, or `'generative'`. */
|
||||
engine?: string;
|
||||
/** TTS provider: `'aws-polly'` (default), `'openai'`, `'elevenlabs'`, `'gemini'`, or `'xai'`. */
|
||||
provider?: string;
|
||||
/** Model identifier (provider-specific). */
|
||||
model?: string;
|
||||
/** OpenAI output format: `'mp3'` (default), `'wav'`, `'opus'`, `'aac'`, `'flac'`, or `'pcm'`. */
|
||||
response_format?: string;
|
||||
/** Output format for ElevenLabs (defaults to `'mp3_44100_128'`) and xAI (`'mp3'` default, `'wav'`, `'pcm'`, `'mulaw'`, `'alaw'`). */
|
||||
output_format?: string;
|
||||
/** Natural-language guidance for voice style such as tone, speed, and mood (OpenAI and Gemini). */
|
||||
instructions?: string;
|
||||
/** ElevenLabs voice tuning options (e.g. stability, similarity boost, speed). */
|
||||
voice_settings?: Record<string, unknown>;
|
||||
/** When `true`, AWS Polly treats `text` as SSML markup. */
|
||||
ssml?: boolean;
|
||||
/** When `true`, returns a sample audio without using credits. */
|
||||
test_mode?: boolean;
|
||||
}
|
||||
|
||||
export interface ListTTSEnginesOptions {
|
||||
/** TTS provider to query. Defaults to `'aws-polly'`. */
|
||||
provider?: string;
|
||||
}
|
||||
|
||||
/** A TTS engine/model as returned by `txt2speech.listEngines()`. */
|
||||
export interface TTSEngine {
|
||||
/** Engine/model identifier. */
|
||||
id: string;
|
||||
/** Human-readable engine name. */
|
||||
name: string;
|
||||
/** Provider this engine belongs to. */
|
||||
provider: string;
|
||||
/** Cost per million characters (may be absent). */
|
||||
pricing_per_million_chars?: number;
|
||||
}
|
||||
|
||||
export interface ListTTSVoicesOptions {
|
||||
/** TTS provider to query. Defaults to `'aws-polly'`. */
|
||||
provider?: string;
|
||||
/** Engine/model filter (provider-specific, ignored by some providers). */
|
||||
engine?: string;
|
||||
}
|
||||
|
||||
/** A TTS voice as returned by `txt2speech.listVoices()`. */
|
||||
export interface TTSVoice {
|
||||
/** Voice identifier to pass to `txt2speech()`. */
|
||||
id: string;
|
||||
/** Human-readable voice name. */
|
||||
name: string;
|
||||
/** Provider this voice belongs to. */
|
||||
provider: string;
|
||||
/** Language info (may be absent). */
|
||||
language?: { name: string; code: string };
|
||||
/** Short description of the voice (may be absent). */
|
||||
description?: string;
|
||||
/** Voice category, e.g. `'premade'` (may be absent). */
|
||||
category?: string;
|
||||
/** Provider-specific labels (may be absent). */
|
||||
labels?: Record<string, unknown>;
|
||||
/** Model IDs this voice works with (may be absent). */
|
||||
supported_models?: string[];
|
||||
/** Engine types this voice supports (may be absent). */
|
||||
supported_engines?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts text to speech. Callable directly, with `listEngines` and
|
||||
* `listVoices` helpers attached for discovering available engines and voices.
|
||||
*/
|
||||
export interface Txt2Speech {
|
||||
(text: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
(text: string, options: Txt2SpeechOptions, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
(text: string, language: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
(text: string, language: string, voice: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
(text: string, language: string, voice: string, engine: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
|
||||
/** List available TTS engines/models with pricing information. */
|
||||
listEngines (provider?: string): Promise<TTSEngine[]>;
|
||||
listEngines (options?: ListTTSEnginesOptions): Promise<TTSEngine[]>;
|
||||
|
||||
/** List available TTS voices, optionally filtered by provider/engine. */
|
||||
listVoices (engine?: string): Promise<TTSVoice[]>;
|
||||
listVoices (options?: ListTTSVoicesOptions): Promise<TTSVoice[]>;
|
||||
}
|
||||
|
||||
export interface Speech2TxtWord {
|
||||
text: string;
|
||||
start: number;
|
||||
end: number;
|
||||
/** Detected speaker, present when `diarize: true` (xAI). */
|
||||
speaker?: string;
|
||||
}
|
||||
|
||||
export interface Speech2TxtResult {
|
||||
text: string;
|
||||
language: string;
|
||||
segments?: Record<string, unknown>[];
|
||||
/** Duration of the audio in seconds (provider-dependent, e.g. xAI). */
|
||||
duration?: number;
|
||||
/** Per-word timestamps (provider-dependent, e.g. xAI). */
|
||||
words?: Speech2TxtWord[];
|
||||
}
|
||||
|
||||
interface BaseSpeech2TxtOptions {
|
||||
@@ -211,7 +423,7 @@ export class AI {
|
||||
txt2vid (prompt: string, options: Txt2VidOptions): Promise<HTMLVideoElement>;
|
||||
txt2vid (options: Txt2VidOptions, testMode?: boolean): Promise<HTMLVideoElement>;
|
||||
|
||||
speech2txt (source: string | File | Blob, testMode?: boolean): Promise<string>;
|
||||
speech2txt (source: string | File | Blob, testMode?: boolean): Promise<Speech2TxtResult>;
|
||||
speech2txt (source: string | File | Blob, options: TextFormatSpeech2TxtOptions, testMode?: boolean): Promise<string>;
|
||||
speech2txt (source: string | File | Blob, options: Speech2TxtOptions, testMode?: boolean): Promise<Speech2TxtResult>;
|
||||
speech2txt (options: TextFormatSpeech2TxtOptions, testMode?: boolean): Promise<string>;
|
||||
@@ -221,11 +433,7 @@ export class AI {
|
||||
speech2speech (source: string | File | Blob, options: Speech2SpeechOptions, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
speech2speech (options: Speech2SpeechOptions, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
|
||||
txt2speech (text: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
txt2speech (text: string, options: Txt2SpeechOptions, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
txt2speech (text: string, language: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
txt2speech (text: string, language: string, voice: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
txt2speech (text: string, language: string, voice: string, engine: string, testMode?: boolean): Promise<HTMLAudioElement>;
|
||||
txt2speech: Txt2Speech;
|
||||
}
|
||||
|
||||
// NOTE: AI responses contain provider-specific payloads that are not fully typed here because
|
||||
|
||||
Vendored
+139
-18
@@ -1,76 +1,197 @@
|
||||
import type { RequestCallbacks } from '../shared.d.ts';
|
||||
|
||||
export interface App {
|
||||
uid: string;
|
||||
name: string;
|
||||
index_url: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
maximize_on_start?: boolean;
|
||||
background?: boolean;
|
||||
filetype_associations?: string[];
|
||||
metadata?: Record<string, unknown>;
|
||||
created_at?: string;
|
||||
open_count?: number;
|
||||
user_count?: number;
|
||||
/** A user of an app, as returned by `App.users()` and `App.getUsers()`. */
|
||||
export interface AppUser {
|
||||
/** The user's username. */
|
||||
username: string;
|
||||
/** The user's unique identifier. */
|
||||
user_uuid: string;
|
||||
}
|
||||
|
||||
export interface CreateAppResult {
|
||||
/** Pagination options for `App.getUsers()`. */
|
||||
export interface GetUsersOptions {
|
||||
/** The number of users to retrieve. Default is `100`. */
|
||||
limit?: number;
|
||||
/** The offset to start retrieving users from. Default is `0`. */
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
/** The `App` object containing Puter app details. */
|
||||
export interface App {
|
||||
/** The unique identifier of the app, generated by Puter when the app is created. */
|
||||
uid: string;
|
||||
/** The name of the app. */
|
||||
name: string;
|
||||
title: string;
|
||||
/** The URL of the index file of the app, loaded when the app is started. */
|
||||
index_url: string;
|
||||
/** The title of the app. */
|
||||
title?: string;
|
||||
/** The description of the app. */
|
||||
description?: string;
|
||||
/** The Data URL of the icon of the app (a base64 encoded image). */
|
||||
icon?: string;
|
||||
/** Whether the app should be maximized when it is started. Default is `false`. */
|
||||
maximize_on_start?: boolean;
|
||||
/** Whether the app should run in the background. Default is `false`. */
|
||||
background?: boolean;
|
||||
/**
|
||||
* The file types that the app can open. Each string is in the format
|
||||
* `".<extension>"` or `"mime/type"`, e.g. `[".txt", "image/png"]`. For a
|
||||
* directory association, the string should be `.directory`.
|
||||
*/
|
||||
filetype_associations?: string[];
|
||||
/** Custom metadata for the app as arbitrary key-value pairs. */
|
||||
metadata?: Record<string, unknown>;
|
||||
/** The date and time when the app was created, in `YYYY-MM-DDTHH:MM:SSZ` format. */
|
||||
created_at?: string;
|
||||
/**
|
||||
* The number of times the app has been opened. If `stats_period` is set to
|
||||
* a value other than `all`, this is the count within that period.
|
||||
*/
|
||||
open_count?: number;
|
||||
/**
|
||||
* The number of users that have access to the app. If `stats_period` is set
|
||||
* to a value other than `all`, this is the count within that period.
|
||||
*/
|
||||
user_count?: number;
|
||||
/**
|
||||
* Iterates over all users of the app, fetching them page by page.
|
||||
* @param pageSize - The number of users to retrieve per page. Default is 100.
|
||||
*/
|
||||
users (pageSize?: number): AsyncIterableIterator<AppUser>;
|
||||
/**
|
||||
* Retrieves a list of users one page at a time as defined by limit and offset.
|
||||
* @param params - Pagination options.
|
||||
*/
|
||||
getUsers (params?: GetUsersOptions): Promise<AppUser[]>;
|
||||
}
|
||||
|
||||
/** The result returned by `Apps.create()`. */
|
||||
export interface CreateAppResult {
|
||||
/** The unique identifier of the app, generated by Puter when the app is created. */
|
||||
uid: string;
|
||||
/** The name of the app. */
|
||||
name: string;
|
||||
/** The title of the app. */
|
||||
title: string;
|
||||
/** The URL of the index file of the app, loaded when the app is started. */
|
||||
index_url: string;
|
||||
/** The subdomain assigned to the app. */
|
||||
subdomain: string;
|
||||
/** Information about the owner of the app. */
|
||||
owner: {
|
||||
/** The username of the owner. */
|
||||
username: string;
|
||||
/** The unique identifier of the owner. */
|
||||
uuid: string;
|
||||
};
|
||||
app_owner?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Options for `Apps.list()` and `Apps.get()`. */
|
||||
export interface AppListOptions {
|
||||
/**
|
||||
* The period for which to get the user and open count. One of `today`,
|
||||
* `yesterday`, `7d`, `30d`, `this_month`, `last_month`, `this_year`,
|
||||
* `last_year`, `month_to_date`, `year_to_date`, or `last_12_months`.
|
||||
* Default is `all` (all time).
|
||||
*/
|
||||
stats_period?: string;
|
||||
/** The size of the icons to return. Default is `null` (the original size). */
|
||||
icon_size?: null | 16 | 32 | 64 | 128 | 256 | 512;
|
||||
}
|
||||
|
||||
/** Options for creating an app with `Apps.create()`. */
|
||||
export interface CreateAppOptions {
|
||||
/**
|
||||
* The name of the app to create. Must be unique to the user's apps;
|
||||
* if an app with this name already exists the promise is rejected.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The URL of the app's index page, displayed when the app is started.
|
||||
* Must start with `http://` or `https://`; other protocols are not allowed.
|
||||
*/
|
||||
indexURL: string;
|
||||
/** The human-readable title of the app. Defaults to `name` if not provided. */
|
||||
title?: string;
|
||||
/** The description of the app aimed at the end user. */
|
||||
description?: string;
|
||||
/** The icon of the app. */
|
||||
icon?: string;
|
||||
/** Whether the app should be maximized when it is started. Defaults to `false`. */
|
||||
maximizeOnStart?: boolean;
|
||||
/** Whether the app should run in the background. Defaults to `false`. */
|
||||
background?: boolean;
|
||||
/**
|
||||
* The filetypes that the app can open. File extensions and MIME types are
|
||||
* supported, e.g. `[".txt", ".md", "application/pdf"]`. Defaults to `[]`.
|
||||
*/
|
||||
filetypeAssociations?: string[];
|
||||
/** Custom metadata for the app as arbitrary key-value pairs. */
|
||||
metadata?: Record<string, unknown>;
|
||||
/** Whether to deduplicate the app name if it already exists. Defaults to `false`. */
|
||||
dedupeName?: boolean;
|
||||
}
|
||||
|
||||
/** Attributes to update with `Apps.update()`. */
|
||||
export interface UpdateAppAttributes {
|
||||
/**
|
||||
* The new name of the app. Must be unique to the user's apps; if an app
|
||||
* with this name already exists the promise is rejected.
|
||||
*/
|
||||
name?: string;
|
||||
/** The new URL of the app's index page. Must be accessible to the user. */
|
||||
indexURL?: string;
|
||||
/** The new title of the app. */
|
||||
title?: string;
|
||||
/** The new description of the app aimed at the end user. */
|
||||
description?: string;
|
||||
/** The new icon of the app. */
|
||||
icon?: string;
|
||||
/** Whether the app should be maximized when it is started. Defaults to `false`. */
|
||||
maximizeOnStart?: boolean;
|
||||
/** Whether the app should run in the background. Defaults to `false`. */
|
||||
background?: boolean;
|
||||
/**
|
||||
* The filetypes that the app can open. File extensions and MIME types are
|
||||
* supported, e.g. `[".txt", ".md", "application/pdf"]`. Defaults to `[]`.
|
||||
*/
|
||||
filetypeAssociations?: string[];
|
||||
/** Custom metadata for the app as arbitrary key-value pairs. */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** The result returned by `Apps.checkName()`. */
|
||||
export interface CheckAppNameResult {
|
||||
/** The name that was checked. */
|
||||
name: string;
|
||||
/** Whether the name is available. */
|
||||
available: boolean;
|
||||
}
|
||||
|
||||
/** Create, manage, and interact with applications in the Puter ecosystem. */
|
||||
export class Apps {
|
||||
/**
|
||||
* Returns all apps belonging to the user that this app has access to.
|
||||
* Resolves to an empty array if the user has no apps.
|
||||
*/
|
||||
list (options?: AppListOptions): Promise<App[]>;
|
||||
/**
|
||||
* Creates a Puter app with the given name. The app name must be unique to
|
||||
* the user's apps; if one already exists the promise is rejected. `indexURL`
|
||||
* must start with `http://` or `https://`.
|
||||
*/
|
||||
create (name: string, indexURL: string, title?: string): Promise<CreateAppResult>;
|
||||
create (options: CreateAppOptions): Promise<CreateAppResult>;
|
||||
/** Updates attributes of the app with the given name. */
|
||||
update (name: string, attributes: UpdateAppAttributes): Promise<App>;
|
||||
/** Returns the app with the given name. If the app does not exist, the promise is rejected. */
|
||||
get (name: string, options?: AppListOptions): Promise<App>;
|
||||
delete (name: string): Promise<{ success?: boolean }>;
|
||||
/**
|
||||
* Deletes the app with the given name. Resolves to `{ success: true, uid }`
|
||||
* with the `uid` of the deleted app.
|
||||
*/
|
||||
delete (name: string): Promise<{ success: boolean; uid: string }>;
|
||||
checkName (name: string): Promise<CheckAppNameResult>;
|
||||
getDeveloperProfile (options?: RequestCallbacks<Record<string, unknown>>): Promise<Record<string, unknown>>;
|
||||
getDeveloperProfile (success: (value: Record<string, unknown>) => void, error?: (reason: unknown) => void): Promise<Record<string, unknown>>;
|
||||
|
||||
Vendored
+64
@@ -1,64 +1,128 @@
|
||||
import { RequestCallbacks } from "../shared";
|
||||
|
||||
/** Puter user details, as returned by `getUser()`. */
|
||||
export interface User {
|
||||
/** Unique identifier of the user. */
|
||||
uuid: string;
|
||||
/** The user's username. */
|
||||
username: string;
|
||||
/** Whether the user's email address has been confirmed. */
|
||||
email_confirmed?: boolean | number;
|
||||
/** The user's free storage. */
|
||||
actual_free_storage?: number;
|
||||
/** The current active app. */
|
||||
app_name?: string;
|
||||
feature_flags?: Record<string, unknown>;
|
||||
hasDevAccountAccess?: boolean;
|
||||
/** Whether the user's account is temporary. */
|
||||
is_temp?: boolean;
|
||||
/** The user's last active timestamp. */
|
||||
last_activity_ts?: number;
|
||||
otp?: boolean;
|
||||
/** The amount of paid storage. */
|
||||
paid_storage?: number;
|
||||
/** The user's referral code. */
|
||||
referral_code?: string;
|
||||
/** Whether the user's account needs email confirmation. */
|
||||
requires_email_confirmation?: boolean | number;
|
||||
/** Whether the user is subscribed. */
|
||||
subscribed?: boolean;
|
||||
}
|
||||
|
||||
/** Information about the user's resource allowance and consumption. */
|
||||
export interface AllowanceInfo {
|
||||
/** Total resource allowance for the month. */
|
||||
monthUsageAllowance: number;
|
||||
/** The remaining allowance that can be used. */
|
||||
remaining: number;
|
||||
}
|
||||
|
||||
/** Total usage for a single application. */
|
||||
export interface AppUsage {
|
||||
/** Number of Puter API calls for the application. */
|
||||
count: number;
|
||||
/** Total resources consumed by the application. */
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** Usage information for a single API. */
|
||||
export interface APIUsage {
|
||||
/** Total resource consumed by this API. */
|
||||
cost: number;
|
||||
/** Number of times the API is called. */
|
||||
count: number;
|
||||
/** Units of measurement for the API (e.g. tokens for AI calls, bytes for FS operations). */
|
||||
units: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's monthly resource usage in the Puter ecosystem.
|
||||
* Resources are measured in microcents (e.g. `$0.01` = `1,000,000`).
|
||||
*/
|
||||
export interface MonthlyUsage {
|
||||
/** The user's resource allowance and consumption. */
|
||||
allowanceInfo: AllowanceInfo;
|
||||
/** Total usage by application, keyed by application id. */
|
||||
appTotals: Record<string, AppUsage>;
|
||||
/** Usage information per API, keyed by API name. */
|
||||
usage: Record<string, APIUsage>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detailed resource usage statistics for a specific application.
|
||||
* Resources are measured in microcents (e.g. `$0.01` = `1,000,000`).
|
||||
*/
|
||||
export interface DetailedAppUsage {
|
||||
/** The application's total resource consumption. */
|
||||
total: number;
|
||||
/** Usage information per API, keyed by API name. */
|
||||
[key: string]: APIUsage;
|
||||
}
|
||||
|
||||
/** The result of a sign-in operation. */
|
||||
export interface SignInResult {
|
||||
/** Whether the sign-in operation was successful. */
|
||||
success: boolean;
|
||||
/** The authentication token. */
|
||||
token: string;
|
||||
/** Unique identifier of the application. */
|
||||
app_uid: string;
|
||||
/** Username of the user who signed in. */
|
||||
username: string;
|
||||
/** Error message if the sign-in operation failed. */
|
||||
error?: string;
|
||||
/** Additional message about the sign-in operation. */
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate users with their Puter accounts. Most Puter methods handle
|
||||
* authentication automatically; these methods are only needed for custom
|
||||
* authentication flows.
|
||||
*/
|
||||
export class Auth {
|
||||
/**
|
||||
* Initiates the sign in process for the user, opening a popup window with the
|
||||
* appropriate authentication method. Must be triggered by a user action (such
|
||||
* as a click) because it opens a popup. Resolves once the user has signed in.
|
||||
*
|
||||
* Set `attempt_temp_user_creation` to `true` to have Puter automatically create
|
||||
* a temporary user, useful for onboarding without requiring sign-up.
|
||||
*/
|
||||
signIn (options?: { attempt_temp_user_creation?: boolean }): Promise<SignInResult>;
|
||||
/** Signs the user out of the application. */
|
||||
signOut (): void;
|
||||
/** Returns `true` if the user is signed in, `false` otherwise. */
|
||||
isSignedIn (): boolean;
|
||||
/** Returns the user's basic information. */
|
||||
getUser (options?: RequestCallbacks<User>): Promise<User>;
|
||||
whoami (): Promise<User>;
|
||||
/** Gets the user's current monthly resource usage. Usage data is scoped to the calling app only. */
|
||||
getMonthlyUsage (): Promise<MonthlyUsage>;
|
||||
/**
|
||||
* Gets detailed resource usage statistics for an application by its `appId`.
|
||||
* Users can only see usage of applications they have accessed before, and
|
||||
* usage data is scoped to the calling app only.
|
||||
*/
|
||||
getDetailedAppUsage (appId: string): Promise<DetailedAppUsage>;
|
||||
}
|
||||
|
||||
+134
-5
@@ -1,89 +1,151 @@
|
||||
import type { RequestCallbacks } from '../shared.d.ts';
|
||||
import type { FSItem } from './fs-item.d.ts';
|
||||
|
||||
/**
|
||||
* Storage space information for the current user, in bytes.
|
||||
*/
|
||||
export interface SpaceInfo {
|
||||
/** Total storage capacity available to the user, in bytes. */
|
||||
capacity: number;
|
||||
/** Amount of storage space used by the user, in bytes. */
|
||||
used: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `copy` operation.
|
||||
*/
|
||||
export interface CopyOptions extends RequestCallbacks<FSItem> {
|
||||
/** Path to the file or directory to copy. Required when passing options as the only argument. */
|
||||
source?: string;
|
||||
/** Path to the destination. Required when passing options as the only argument. */
|
||||
destination?: string;
|
||||
/** Whether to overwrite the destination file or directory if it already exists. Defaults to `false`. */
|
||||
overwrite?: boolean;
|
||||
/** The new name to use for the copied file or directory. Defaults to `undefined`. */
|
||||
newName?: string;
|
||||
createMissingParents?: boolean;
|
||||
/** Whether to deduplicate the file or directory name if it already exists. Defaults to `false`. */
|
||||
dedupeName?: boolean;
|
||||
newMetadata?: Record<string, unknown>;
|
||||
excludeSocketID?: string;
|
||||
original_client_socket_id?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `move` operation.
|
||||
*/
|
||||
export interface MoveOptions extends RequestCallbacks<FSItem> {
|
||||
/** Path to the file or directory to move. Required when passing options as the only argument. */
|
||||
source?: string;
|
||||
/** Path to the destination. Required when passing options as the only argument. */
|
||||
destination?: string;
|
||||
/** Whether to overwrite the destination file or directory if it already exists. Defaults to `false`. */
|
||||
overwrite?: boolean;
|
||||
/** The new name to use for the moved file or directory. Defaults to `undefined`. */
|
||||
newName?: string;
|
||||
/** Whether to create missing parent directories. Defaults to `false`. */
|
||||
createMissingParents?: boolean;
|
||||
newMetadata?: Record<string, unknown>;
|
||||
excludeSocketID?: string;
|
||||
original_client_socket_id?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `mkdir` operation.
|
||||
*/
|
||||
export interface MkdirOptions extends RequestCallbacks<FSItem> {
|
||||
/** The directory path to create if not specified via function parameter. */
|
||||
path?: string;
|
||||
/** Whether to overwrite the directory if it already exists. Defaults to `false`. */
|
||||
overwrite?: boolean;
|
||||
/** Whether to deduplicate the directory name if it already exists. Defaults to `false`. */
|
||||
dedupeName?: boolean;
|
||||
rename?: boolean;
|
||||
/** Whether to create missing parent directories. Defaults to `false`. */
|
||||
createMissingParents?: boolean;
|
||||
recursive?: boolean;
|
||||
shortcutTo?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `delete` operation.
|
||||
*/
|
||||
export interface DeleteOptions extends RequestCallbacks<void> {
|
||||
/** A single path or array of paths to delete. Required when passing options as the only argument. */
|
||||
paths?: string | string[];
|
||||
/** Whether to delete the directory recursively. Defaults to `true`. */
|
||||
recursive?: boolean;
|
||||
/** Whether to delete only the descendants of the directory and not the directory itself. Defaults to `false`. */
|
||||
descendantsOnly?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `read` operation.
|
||||
*/
|
||||
export interface ReadOptions extends RequestCallbacks<Blob> {
|
||||
/** Path to the file to read. Required when passing options as the only argument. */
|
||||
path?: string;
|
||||
/** The offset to start reading from. */
|
||||
offset?: number;
|
||||
/** The number of bytes to read from the offset. Required if `offset` is provided. */
|
||||
byte_count?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `readdir` operation.
|
||||
*/
|
||||
export interface ReaddirOptions extends RequestCallbacks<FSItem[]> {
|
||||
/** The path to the directory to read. Required when passing options as the only argument. */
|
||||
path?: string;
|
||||
/** The UID of the directory to read. */
|
||||
uid?: string;
|
||||
no_thumbs?: boolean;
|
||||
no_assocs?: boolean;
|
||||
consistency?: 'strong' | 'eventual';
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `rename` operation.
|
||||
*/
|
||||
export interface RenameOptions extends RequestCallbacks<FSItem> {
|
||||
/** The UID of the file or directory to rename. Can be used instead of `path`. */
|
||||
uid?: string;
|
||||
/** Path to the file or directory to rename. Required when passing options as the only argument. */
|
||||
path?: string;
|
||||
/** The new name for the file or directory. Required when passing options as the only argument. */
|
||||
newName?: string;
|
||||
excludeSocketID?: string;
|
||||
original_client_socket_id?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `stat` operation.
|
||||
*/
|
||||
export interface StatOptions extends RequestCallbacks<FSItem> {
|
||||
/** Path to the file or directory. Required when passing options as the only argument. */
|
||||
path?: string;
|
||||
/** The UID of the file or directory. Can be used instead of `path`. */
|
||||
uid?: string;
|
||||
consistency?: 'strong' | 'eventual';
|
||||
/** Whether to return subdomain information. Defaults to `false`. */
|
||||
returnSubdomains?: boolean;
|
||||
/** Whether to return permission information. Defaults to `false`. */
|
||||
returnPermissions?: boolean;
|
||||
/** Whether to return version information. Defaults to `false`. */
|
||||
returnVersions?: boolean;
|
||||
/** Whether to return size information. Defaults to `false`. */
|
||||
returnSize?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `upload` operation.
|
||||
*/
|
||||
export interface UploadOptions extends RequestCallbacks<FSItem | FSItem[]> {
|
||||
/** Whether to overwrite the destination file if it already exists. Defaults to `false`. */
|
||||
overwrite?: boolean;
|
||||
/** Whether to deduplicate the file name if it already exists. Defaults to `true`. Ignored when `overwrite` is `true`. */
|
||||
dedupeName?: boolean;
|
||||
name?: string;
|
||||
parsedDataTransferItems?: boolean;
|
||||
createFileParent?: boolean;
|
||||
createMissingAncestors?: boolean;
|
||||
/** Whether to create missing parent directories. Defaults to `false`. */
|
||||
createMissingParents?: boolean;
|
||||
shortcutTo?: string;
|
||||
appUID?: string;
|
||||
@@ -94,9 +156,15 @@ export interface UploadOptions extends RequestCallbacks<FSItem | FSItem[]> {
|
||||
abort?: (operationId: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for the `write` operation.
|
||||
*/
|
||||
export interface WriteOptions extends RequestCallbacks<FSItem> {
|
||||
/** Whether to overwrite the file if it already exists. Defaults to `true`. */
|
||||
overwrite?: boolean;
|
||||
/** Whether to deduplicate the file name if it already exists. Defaults to `false`. */
|
||||
dedupeName?: boolean;
|
||||
/** Whether to create missing parent directories. Defaults to `false`. */
|
||||
createMissingParents?: boolean;
|
||||
createMissingAncestors?: boolean;
|
||||
init?: (operationId: string, xhr: XMLHttpRequest) => void;
|
||||
@@ -112,47 +180,108 @@ export interface SignResult<T = Record<string, unknown>> {
|
||||
|
||||
export type UploadItems = DataTransferItemList | DataTransferItem | FileList | File[] | Blob[] | Blob | File | string | unknown[];
|
||||
|
||||
/**
|
||||
* The Cloud Storage API. Lets you store and manage files and directories in the cloud.
|
||||
*/
|
||||
export class FS {
|
||||
/**
|
||||
* Returns the storage space capacity and usage for the current user, in bytes.
|
||||
* Requires permission to access the user's storage space.
|
||||
*/
|
||||
space (): Promise<SpaceInfo>;
|
||||
space (options: RequestCallbacks<SpaceInfo>): Promise<SpaceInfo>;
|
||||
space (success: (value: SpaceInfo) => void, error?: (reason: unknown) => void): Promise<SpaceInfo>;
|
||||
|
||||
/**
|
||||
* Creates a directory. Resolves to the `FSItem` of the created directory.
|
||||
* If `path` is not absolute, it is resolved relative to the app's root directory.
|
||||
*/
|
||||
mkdir (options: MkdirOptions): Promise<FSItem>;
|
||||
mkdir (path: string, options?: MkdirOptions): Promise<FSItem>;
|
||||
mkdir (path: string, options: MkdirOptions, success: (value: FSItem) => void, error?: (reason: unknown) => void): Promise<FSItem>;
|
||||
mkdir (path: string, success: (value: FSItem) => void, error?: (reason: unknown) => void): Promise<FSItem>;
|
||||
|
||||
/**
|
||||
* Copies a file or directory from one location to another. Resolves to the `FSItem`
|
||||
* of the copied file or directory. If the source does not exist, the promise is rejected.
|
||||
* If `destination` is a directory, the item is copied into it using the same name.
|
||||
*/
|
||||
copy (options: CopyOptions): Promise<FSItem>;
|
||||
copy (source: string, destination: string, options?: CopyOptions): Promise<FSItem>;
|
||||
copy (source: string, destination: string, options: CopyOptions | undefined, success: (value: FSItem) => void, error?: (reason: unknown) => void): Promise<FSItem>;
|
||||
|
||||
/**
|
||||
* Moves a file or directory from one location to another. Resolves to the `FSItem`
|
||||
* of the moved file or directory. If the source does not exist, the promise is rejected.
|
||||
* If `destination` is a directory, the item is moved into it using the same name.
|
||||
*/
|
||||
move (options: MoveOptions): Promise<FSItem>;
|
||||
move (source: string, destination: string, options?: MoveOptions): Promise<FSItem>;
|
||||
|
||||
/**
|
||||
* Renames a file or directory to a new name. Resolves to the `FSItem` of the renamed item.
|
||||
* If `path` is not absolute, it is resolved relative to the app's root directory.
|
||||
*/
|
||||
rename (options: RenameOptions): Promise<FSItem>;
|
||||
rename (path: string, newName: string, success?: (value: FSItem) => void, error?: (reason: unknown) => void): Promise<FSItem>;
|
||||
|
||||
/**
|
||||
* Reads data from a file. Resolves to a `Blob` containing the file's contents.
|
||||
* If `path` is not absolute, it is resolved relative to the app's root directory.
|
||||
*/
|
||||
read (options: ReadOptions): Promise<Blob>;
|
||||
read (path: string, options?: ReadOptions): Promise<Blob>;
|
||||
read (path: string, success: (value: Blob) => void, error?: (reason: unknown) => void): Promise<Blob>;
|
||||
|
||||
/**
|
||||
* Reads the contents of a directory. Resolves to an array of `FSItem` objects
|
||||
* (files and directories) within the specified directory.
|
||||
* If `path` is not absolute, it is resolved relative to the app's root directory.
|
||||
*/
|
||||
readdir (options: ReaddirOptions): Promise<FSItem[]>;
|
||||
readdir (path: string, success?: (value: FSItem[]) => void, error?: (reason: unknown) => void): Promise<FSItem[]>;
|
||||
|
||||
/**
|
||||
* Gets information about a file or directory. Resolves to the `FSItem` of the item.
|
||||
* If `path` is not absolute, it is resolved relative to the app's root directory.
|
||||
*/
|
||||
stat (options: StatOptions): Promise<FSItem>;
|
||||
stat (path: string, options?: StatOptions): Promise<FSItem>;
|
||||
stat (path: string, options: StatOptions, success: (value: FSItem) => void, error?: (reason: unknown) => void): Promise<FSItem>;
|
||||
stat (path: string, success: (value: FSItem) => void, error?: (reason: unknown) => void): Promise<FSItem>;
|
||||
|
||||
/**
|
||||
* Deletes a file or directory. Accepts a single path or an array of paths.
|
||||
* Resolves when the file(s) or directory(ies) are deleted.
|
||||
* If a path is not absolute, it is resolved relative to the app's root directory.
|
||||
*/
|
||||
delete (options: DeleteOptions): Promise<void>;
|
||||
delete (paths: string | string[], options?: DeleteOptions): Promise<void>;
|
||||
|
||||
/**
|
||||
* Uploads local items to the Puter filesystem. Resolves to a single `FSItem` if `items`
|
||||
* contains one item, or an array of `FSItem` objects if it contains multiple items.
|
||||
* If `dirPath` is not set, items are uploaded to the app's root directory.
|
||||
*/
|
||||
upload (items: UploadItems, dirPath?: string, options?: UploadOptions): Promise<FSItem | FSItem[]>;
|
||||
|
||||
/**
|
||||
* Writes data to a file, creating it if it does not exist. Resolves to the `FSItem`
|
||||
* of the written file. If `path` is not absolute, it is resolved relative to the app's
|
||||
* root directory. A `File` may be written directly, in which case its path is derived
|
||||
* from the file's name.
|
||||
*/
|
||||
write (file: File): Promise<FSItem>;
|
||||
write (path: string, data: string | File | Blob | ArrayBuffer | ArrayBufferView, options?: WriteOptions): Promise<FSItem>;
|
||||
|
||||
sign (appUid: string, items: unknown | unknown[], success?: (result: SignResult) => void, error?: (reason: unknown) => void): Promise<SignResult>;
|
||||
|
||||
getReadURL (path: string, expiresIn?: string): Promise<string>;
|
||||
/**
|
||||
* Generates a URL that can be used to read a file. Resolves to the URL string.
|
||||
* `expiresIn` controls how long the URL stays valid, as a
|
||||
* [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken#usage) duration string
|
||||
* (e.g. `'24h'`, `'30d'`; units `s`, `m`, `h`, `d`, `w`, `y`) or a number of seconds.
|
||||
* Defaults to `'24h'`.
|
||||
*/
|
||||
getReadURL (path: string, expiresIn?: string | number): Promise<string>;
|
||||
}
|
||||
|
||||
+20
-5
@@ -1,5 +1,3 @@
|
||||
import type { ReaddirOptions, WriteOptions } from './filesystem.d.ts';
|
||||
|
||||
export interface FileSignatureInfo {
|
||||
read_url?: string;
|
||||
write_url?: string;
|
||||
@@ -20,31 +18,48 @@ export interface InternalFSProperties {
|
||||
file_signature: FileSignatureInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a file or a directory in the Puter file system.
|
||||
*/
|
||||
export class FSItem {
|
||||
constructor (options: Record<string, unknown>);
|
||||
|
||||
readURL?: string;
|
||||
writeURL?: string;
|
||||
metadataURL?: string;
|
||||
/** The name of the item. */
|
||||
name: string;
|
||||
uid: string;
|
||||
/** The unique identifier of the item, generated by Puter when the item is created. */
|
||||
id: string;
|
||||
uuid: string;
|
||||
/** The path of the item, relative to the root directory of the file system. */
|
||||
path: string;
|
||||
/** The size of the item in bytes. `null` if the item is a directory. */
|
||||
size: number | null;
|
||||
/** Unix timestamp of when the item was last accessed. */
|
||||
accessed?: number;
|
||||
/** Unix timestamp of when the item was last modified. */
|
||||
modified?: number;
|
||||
/** Unix timestamp of when the item was created. */
|
||||
created?: number;
|
||||
isDirectory: boolean;
|
||||
/** Whether the item is a directory. `true` for a directory, `false` for a file. */
|
||||
isDir: boolean;
|
||||
_internalProperties?: InternalFSProperties;
|
||||
|
||||
/** Writes data to the file, overwriting its existing contents. Resolves to the written `FSItem`. */
|
||||
write (data: Blob | File | ArrayBuffer | ArrayBufferView | string): Promise<FSItem>;
|
||||
/** Renames the item. Resolves to the renamed `FSItem`. */
|
||||
rename (newName: string): Promise<FSItem>;
|
||||
move (destination: string, overwrite?: boolean, newName?: string): Promise<FSItem>;
|
||||
copy (destinationDirectory: string, autoRename?: boolean, overwrite?: boolean): Promise<FSItem>;
|
||||
/** Deletes the item. Resolves once the item has been deleted. */
|
||||
delete (): Promise<void>;
|
||||
mkdir (name: string, autoRename?: boolean): Promise<FSItem>;
|
||||
readdir (options?: ReaddirOptions): Promise<FSItem[]>;
|
||||
/** Creates a new subdirectory inside the item. The item must be a directory, otherwise an error is thrown. Resolves to the created `FSItem`. */
|
||||
mkdir (name: string): Promise<FSItem>;
|
||||
/** Lists the contents of the item. The item must be a directory, otherwise an error is thrown. Resolves to an array of `FSItem` objects. */
|
||||
readdir (): Promise<FSItem[]>;
|
||||
/** Reads the contents of the file. Resolves to a `Blob` containing the file's contents. */
|
||||
read (): Promise<Blob>;
|
||||
|
||||
// Placeholders that are not implemented in the runtime SDK yet.
|
||||
|
||||
+27
-5
@@ -1,20 +1,42 @@
|
||||
import type { FSItem } from './fs-item.d.ts';
|
||||
|
||||
/** A subdomain hosted on Puter, containing its details. */
|
||||
export interface Subdomain {
|
||||
/** Unique identifier of the subdomain. */
|
||||
uid: string;
|
||||
/** Name of the subdomain, i.e. the part before the main domain (e.g. `example` in `example.puter.site`). */
|
||||
subdomain: string;
|
||||
/** The root directory of the subdomain, where its files are stored. */
|
||||
root_dir: FSItem;
|
||||
}
|
||||
|
||||
/** Deploy and manage websites on Puter by hosting directories under subdomains. */
|
||||
export class Hosting {
|
||||
/**
|
||||
* Lists all subdomains belonging to the user that this app has access to.
|
||||
* Resolves to an empty array if the user has no subdomains.
|
||||
*/
|
||||
list (): Promise<Subdomain[]>;
|
||||
|
||||
create (subdomain: string, dirPath?: string): Promise<Subdomain>;
|
||||
create (options: { subdomain: string; root_dir?: string }): Promise<Subdomain>;
|
||||
|
||||
update (subdomain: string, dirPath?: string | null): Promise<Subdomain>;
|
||||
/**
|
||||
* Creates a new subdomain served by the hosting service from the given directory.
|
||||
* Rejects if a subdomain with the given name already exists or if the path does not exist.
|
||||
*/
|
||||
create (subdomain: string, dirPath: string): Promise<Subdomain>;
|
||||
create (options: { subdomain: string; root_dir: string }): Promise<Subdomain>;
|
||||
|
||||
/**
|
||||
* Updates a subdomain to point to a new directory.
|
||||
* Rejects if the subdomain does not exist or if the path does not exist.
|
||||
*/
|
||||
update (subdomain: string, dirPath: string): Promise<Subdomain>;
|
||||
|
||||
/** Retrieves a subdomain by name. Rejects if the subdomain does not exist. */
|
||||
get (subdomain: string): Promise<Subdomain>;
|
||||
|
||||
delete (subdomain: string): Promise<boolean>;
|
||||
/**
|
||||
* Deletes a subdomain from the account; it will no longer be served. The associated
|
||||
* directory is disconnected but not deleted. Rejects if the subdomain does not exist.
|
||||
*/
|
||||
delete (subdomain: string): Promise<{ success: boolean; uid: string }>;
|
||||
}
|
||||
|
||||
Vendored
+146
-1
@@ -2,27 +2,92 @@
|
||||
export type KVValue = string | number | boolean | object | unknown;
|
||||
export type KVScalar = KVValue | KVValue[];
|
||||
|
||||
/** A key-value pair as returned by `list()` when `returnValues` is `true`. */
|
||||
export interface KVPair<T = unknown> {
|
||||
/** The key name. */
|
||||
key: string;
|
||||
/** The value associated with the key. Can be of any type. */
|
||||
value: T;
|
||||
}
|
||||
|
||||
/** A single item in a batch `set()` operation. */
|
||||
export interface KVSetItem<T = KVScalar> {
|
||||
/** The key to create or update. Maximum key size is `1 KB`. */
|
||||
key: string;
|
||||
/** The value to store. Maximum value size is `400 KB`. */
|
||||
value: T;
|
||||
/** Timestamp, in seconds, at which the key should expire. */
|
||||
expireAt?: number;
|
||||
}
|
||||
|
||||
/** Object form of the arguments to `set()`. */
|
||||
export interface KVSetObject<T = KVScalar> {
|
||||
/** The key to create or update. Maximum key size is `1 KB`. */
|
||||
key: string;
|
||||
/** The value to store. Maximum value size is `400 KB`. */
|
||||
value: T;
|
||||
/** Timestamp, in seconds, at which the key should expire. */
|
||||
expireAt?: number;
|
||||
optConfig?: KVOptConfig;
|
||||
}
|
||||
|
||||
/** Wrapped batch form of `set()`, setting multiple items in a single request. */
|
||||
export interface KVSetBatch<T = KVScalar> {
|
||||
/** The key-value items to set in a single request. */
|
||||
items: KVSetItem<T>[];
|
||||
optConfig?: KVOptConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a dot-separated path to a property within an object value (e.g.
|
||||
* `"user.score"`) to the amount to increment/decrement it by.
|
||||
*/
|
||||
export interface KVIncrementPath {
|
||||
[path: string]: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps each dot-separated path (e.g. `"profile.name"`) to the new value for
|
||||
* that path.
|
||||
*/
|
||||
export interface KVUpdatePath {
|
||||
[path: string]: KVValue;
|
||||
}
|
||||
|
||||
/** Object form of the arguments to `update()`. */
|
||||
export interface KVUpdateObject {
|
||||
/** The key to update. */
|
||||
key: string;
|
||||
/** Maps dot-separated paths to their new values. */
|
||||
pathAndValueMap: KVUpdatePath;
|
||||
/** Time-to-live for the key, in seconds. */
|
||||
ttl?: number;
|
||||
optConfig?: KVOptConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps each dot-separated path (e.g. `"profile.tags"`) to the value (or values)
|
||||
* to add at that path.
|
||||
*/
|
||||
export interface KVAddPath {
|
||||
[path: string]: KVValue | KVValue[];
|
||||
}
|
||||
|
||||
/** Options object form of the arguments to `list()`. */
|
||||
export interface KVListOptions {
|
||||
/**
|
||||
* Prefix-based key filter. A trailing `*` is a wildcard; both `abc` and
|
||||
* `abc*` match keys starting with `abc`. Defaults to `*`, matching all keys.
|
||||
*/
|
||||
pattern?: string;
|
||||
/**
|
||||
* When `true`, results contain `KVPair` objects with `key` and `value`;
|
||||
* when `false`, results contain only keys. Defaults to `false`.
|
||||
*/
|
||||
returnValues?: boolean;
|
||||
/** Maximum number of items to return in a single call. */
|
||||
limit?: number;
|
||||
/** Pagination cursor from a previous call. */
|
||||
cursor?: string;
|
||||
optConfig?: KVOptConfig;
|
||||
}
|
||||
@@ -31,8 +96,14 @@ export type KVListPaginationOptions =
|
||||
| { limit: number; cursor?: string }
|
||||
| { cursor: string; limit?: number };
|
||||
|
||||
/** A page of paginated results from `list()` when `limit` or `cursor` is used. */
|
||||
export interface KVListPage<T = unknown> {
|
||||
/** The keys (or `KVPair` objects when `returnValues` is `true`) for this page. */
|
||||
items: T[];
|
||||
/**
|
||||
* Pagination cursor for the next page. Present only when there are more
|
||||
* results to fetch; pass it to the next `list()` call.
|
||||
*/
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
@@ -40,25 +111,95 @@ export interface KVOptConfig {
|
||||
appUuid?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key-value store. Each app has its own private store within each user's
|
||||
* account; apps cannot access other apps' stores.
|
||||
*/
|
||||
export class KV {
|
||||
/** The maximum allowed key size, in bytes (`1 KB`). */
|
||||
readonly MAX_KEY_SIZE: number;
|
||||
/** The maximum allowed value size, in bytes (`400 KB`). */
|
||||
readonly MAX_VALUE_SIZE: number;
|
||||
|
||||
/**
|
||||
* Creates a key-value pair, or updates the value if the key already exists.
|
||||
* Can also set multiple pairs at once via an array or batch object.
|
||||
* @param key - Key name. Maximum key size is `1 KB`.
|
||||
* @param value - Value to store. Maximum value size is `400 KB`.
|
||||
* @returns `true` once the pair has been created or updated.
|
||||
*/
|
||||
set<T = KVScalar>(key: string, value: T, optConfig: KVOptConfig): Promise<boolean>;
|
||||
/** @param expireAt - Timestamp, in seconds, at which the key should expire. */
|
||||
set<T = KVScalar>(key: string, value: T, expireAt?: number, optConfig?: KVOptConfig): Promise<boolean>;
|
||||
set<T = KVScalar>(item: KVSetObject<T>): Promise<boolean>;
|
||||
set<T = KVScalar>(items: KVSetItem<T>[], optConfig?: KVOptConfig): Promise<boolean>;
|
||||
set<T = KVScalar>(batch: KVSetBatch<T>): Promise<boolean>;
|
||||
/** Returns the key's value, or `undefined` if the key does not exist. */
|
||||
get<T = unknown>(key: string, optConfig?: KVOptConfig): Promise<T | undefined>;
|
||||
/**
|
||||
* Removes a key. Does nothing if the key does not exist.
|
||||
* @returns `true` once the key has been removed.
|
||||
*/
|
||||
del (key: string, optConfig?: KVOptConfig): Promise<boolean>;
|
||||
/**
|
||||
* Increments the value of a key, returning the new value. If the key does
|
||||
* not exist it is initialized to `0` first. Limited to 64-bit signed
|
||||
* integers; errors if the value is not a valid integer.
|
||||
* @param amount - Amount to increment by (defaults to `1`), or an object
|
||||
* mapping a path within an object value to the amount to increment it by.
|
||||
*/
|
||||
incr (key: string, optConfig: KVOptConfig): Promise<number>;
|
||||
incr (key: string, amount?: number | KVIncrementPath, optConfig?: KVOptConfig): Promise<number>;
|
||||
/**
|
||||
* Decrements the value of a key, returning the new value. If the key does
|
||||
* not exist it is initialized to `0` first. Errors if the value is not a
|
||||
* valid integer.
|
||||
* @param amount - Amount to decrement by (defaults to `1`), or an object
|
||||
* mapping a path within an object value to the amount to decrement it by.
|
||||
*/
|
||||
decr (key: string, optConfig: KVOptConfig): Promise<number>;
|
||||
decr (key: string, amount?: number | KVIncrementPath, optConfig?: KVOptConfig): Promise<number>;
|
||||
/**
|
||||
* Adds values to an existing key, returning the updated value.
|
||||
* @param value - The value to add (defaults to `1` when omitted), or an
|
||||
* object mapping dot-separated paths to the value(s) to add at each path.
|
||||
*/
|
||||
add (key: string, optConfig: KVOptConfig): Promise<KVValue>;
|
||||
add (key: string, value?: KVValue | KVAddPath, optConfig?: KVOptConfig): Promise<KVValue>;
|
||||
/**
|
||||
* Removes values from a key by one or more dot-separated paths, returning
|
||||
* the updated value.
|
||||
* @param paths - One or more dot-separated paths to remove (e.g. `"profile.bio"`).
|
||||
*/
|
||||
remove (key: string, ...paths: Array<string | KVOptConfig>): Promise<KVValue>;
|
||||
/**
|
||||
* Updates one or more paths within the value stored at a key without
|
||||
* overwriting the entire value, returning the updated value.
|
||||
* @param pathAndValueMap - Maps dot-separated paths to their new values.
|
||||
* @param ttl - Time-to-live for the key, in seconds.
|
||||
*/
|
||||
update (key: string, pathAndValueMap: KVUpdatePath, optConfig: KVOptConfig): Promise<KVValue>;
|
||||
update (key: string, pathAndValueMap: KVUpdatePath, ttlSeconds?: number, optConfig?: KVOptConfig): Promise<KVValue>;
|
||||
update (key: string, pathAndValueMap: KVUpdatePath, ttl?: number, optConfig?: KVOptConfig): Promise<KVValue>;
|
||||
update (item: KVUpdateObject): Promise<KVValue>;
|
||||
/**
|
||||
* Sets the time-to-live for a key, in seconds.
|
||||
* @param ttlSeconds - Number of seconds until the key is removed.
|
||||
* @returns `true` once the expiration has been set.
|
||||
*/
|
||||
expire (key: string, ttlSeconds: number, optConfig?: KVOptConfig): Promise<boolean>;
|
||||
/**
|
||||
* Sets the expiration timestamp for a key.
|
||||
* @param timestampSeconds - Unix timestamp, in seconds, at which the key is removed.
|
||||
* @returns `true` once the expiry time has been set.
|
||||
*/
|
||||
expireAt (key: string, timestampSeconds: number, optConfig?: KVOptConfig): Promise<boolean>;
|
||||
/**
|
||||
* Lists keys in the store for the current app, sorted lexicographically by
|
||||
* key. Returns just the keys, an array of `KVPair` objects when
|
||||
* `returnValues` is `true`, or a `KVListPage` when `limit`/`cursor` is used.
|
||||
* @param pattern - Prefix-based key filter with an optional trailing `*`
|
||||
* wildcard. Defaults to `*`, matching all keys.
|
||||
*/
|
||||
list (pattern?: string, returnValues?: false): Promise<string[]>;
|
||||
list<T = unknown>(pattern: string, returnValues: true): Promise<KVPair<T>[]>;
|
||||
list<T = unknown>(returnValues: true): Promise<KVPair<T>[]>;
|
||||
@@ -69,6 +210,10 @@ export class KV {
|
||||
list<T = unknown>(options: KVListOptions & KVListPaginationOptions & { returnValues: true }): Promise<KVListPage<KVPair<T>>>;
|
||||
list (options: KVListOptions & { returnValues?: false }): Promise<string[]>;
|
||||
list<T = unknown>(options: KVListOptions & { returnValues: true }): Promise<KVPair<T>[]>;
|
||||
/**
|
||||
* Removes all key-value pairs from the store for the current app.
|
||||
* @returns `true` once the store has been flushed.
|
||||
*/
|
||||
flush (optConfig?: KVOptConfig): Promise<boolean>;
|
||||
clear (optConfig?: KVOptConfig): Promise<boolean>;
|
||||
}
|
||||
|
||||
+43
-1
@@ -1,3 +1,4 @@
|
||||
/** Names of events emitted by a socket. Plain `PSocket` uses `'open'`, `'data'`, `'close'`, `'error'`; `PTLSSocket` uses the `'tls'`-prefixed variants. */
|
||||
export type SocketEvent =
|
||||
| 'open'
|
||||
| 'data'
|
||||
@@ -8,26 +9,67 @@ export type SocketEvent =
|
||||
| 'tlsopen'
|
||||
| 'tlsclose';
|
||||
|
||||
/**
|
||||
* A raw TCP socket usable directly in the browser.
|
||||
* Construct via `puter.net.Socket(hostname, port)`.
|
||||
*/
|
||||
export class PSocket {
|
||||
/**
|
||||
* @param host The hostname of the server to connect to (an IP address or domain name).
|
||||
* @param port The port number to connect to on the server.
|
||||
*/
|
||||
constructor (host: string, port: number);
|
||||
/** Write data to the socket. */
|
||||
write (data: ArrayBuffer | ArrayBufferView | string, callback?: () => void): void;
|
||||
/** Voluntarily close the TCP socket. */
|
||||
close (): void;
|
||||
/** `'open'` fires when the socket is initialized and ready to send data. */
|
||||
on (event: 'open', handler: () => void): void;
|
||||
/** `'data'` fires when the remote server sends data over the socket; `buffer` is the received data. */
|
||||
on (event: 'data', handler: (buffer: Uint8Array) => void): void;
|
||||
on (event: 'error', handler: (reason: string) => void): void;
|
||||
/** `'error'` fires when the socket encounters an error (a `'close'` event follows shortly after). The human-readable reason is on `error.message`. */
|
||||
on (event: 'error', handler: (error: Error) => void): void;
|
||||
/** `'close'` fires when the socket is closed; `hadError` is `true` if it closed due to an error. */
|
||||
on (event: 'close', handler: (hadError: boolean) => void): void;
|
||||
/** Register a handler for a socket event by name. */
|
||||
addListener (event: SocketEvent, handler: (...args: unknown[]) => void): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A TLS-protected TCP socket usable directly in the browser. The interface is
|
||||
* the same as `PSocket` but the connection is encrypted. Its events are
|
||||
* `'tls'`-prefixed. Construct via `puter.net.tls.TLSSocket(hostname, port)`.
|
||||
*/
|
||||
export class PTLSSocket extends PSocket {
|
||||
/**
|
||||
* @param host The hostname of the server to connect to (an IP address or domain name).
|
||||
* @param port The port number to connect to on the server.
|
||||
*/
|
||||
constructor (host: string, port: number);
|
||||
/** `'tlsopen'` fires when the socket is initialized and ready to send data. */
|
||||
on (event: 'tlsopen', handler: () => void): void;
|
||||
/** `'tlsdata'` fires when the remote server sends data over the socket; `buffer` is the received data. */
|
||||
on (event: 'tlsdata', handler: (buffer: Uint8Array) => void): void;
|
||||
/** `'tlsclose'` fires when the socket is closed; `hadError` is `true` if it closed due to an error. */
|
||||
on (event: 'tlsclose', handler: (hadError: boolean) => void): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `puter.net` networking API. Establishes network connections directly from
|
||||
* the frontend without a server or proxy, and bypasses CORS restrictions.
|
||||
*/
|
||||
export interface Networking {
|
||||
generateWispV1URL(): Promise<string>;
|
||||
/** Constructor for a raw TCP `Socket`. */
|
||||
Socket: typeof PSocket;
|
||||
tls: {
|
||||
/** Constructor for a TLS-protected `TLSSocket`. */
|
||||
TLSSocket: typeof PTLSSocket;
|
||||
};
|
||||
/**
|
||||
* Fetch an http/https resource without being bound by CORS restrictions.
|
||||
* @param init A standard `RequestInit` object.
|
||||
* @returns A `Promise` that resolves to a `Response`.
|
||||
*/
|
||||
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
|
||||
}
|
||||
|
||||
Vendored
+45
@@ -1,7 +1,10 @@
|
||||
/** Options for `puter.peer.serve()` and `puter.peer.connect()`. */
|
||||
export interface PuterPeerOptions {
|
||||
/** Custom ICE servers (STUN/TURN) to use instead of the Puter-managed relays. */
|
||||
iceServers?: RTCIceServer[];
|
||||
}
|
||||
|
||||
/** Metadata about a peer user. */
|
||||
export interface PuterPeerUser {
|
||||
username: string;
|
||||
uuid: string;
|
||||
@@ -11,21 +14,30 @@ export type PuterPeerMessage = string | Blob | ArrayBuffer | ArrayBufferView;
|
||||
export type PuterPeerDescription = RTCSessionDescription | RTCSessionDescriptionInit;
|
||||
export type PuterPeerIceCandidate = RTCIceCandidate | RTCIceCandidateInit;
|
||||
|
||||
/** Dispatched by `PuterPeerServer` for the `'connection'` event when a client connects. */
|
||||
export class PuterPeerServerConnectionEvent extends Event {
|
||||
/** The connection to the client. */
|
||||
readonly conn: PuterPeerConnection;
|
||||
/** Metadata about the connecting user (if available). */
|
||||
readonly user: PuterPeerUser;
|
||||
}
|
||||
|
||||
/** Dispatched by `PuterPeerConnection` for the `'message'` event when a message is received. */
|
||||
export class PuterPeerConnectionMessageEvent extends Event {
|
||||
/** The received message payload. */
|
||||
readonly data: ArrayBuffer | string;
|
||||
}
|
||||
|
||||
/** Dispatched by `PuterPeerConnection` for the `'open'` event when the data channel is ready. */
|
||||
export class PuterPeerConnectionOpenEvent extends Event {}
|
||||
|
||||
/** Dispatched by `PuterPeerConnection` for the `'close'` event when the connection closes. */
|
||||
export class PuterPeerConnectionCloseEvent extends Event {
|
||||
/** The reason the connection was closed, if one was provided. */
|
||||
readonly reason?: string;
|
||||
}
|
||||
|
||||
/** Dispatched by `PuterPeerConnection` for the `'error'` event when a connection error occurs. */
|
||||
export class PuterPeerConnectionErrorEvent extends Event {
|
||||
readonly error: string;
|
||||
}
|
||||
@@ -41,8 +53,14 @@ export interface PuterPeerConnectionEventMap {
|
||||
error: PuterPeerConnectionErrorEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* A peer server created by `puter.peer.serve()`. Emits a `'connection'` event
|
||||
* when a client connects.
|
||||
*/
|
||||
export class PuterPeerServer extends EventTarget {
|
||||
/** The invite code to share with other clients so they can connect. */
|
||||
inviteCode?: string;
|
||||
/** Map of all connected clients, keyed by id. */
|
||||
connections: Map<string, PuterPeerConnection>;
|
||||
|
||||
start (): Promise<string>;
|
||||
@@ -62,18 +80,25 @@ export class PuterPeerServer extends EventTarget {
|
||||
): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A WebRTC data-channel connection to a peer. Emits `'open'`, `'message'`,
|
||||
* `'close'`, and `'error'` events.
|
||||
*/
|
||||
export class PuterPeerConnection extends EventTarget {
|
||||
peerconnection: RTCPeerConnection;
|
||||
/** Information about the user who created the server. */
|
||||
owner?: PuterPeerUser;
|
||||
connected: boolean;
|
||||
closed: boolean;
|
||||
|
||||
connect (invitecode: string): Promise<void>;
|
||||
/** Close the connection, optionally providing a reason. */
|
||||
close (reason?: string): void;
|
||||
createOffer (): Promise<RTCSessionDescriptionInit>;
|
||||
createAnswer (): Promise<RTCSessionDescriptionInit>;
|
||||
setRemoteDescription (description: PuterPeerDescription): void;
|
||||
addIceCandidate (candidate: PuterPeerIceCandidate): void;
|
||||
/** Send a message to the peer. Supports `string`, `Blob`, `ArrayBuffer`, or `ArrayBufferView`. */
|
||||
send (message: PuterPeerMessage): void;
|
||||
|
||||
addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
|
||||
@@ -90,6 +115,11 @@ export class PuterPeerConnection extends EventTarget {
|
||||
): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `puter.peer` API. Provides WebRTC data channels with built-in signaling
|
||||
* and TURN relays for connecting clients directly without your own signaling
|
||||
* server. Peer connections require authentication.
|
||||
*/
|
||||
export default class Peer {
|
||||
authToken?: string | null;
|
||||
APIOrigin: string;
|
||||
@@ -97,7 +127,22 @@ export default class Peer {
|
||||
|
||||
setAuthToken (authToken: string): void;
|
||||
setAPIOrigin (APIOrigin: string): void;
|
||||
/**
|
||||
* Fetches TURN relay credentials ahead of time so peer connections start
|
||||
* faster. Optional, since `serve()` and `connect()` call it automatically
|
||||
* when needed. Resolves once relay details are cached; if relays cannot be
|
||||
* loaded, Puter.js falls back to default ICE servers when connecting.
|
||||
*/
|
||||
ensureTurnRelays (): Promise<void>;
|
||||
/**
|
||||
* Create a peer server that generates an invite code other clients can use
|
||||
* to connect.
|
||||
* @returns A `Promise` that resolves to a `PuterPeerServer`.
|
||||
*/
|
||||
serve (options?: PuterPeerOptions): Promise<PuterPeerServer>;
|
||||
/**
|
||||
* Connect to a peer server using an invite code created by `serve()`.
|
||||
* @returns A `Promise` that resolves to a `PuterPeerConnection`.
|
||||
*/
|
||||
connect (invitecode: string, options?: PuterPeerOptions): Promise<PuterPeerConnection>;
|
||||
}
|
||||
|
||||
+88
-5
@@ -1,9 +1,4 @@
|
||||
export class Perms {
|
||||
constructor (context: { authToken?: string; APIOrigin: string });
|
||||
|
||||
setAuthToken (authToken: string): void;
|
||||
setAPIOrigin (APIOrigin: string): void;
|
||||
|
||||
grantUser (username: string, permission: string): Promise<Record<string, unknown>>;
|
||||
grantGroup (groupUid: string, permission: string): Promise<Record<string, unknown>>;
|
||||
grantApp (appUid: string, permission: string): Promise<Record<string, unknown>>;
|
||||
@@ -20,4 +15,92 @@ export class Perms {
|
||||
addUsersToGroup (uid: string, usernames: string[]): Promise<Record<string, unknown>>;
|
||||
removeUsersFromGroup (uid: string, usernames: string[]): Promise<Record<string, unknown>>;
|
||||
listGroups (): Promise<Record<string, unknown>>;
|
||||
|
||||
/**
|
||||
* Request a specific permission string to be granted. Note that some
|
||||
* permission strings are not supported and will be denied silently.
|
||||
* @param permission - The permission string to request.
|
||||
* @returns `true` if the permission was granted, `false` otherwise.
|
||||
*/
|
||||
request (permission: string): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Request to see a user's email. If the permission has already been granted
|
||||
* the user will not be prompted and their email address will be returned.
|
||||
* @returns The user's email address if granted, `null` if granted but the
|
||||
* user has no email address, or `undefined` if access is denied.
|
||||
*/
|
||||
requestEmail (): Promise<string | null | undefined>;
|
||||
|
||||
/**
|
||||
* Request read access to the user's Desktop folder.
|
||||
* @returns The Desktop folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestReadDesktop (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request write access to the user's Desktop folder.
|
||||
* @returns The Desktop folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestWriteDesktop (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request read access to the user's Documents folder.
|
||||
* @returns The Documents folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestReadDocuments (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request write access to the user's Documents folder.
|
||||
* @returns The Documents folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestWriteDocuments (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request read access to the user's Pictures folder.
|
||||
* @returns The Pictures folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestReadPictures (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request write access to the user's Pictures folder.
|
||||
* @returns The Pictures folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestWritePictures (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request read access to the user's Videos folder.
|
||||
* @returns The Videos folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestReadVideos (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request write access to the user's Videos folder.
|
||||
* @returns The Videos folder path if granted, or `undefined` if denied.
|
||||
*/
|
||||
requestWriteVideos (): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
* Request read access to the user's apps.
|
||||
* @returns `true` if read access was granted, `false` otherwise.
|
||||
*/
|
||||
requestReadApps (): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Request write (manage) access to the user's apps.
|
||||
* @returns `true` if manage access was granted, `false` otherwise.
|
||||
*/
|
||||
requestManageApps (): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Request read access to the user's subdomains.
|
||||
* @returns `true` if read access was granted, `false` otherwise.
|
||||
*/
|
||||
requestReadSubdomains (): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Request write (manage) access to the user's subdomains.
|
||||
* @returns `true` if manage access was granted, `false` otherwise.
|
||||
*/
|
||||
requestManageSubdomains (): Promise<boolean>;
|
||||
}
|
||||
|
||||
Vendored
+205
-9
@@ -1,118 +1,212 @@
|
||||
import type { FSItem } from './fs-item.d.ts';
|
||||
|
||||
/** A button shown in an `alert()` dialog. */
|
||||
export interface AlertButton {
|
||||
/** Text displayed on the button. */
|
||||
label: string;
|
||||
/** Value returned when this button is pressed. Defaults to `label` if not set. */
|
||||
value?: string;
|
||||
/** Visual style of the button. */
|
||||
type?: 'primary' | 'success' | 'info' | 'warning' | 'danger';
|
||||
}
|
||||
|
||||
/** Options that configure an `alert()` dialog. */
|
||||
export interface AlertOptions {
|
||||
/** Visual style of the alert dialog. */
|
||||
type?: 'primary' | 'success' | 'info' | 'warning' | 'danger';
|
||||
/** Icon URL shown in the dialog body. Takes precedence over `icon`. */
|
||||
body_icon?: string;
|
||||
/** Icon URL shown in the dialog body, used when `body_icon` is not set. */
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export interface PromptOptions {
|
||||
defaultValue?: string;
|
||||
}
|
||||
|
||||
/** A single item in a context menu. The string `'-'` may be used in place of an item to render a separator. */
|
||||
export interface ContextMenuItem {
|
||||
/** Text displayed for the menu item. */
|
||||
label: string;
|
||||
/** Function executed when the item is clicked. Not required for items with submenus. */
|
||||
action?: () => void;
|
||||
/** Icon shown next to the label. Must be a base64-encoded image data URI starting with `data:image`; other strings are ignored. */
|
||||
icon?: string;
|
||||
/** Icon shown when the item is hovered or active. Must be a base64-encoded image data URI starting with `data:image`; other strings are ignored. */
|
||||
icon_active?: string;
|
||||
/** If `true`, the item is disabled and unclickable. Defaults to `false`. */
|
||||
disabled?: boolean;
|
||||
/** Submenu items. Specifying this creates a submenu. */
|
||||
items?: (ContextMenuItem | '-')[];
|
||||
}
|
||||
|
||||
/** A handle to a window created by `createWindow()`. */
|
||||
export interface WindowHandle {
|
||||
/** Identifier of the window, usable as the `window_id` argument to the `setWindow*` methods. */
|
||||
id: string;
|
||||
}
|
||||
|
||||
/** Identifies a window: either a window id string or a window handle returned by `createWindow()`. */
|
||||
export type WindowIdentifier = string | WindowHandle;
|
||||
|
||||
/** Options that configure a context menu. */
|
||||
export interface ContextMenuOptions {
|
||||
/** Menu items and separators. Use the string `'-'` to insert a separator. */
|
||||
items: (ContextMenuItem | '-')[];
|
||||
}
|
||||
|
||||
/** Options that configure a window created by `createWindow()`. */
|
||||
export interface WindowOptions {
|
||||
/** If `true`, the window is placed at the center of the screen. */
|
||||
center?: boolean;
|
||||
/** Content of the window. */
|
||||
content?: string;
|
||||
/** If `true`, the parent window is blocked until this window is closed. */
|
||||
disable_parent_window?: boolean;
|
||||
/** If `true`, the window has a head containing the icon and close, minimize, and maximize buttons. */
|
||||
has_head?: boolean;
|
||||
/** Height of the window in pixels. */
|
||||
height?: number;
|
||||
/** If `true`, the user can resize the window. */
|
||||
is_resizable?: boolean;
|
||||
/** If `true`, the window is represented in the taskbar. */
|
||||
show_in_taskbar?: boolean;
|
||||
/** Title of the window. */
|
||||
title?: string;
|
||||
/** Width of the window in pixels. */
|
||||
width?: number;
|
||||
}
|
||||
|
||||
/** Options that configure `launchApp()`. */
|
||||
export interface LaunchAppOptions {
|
||||
/** Name of the app to launch. If not provided, a new instance of the current app is launched. */
|
||||
name?: string;
|
||||
app_name?: string;
|
||||
/** Arguments to pass to the app. */
|
||||
args?: Record<string, unknown>;
|
||||
/** Paths of existing files to open with the launched app. */
|
||||
file_paths?: string[];
|
||||
/** `FSItem` objects to open with the launched app. */
|
||||
items?: FSItem[];
|
||||
/** A pseudonym to launch the app under. */
|
||||
pseudonym?: string;
|
||||
callback?: (connection: AppConnection) => void;
|
||||
}
|
||||
|
||||
/** Theme data delivered with the `themeChanged` event. */
|
||||
export interface ThemeData {
|
||||
palette: {
|
||||
/** Hue of the theme color. */
|
||||
primaryHue: number;
|
||||
/** Saturation of the theme color as a percentage string, including the `%` sign. */
|
||||
primarySaturation: string;
|
||||
/** Lightness of the theme color as a percentage string, including the `%` sign. */
|
||||
primaryLightness: string;
|
||||
/** Opacity of the theme color, from `0` to `1`. */
|
||||
primaryAlpha: number;
|
||||
/** CSS color value for text. */
|
||||
primaryColor: string;
|
||||
};
|
||||
}
|
||||
|
||||
/** Options that configure the menubar set by `setMenubar()`. */
|
||||
export interface MenubarOptions {
|
||||
/** Menu items and separators. Use the string `'-'` to insert a separator. */
|
||||
items: (MenuItem | '-')[];
|
||||
}
|
||||
|
||||
/** A single item in a menubar menu. The string `'-'` may be used in place of an item to render a separator. */
|
||||
export interface MenuItem {
|
||||
/** Text displayed for the menu item. */
|
||||
label: string;
|
||||
id?: string;
|
||||
/** Function executed when the item is clicked. */
|
||||
action?: () => void;
|
||||
/** Submenu items. */
|
||||
items?: (MenuItem | '-')[];
|
||||
/** URL or data URI of an icon shown next to the label. */
|
||||
icon?: string;
|
||||
/** URL or data URI of an icon shown when the item is hovered or active. Falls back to `icon` if not provided. */
|
||||
icon_active?: string;
|
||||
/** If `true`, renders a checkmark next to the item. Use for toggleable options. */
|
||||
checked?: boolean;
|
||||
/** If `true`, the item is visible but cannot be clicked. */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/** Options that configure `showOpenFilePicker()`. */
|
||||
export interface FilePickerOptions {
|
||||
/** If `true`, the user can select multiple files. Defaults to `false`. */
|
||||
multiple?: boolean;
|
||||
/**
|
||||
* MIME types or file extensions accepted by the picker. Defaults to `*\/*`.
|
||||
* For example `'image/*'`, or `['.jpg', '.png']`.
|
||||
*/
|
||||
accept?: string | string[];
|
||||
/**
|
||||
* Initial directory to open the picker in. Defaults to the user's Desktop.
|
||||
* The special prefix `%appdata%` resolves to the app's private appdata directory.
|
||||
*/
|
||||
path?: string;
|
||||
}
|
||||
|
||||
/** Options that configure `showColorPicker()`. */
|
||||
export interface ColorPickerOptions {
|
||||
/** The color initially selected when the picker opens. */
|
||||
defaultColor?: string;
|
||||
}
|
||||
|
||||
/** Options that configure `showFontPicker()`. */
|
||||
export interface FontPickerOptions {
|
||||
/** The font initially selected when the picker opens. */
|
||||
defaultFont?: string;
|
||||
}
|
||||
|
||||
/** Options that configure `showDirectoryPicker()`. */
|
||||
export interface DirectoryPickerOptions {
|
||||
/** If `true`, the user can select multiple directories. Defaults to `false`. */
|
||||
multiple?: boolean;
|
||||
}
|
||||
|
||||
/** Options that configure a notification shown by `notify()`. */
|
||||
export interface NotificationOptions {
|
||||
/** Title shown in the notification. */
|
||||
title?: string;
|
||||
/** Body text shown under the title. */
|
||||
text?: string;
|
||||
/** Icon URL or Puter icon name (for example `bell.svg`). */
|
||||
icon?: string;
|
||||
/** Visual style used to pick a default icon and accent color when no `icon` is provided. */
|
||||
type?: 'info' | 'success' | 'warning' | 'error' | 'default';
|
||||
/** Time in milliseconds before the notification auto-dismisses. Defaults to `5000`; set to `0` to keep it until dismissed. */
|
||||
duration?: number;
|
||||
/** If `true`, renders the icon as a circle. */
|
||||
round_icon?: boolean;
|
||||
/** Alias for `round_icon`. */
|
||||
roundIcon?: boolean;
|
||||
/** Optional ID to associate with the notification. */
|
||||
uid?: string;
|
||||
/** Optional value stored on the notification element. */
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
/** Data passed to the `close` handler on an `AppConnection`. */
|
||||
export interface AppConnectionCloseEvent {
|
||||
/** Instance ID of the app that closed. */
|
||||
appInstanceID: string;
|
||||
statusCode?: number;
|
||||
}
|
||||
|
||||
/** Data passed to the `connection` event handler when another app requests a connection to your app. */
|
||||
export interface ConnectionEvent {
|
||||
/** Connection to the app that initiated the request. */
|
||||
conn: AppConnection;
|
||||
/** Call `accept(value)` to accept the connection; `value` is sent back to the requester. */
|
||||
accept: (value?: unknown) => void;
|
||||
/** Call `reject(value)` to reject the connection; `value` is sent back to the requester. */
|
||||
reject: (value?: unknown) => void;
|
||||
}
|
||||
|
||||
export interface LaunchAppResult {
|
||||
launched: boolean;
|
||||
requestedAppName?: string | null;
|
||||
@@ -131,73 +225,175 @@ export interface LaunchAppResult {
|
||||
|
||||
export type CancelAwarePromise<T> = Promise<T> & { undefinedOnCancel?: Promise<T | undefined> };
|
||||
|
||||
/** Provides an interface for interaction with another app. */
|
||||
export class AppConnection {
|
||||
/** Whether the target app is using Puter.js. If not, some features of `AppConnection` are unavailable. */
|
||||
readonly usesSDK: boolean;
|
||||
readonly response?: Record<string, unknown> & {
|
||||
launchResult?: LaunchAppResult;
|
||||
};
|
||||
|
||||
/**
|
||||
* Listen to an event from the target app.
|
||||
* - `message`: the target app sent a message with `postMessage()`; the handler receives the message.
|
||||
* - `close`: the target app closed; the handler receives an object with the closed app's `appInstanceID`.
|
||||
*/
|
||||
on (eventName: 'message', handler: (message: unknown) => void): void;
|
||||
on (eventName: 'close', handler: (data: AppConnectionCloseEvent) => void): void;
|
||||
/** Remove an event listener added with `on(eventName, handler)`. */
|
||||
off (eventName: string, handler: (...args: unknown[]) => void): void;
|
||||
/** Send a message to the target app. Does nothing if the target app is not using the SDK or the connection is not open. */
|
||||
postMessage (message: unknown): void;
|
||||
/** Attempt to close the target app. An app may close apps it launched with `launchApp()`. Does nothing without permission or if already closed. */
|
||||
close (): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The UI API: tools for creating rich user interfaces and interacting with the
|
||||
* Puter desktop environment, including dialogs, window management, file pickers,
|
||||
* and desktop integration.
|
||||
*/
|
||||
export class UI {
|
||||
/**
|
||||
* Displays an alert dialog. Blocks the parent window until the user presses a button.
|
||||
* Resolves to the pressed button's `value` (or its `label` if `value` is unset).
|
||||
*/
|
||||
alert (message?: string, buttons?: AlertButton[], options?: AlertOptions): Promise<string>;
|
||||
prompt (message?: string, placeholder?: string, options?: PromptOptions): Promise<string | null>;
|
||||
/**
|
||||
* Displays a prompt dialog. Blocks the parent window until the user responds.
|
||||
* Resolves to the input value on OK, or `false` if the user cancels.
|
||||
*/
|
||||
prompt (message?: string, placeholder?: string, options?: PromptOptions): Promise<string | false>;
|
||||
/** Displays a desktop notification. Resolves to the notification UID. */
|
||||
notify (options?: NotificationOptions): Promise<string>;
|
||||
/** Presents a dialog for the user to authenticate with their Puter account. Resolves once authenticated; rejects if the user cancels. */
|
||||
authenticateWithPuter (): Promise<void>;
|
||||
/** Displays a context menu at the current cursor position. Menu item actions run when clicked. */
|
||||
contextMenu (options: ContextMenuOptions): void;
|
||||
/** Creates and displays a window. Resolves to a window handle whose `id` can be passed to the `setWindow*` methods. */
|
||||
createWindow (options?: WindowOptions): Promise<WindowHandle>;
|
||||
exit (statusCode?: number): void;
|
||||
/** Retrieves the current language/locale code from the Puter environment (e.g. `en`, `fr`, `es`, `de`). */
|
||||
getLanguage (): Promise<string>;
|
||||
/** Hides the active spinner instance. */
|
||||
hideSpinner (): void;
|
||||
/** Hides the window of the application. */
|
||||
hideWindow (): void;
|
||||
/**
|
||||
* Shows an overlay with a spinner in the center of the screen. If called
|
||||
* multiple times, only one spinner is shown until all instances are hidden.
|
||||
* @param html Custom message rendered under the spinner; accepts plain text or HTML. Defaults to `"Working..."`.
|
||||
*/
|
||||
showSpinner (html?: string): void;
|
||||
/** Shows the window of the application. */
|
||||
showWindow (): void;
|
||||
/** Presents a color picker dialog and resolves to the selected color. */
|
||||
showColorPicker (defaultColor?: string): Promise<string>;
|
||||
showColorPicker (options?: ColorPickerOptions): Promise<string>;
|
||||
/**
|
||||
* Presents a directory picker for the user's Puter cloud storage. Resolves to
|
||||
* one `FSItem` or an array of `FSItem` objects depending on selection count.
|
||||
*/
|
||||
showDirectoryPicker (options?: DirectoryPickerOptions): Promise<FSItem | FSItem[]>;
|
||||
/** Presents a font picker for previewing and selecting a font. */
|
||||
showFontPicker (defaultFont?: string): Promise<{ fontFamily: string }>;
|
||||
showFontPicker (options?: FontPickerOptions): Promise<{ fontFamily: string }>;
|
||||
/**
|
||||
* Presents a file picker for the user's Puter cloud storage. Resolves to one
|
||||
* `FSItem` or an array of `FSItem` objects depending on selection count.
|
||||
*/
|
||||
showOpenFilePicker (options?: FilePickerOptions): CancelAwarePromise<FSItem | FSItem[]>;
|
||||
/**
|
||||
* Presents a file picker for choosing where and with what name to save a file.
|
||||
* Resolves to an `FSItem` for the saved file. If the user cancels, the promise stays pending.
|
||||
* @param content Data to write. When `type` is `'url'`, a URL whose contents are saved; when `'move'` or `'copy'`, the source path of an existing file.
|
||||
* @param suggestedName Default file name to pre-fill in the dialog.
|
||||
* @param type How `content` is interpreted: `'url'`, `'move'`, or `'copy'`. Auto-detected as `'url'` when `content` is a `URL` object.
|
||||
*/
|
||||
showSaveFilePicker (
|
||||
content?: unknown,
|
||||
suggestedName?: string,
|
||||
type?: 'url' | 'move' | 'copy',
|
||||
): CancelAwarePromise<FSItem>;
|
||||
/**
|
||||
* Presents a dialog for sharing a link on various social media platforms.
|
||||
* @param url The URL to share.
|
||||
* @param message Message to prefill in the post. Only supported by some platforms.
|
||||
* @param options Dialog position; `left` and `top` both default to `0`.
|
||||
*/
|
||||
socialShare (url: string, message?: string, options?: { left?: number; top?: number }): void;
|
||||
/** Creates a menubar, a horizontal bar at the top of the window containing menus. */
|
||||
setMenubar (options: MenubarOptions): void;
|
||||
setMenuItemIcon (itemId: string, icon: string): void;
|
||||
setMenuItemIconActive (itemId: string, icon: string): void;
|
||||
setMenuItemChecked (itemId: string, checked: boolean): void;
|
||||
/**
|
||||
* Dynamically sets the window height. Minimum is `200`; smaller values are clamped to `200`.
|
||||
* @param window_id Targets a specific window; accepts a window id string or a handle from `createWindow()`. Defaults to the app's main window.
|
||||
*/
|
||||
setWindowHeight (height: number, window_id?: WindowIdentifier): void;
|
||||
/**
|
||||
* Sets the window position.
|
||||
* @param window_id Targets a specific window; accepts a window id string or a handle from `createWindow()`. Defaults to the app's main window.
|
||||
*/
|
||||
setWindowPosition (x: number, y: number, window_id?: WindowIdentifier): void;
|
||||
/**
|
||||
* Dynamically sets the window width and height. Minimum for each is `200`; smaller values are clamped to `200`.
|
||||
* @param window_id Targets a specific window; accepts a window id string or a handle from `createWindow()`. Defaults to the app's main window.
|
||||
*/
|
||||
setWindowSize (width: number, height: number, window_id?: WindowIdentifier): void;
|
||||
/**
|
||||
* Dynamically sets the window title.
|
||||
* @param window_id Targets a specific window; accepts a window id string or a handle from `createWindow()`. Defaults to the app's main window.
|
||||
*/
|
||||
setWindowTitle (title: string, window_id?: WindowIdentifier): void;
|
||||
/**
|
||||
* Dynamically sets the window width. Minimum is `200`; smaller values are clamped to `200`.
|
||||
* @param window_id Targets a specific window; accepts a window id string or a handle from `createWindow()`. Defaults to the app's main window.
|
||||
*/
|
||||
setWindowWidth (width: number, window_id?: WindowIdentifier): void;
|
||||
/**
|
||||
* Sets the window X position.
|
||||
* @param window_id Targets a specific window; accepts a window id string or a handle from `createWindow()`. Defaults to the app's main window.
|
||||
*/
|
||||
setWindowX (x: number, window_id?: WindowIdentifier): void;
|
||||
/**
|
||||
* Sets the window Y position.
|
||||
* @param window_id Targets a specific window; accepts a window id string or a handle from `createWindow()`. Defaults to the app's main window.
|
||||
*/
|
||||
setWindowY (y: number, window_id?: WindowIdentifier): void;
|
||||
/** Returns whether the app was launched to open one or more items (via double-clicking, the 'Open With...' menu, etc.). */
|
||||
wasLaunchedWithItems (): boolean;
|
||||
/** @deprecated Also fires when items are dropped on the app; new code should handle the `drop` event instead. */
|
||||
onItemsOpened (handler: (items: FSItem[]) => void): void;
|
||||
/**
|
||||
* Registers a callback invoked when the app is launched with items (via
|
||||
* double-clicking or the 'Open With...' menu). The handler receives an array
|
||||
* of items, each a file or directory.
|
||||
*/
|
||||
onLaunchedWithItems (handler: (items: FSItem[]) => void): void;
|
||||
/** Registers a function run when the window is about to close. Not called when the app exits via `puter.exit()`. */
|
||||
onWindowClose (handler: () => void): void;
|
||||
/**
|
||||
* Listen to a broadcast event from Puter. If the broadcast was received before
|
||||
* the handler was attached, the handler is called immediately with the most recent value.
|
||||
* - `localeChanged`: sent on startup and when the user's locale changes.
|
||||
* - `themeChanged`: sent on startup and when the user's desktop theme changes.
|
||||
* - `connection`: sent when another app requests a connection to your app.
|
||||
*/
|
||||
on (eventName: 'localeChanged', handler: (data: { language: string }) => void): void;
|
||||
on (eventName: 'themeChanged', handler: (data: ThemeData) => void): void;
|
||||
on (eventName: 'connection', handler: (data: ConnectionEvent) => void): void;
|
||||
/** Obtains a connection to the app that launched this app, or `null` if there is no parent app. */
|
||||
parentApp (): AppConnection | null;
|
||||
/**
|
||||
* Dynamically launches another app. If no app name is given, a new instance of
|
||||
* the current app is launched. Resolves to an `AppConnection` once launched.
|
||||
*/
|
||||
launchApp (appName?: string, args?: Record<string, unknown>, callback?: (connection: AppConnection) => void): Promise<AppConnection>;
|
||||
launchApp (options: LaunchAppOptions): Promise<AppConnection>;
|
||||
|
||||
getEntriesFromDataTransferItems (dataTransferItems: DataTransferItemList, options?: { raw?: boolean }): Promise<Array<File | FileSystemEntry>>;
|
||||
|
||||
// Broadcast helpers are only partially typed because the payloads are app-defined.
|
||||
broadcast (name: string, data: unknown): void;
|
||||
listenForBroadcast (name: string, handler: (data: unknown) => void): void;
|
||||
|
||||
get FILE_SAVE_CANCELLED (): symbol;
|
||||
get FILE_OPEN_CANCELLED (): symbol;
|
||||
|
||||
requestUpgrade (): Promise<unknown>;
|
||||
}
|
||||
|
||||
|
||||
+34
@@ -1,22 +1,56 @@
|
||||
/** Information about a deployed worker, as returned by `get()` and `list()`. */
|
||||
export interface WorkerInfo {
|
||||
/** The name of the worker. */
|
||||
name: string;
|
||||
/** The URL of the worker. */
|
||||
url: string;
|
||||
/** The file path of the worker's source code. */
|
||||
file_path: string;
|
||||
/** The unique identifier of the worker file. */
|
||||
file_uid: string;
|
||||
/** The date and time when the worker was created. */
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** The result of a worker deployment, as returned by `create()`. */
|
||||
export interface WorkerDeployment {
|
||||
/** Whether the worker deployment was successful. */
|
||||
success: boolean;
|
||||
/** The URL of the deployed worker. */
|
||||
url: string;
|
||||
/** Any errors that occurred during deployment. */
|
||||
errors?: string[];
|
||||
}
|
||||
|
||||
export class WorkersHandler {
|
||||
/**
|
||||
* Creates and deploys a new worker from a JavaScript file containing router code.
|
||||
* A worker is tied to its name: create it once, then deploy changes by overwriting
|
||||
* its source file rather than calling `create()` again. Workers cannot be larger
|
||||
* than 10MB. Requires a Puter account with a verified email address.
|
||||
*
|
||||
* @param workerName The name for the worker. May contain letters, numbers, hyphens, and underscores.
|
||||
* @param filePath The path to a JavaScript file in your Puter account that contains the router code.
|
||||
* @param appName The name of an existing app to associate the worker with. When provided, the worker is bound to that app and no sandbox app is created.
|
||||
*/
|
||||
create (workerName: string, filePath: string, appName?: string): Promise<WorkerDeployment>;
|
||||
/**
|
||||
* @param options Controls the worker's sandbox. `sandbox` defaults to `true`;
|
||||
* when `true`, a dedicated `sandbox-<workerName>` app is created (or reused) to
|
||||
* own the worker. Pass `false` to opt out.
|
||||
*/
|
||||
create (workerName: string, filePath: string, options?: { sandbox?: boolean }): Promise<WorkerDeployment>;
|
||||
/** Deletes an existing worker and stops its execution. Resolves to `true` if successful. */
|
||||
delete (workerName: string): Promise<boolean>;
|
||||
/**
|
||||
* Sends a request to a worker endpoint, automatically including the user's session
|
||||
* so the worker gets user context (`user.puter`) for the User-Pays model. Accepts the
|
||||
* same input as the Fetch API; resolves to a `Response`.
|
||||
*/
|
||||
exec (request: RequestInfo | URL, init?: RequestInit): Promise<Response>;
|
||||
/** Gets information for a specific worker, or `undefined` if it does not exist. */
|
||||
get (workerName: string): Promise<WorkerInfo | undefined>;
|
||||
/** Lists all workers in your account with their details. */
|
||||
list (): Promise<WorkerInfo[]>;
|
||||
getLoggingHandle (workerName: string): Promise<EventTarget & {
|
||||
close: () => void;
|
||||
|
||||
Reference in New Issue
Block a user