ultrafastmov 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -5
- package/dist/cjs/client.d.ts +167 -0
- package/dist/cjs/client.js +282 -0
- package/dist/cjs/errors.d.ts +102 -0
- package/dist/cjs/errors.js +163 -0
- package/dist/cjs/files.d.ts +31 -0
- package/dist/cjs/files.js +188 -0
- package/dist/cjs/http.d.ts +49 -0
- package/dist/cjs/http.js +140 -0
- package/dist/cjs/index.d.ts +13 -0
- package/dist/cjs/index.js +46 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/results.d.ts +114 -0
- package/dist/cjs/results.js +284 -0
- package/dist/cjs/runtime.d.ts +31 -0
- package/dist/cjs/runtime.js +118 -0
- package/dist/cjs/schema.d.ts +2182 -0
- package/dist/cjs/schema.js +83 -0
- package/dist/cjs/types.d.ts +199 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +22 -0
- package/dist/cjs/webhooks.js +82 -0
- package/dist/esm/client.d.ts +167 -0
- package/dist/esm/client.js +277 -0
- package/dist/esm/errors.d.ts +102 -0
- package/dist/esm/errors.js +138 -0
- package/dist/esm/files.d.ts +31 -0
- package/dist/esm/files.js +181 -0
- package/dist/esm/http.d.ts +49 -0
- package/dist/esm/http.js +136 -0
- package/dist/esm/index.d.ts +13 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/results.d.ts +114 -0
- package/dist/esm/results.js +274 -0
- package/dist/esm/runtime.d.ts +31 -0
- package/dist/esm/runtime.js +75 -0
- package/dist/esm/schema.d.ts +2182 -0
- package/dist/esm/schema.js +79 -0
- package/dist/esm/types.d.ts +199 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +22 -0
- package/dist/esm/webhooks.js +77 -0
- package/package.json +54 -7
- package/cli.js +0 -2
- package/index.js +0 -2
package/README.md
CHANGED
|
@@ -1,9 +1,134 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ultrafastmov
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
the
|
|
3
|
+
TypeScript client for ultrafast, the GPU video engine. A video is a JSON
|
|
4
|
+
document; the render service turns it into an MP4. This package talks to
|
|
5
|
+
ultrafast Cloud or your own `ultrafast serve`.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
```bash
|
|
8
|
+
npm i ultrafastmov
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { Ultrafast } from "ultrafastmov";
|
|
13
|
+
|
|
14
|
+
const uf = new Ultrafast(); // ULTRAFAST_API_KEY
|
|
15
|
+
|
|
16
|
+
const doc = await uf.load("film.json");
|
|
17
|
+
const sheet = await uf.sheet(doc, { count: 9 });
|
|
18
|
+
const job = await uf.render(doc, {
|
|
19
|
+
webhook: "https://example.com/rendered",
|
|
20
|
+
});
|
|
21
|
+
console.log(job.id, job.status);
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Node 18 or later, no dependencies. ESM and CommonJS.
|
|
25
|
+
|
|
26
|
+
## Your own server
|
|
27
|
+
|
|
28
|
+
`ultrafast serve` is the open-source render service for one machine with a
|
|
29
|
+
GPU.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
export ULTRAFAST_BASE_URL=http://localhost:8080
|
|
33
|
+
export ULTRAFAST_API_KEY=... # the server's key (it prints one at first start)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
or `new Ultrafast({ baseUrl: "http://localhost:8080", apiKey })`. Without
|
|
37
|
+
`ULTRAFAST_BASE_URL` the client uses ultrafast Cloud,
|
|
38
|
+
`https://api.ultrafast.mov`.
|
|
39
|
+
|
|
40
|
+
Everything here works against it except what only ultrafast Cloud has:
|
|
41
|
+
jobs and webhooks (`{ job }`, `{ webhook }`, `uf.jobs`), `{ uri }` output
|
|
42
|
+
to your own bucket, and `gs://`, `s3://` or `r2://` inputs. Those throw
|
|
43
|
+
`CloudOnlyError` (`e.feature` says which).
|
|
44
|
+
|
|
45
|
+
## Methods
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
const doc = await uf.new("vertical"); // a starter document; names from uf.templates()
|
|
49
|
+
|
|
50
|
+
const frame = await uf.frame(doc, { at: 2.5 }); // Image: bytes, contentType, save(), toBase64()
|
|
51
|
+
await (await uf.sheet(doc, { count: 9 })).save("sheet.png");
|
|
52
|
+
|
|
53
|
+
const { ok, issues } = await uf.check(doc);
|
|
54
|
+
for (const issue of await uf.review(doc, { safe: "social" })) {
|
|
55
|
+
console.log(issue.kind, issue.node, issue.from, issue.to, issue.message);
|
|
56
|
+
}
|
|
57
|
+
console.log(`${await uf.estimate(doc)}`); // $0.004, 8 s of 1080p
|
|
58
|
+
|
|
59
|
+
const render = await uf.render(doc); // stored; render.url is signed
|
|
60
|
+
await render.save("film.mp4"); // streamed, sha256 checked
|
|
61
|
+
const short = await uf.render(doc, { inline: true, range: [0, 3] });
|
|
62
|
+
|
|
63
|
+
const job = await uf.render(doc, { job: true }); // or { webhook } (Cloud)
|
|
64
|
+
const done = await job.wait(); // polls; throws the job's error if it failed
|
|
65
|
+
await uf.jobs.get(job.id);
|
|
66
|
+
|
|
67
|
+
const asset = await uf.upload("interview.mp4"); // or a Blob, File or bytes
|
|
68
|
+
// "src": asset.uri
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Every method that takes a document also takes the path of one.
|
|
72
|
+
|
|
73
|
+
## Local files
|
|
74
|
+
|
|
75
|
+
Documents can name local files: `"src": "footage/a.mp4"`, a font file, a
|
|
76
|
+
logo. Before sending a document the client uploads each one (once per
|
|
77
|
+
client, while its size and mtime stay the same) and sends a copy with
|
|
78
|
+
`asset://` references in their place; your object is not changed. Paths
|
|
79
|
+
resolve against the document's directory when it came from `uf.load`
|
|
80
|
+
(spread copies keep it), else the working directory. Font family names (`"Inter"`), inline face tracks
|
|
81
|
+
and `asset://`, `https://`, `data:` and (on Cloud) `gs://`, `s3://`, `r2://` values are
|
|
82
|
+
sent as they are. `uf.prepare(doc)` returns the copy without rendering.
|
|
83
|
+
|
|
84
|
+
Reading files needs Node. In edge runtimes, pass documents as objects whose
|
|
85
|
+
media are already references.
|
|
86
|
+
|
|
87
|
+
## Webhooks (Cloud)
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
import { verifyWebhook } from "ultrafastmov";
|
|
91
|
+
|
|
92
|
+
const { webhook_secret } = await uf.me();
|
|
93
|
+
|
|
94
|
+
// in your handler, with the raw body:
|
|
95
|
+
const job = await verifyWebhook(rawBody, req.headers["ultrafast-signature"], webhook_secret);
|
|
96
|
+
if (job.status === "rendered") console.log(job.receipt?.url);
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
It checks the HMAC over the raw bytes and refuses deliveries whose
|
|
100
|
+
`sent_at` is more than 5 minutes off (`{ toleranceSec }`). It uses Web
|
|
101
|
+
Crypto, so it runs in Node and edge runtimes alike.
|
|
102
|
+
|
|
103
|
+
## Errors
|
|
104
|
+
|
|
105
|
+
Failures throw `UltrafastError` (or a subclass per API error code, such as
|
|
106
|
+
`InvalidDocumentError` with `issues`, `BusyError`, `OverLimitError`,
|
|
107
|
+
`CloudOnlyError` with `feature`), with
|
|
108
|
+
`status`, `code`, `message`, `retry` and the server's `body`. Requests the
|
|
109
|
+
server refused with `retry: true` (429, 503) are retried with backoff;
|
|
110
|
+
reads and other repeatable requests are also retried after a dropped
|
|
111
|
+
connection. A render is only resent after a dropped connection when it
|
|
112
|
+
writes to an `output.uri`, where the request's `attempt` ids make the
|
|
113
|
+
retry a replay.
|
|
114
|
+
|
|
115
|
+
A synchronous render holds the request open until the video is written,
|
|
116
|
+
and Node's fetch stops waiting for response headers after 5 minutes: on
|
|
117
|
+
Cloud, use a job for long renders.
|
|
118
|
+
|
|
119
|
+
## Types
|
|
120
|
+
|
|
121
|
+
`Document`, `Format`, `Node` (a union over `op` with each op's params),
|
|
122
|
+
`ParamsOf<"text">` and the animated forms (`keys`, `expr`, `wiggle`,
|
|
123
|
+
`oscillate`, `audio`) are generated from the document schema,
|
|
124
|
+
https://ultrafast.mov/schema/v1.json, by `scripts/gen-types.mjs`.
|
|
125
|
+
|
|
126
|
+
## Development
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
npm install
|
|
130
|
+
npm test # builds, typechecks, runs the tests against an in-process fake server
|
|
131
|
+
npm run gen # regenerates src/schema.ts from schema/v1.json
|
|
132
|
+
```
|
|
8
133
|
|
|
9
134
|
Licensed under Apache-2.0 OR MIT.
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { type FetchLike, Transport } from "./http.js";
|
|
2
|
+
import { Estimate, Image, Job, Render, Review } from "./results.js";
|
|
3
|
+
import type { Document } from "./schema.js";
|
|
4
|
+
import type { Asset, Attempt, CheckResult, Health, Me } from "./types.js";
|
|
5
|
+
export declare const DEFAULT_BASE_URL = "https://api.ultrafast.mov";
|
|
6
|
+
export interface UltrafastOptions {
|
|
7
|
+
/** Default: `ULTRAFAST_API_KEY`. */
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/** Default: `ULTRAFAST_BASE_URL`, else ultrafast Cloud. A self-hosted server: `http://localhost:8080`. */
|
|
10
|
+
baseUrl?: string;
|
|
11
|
+
/** A fetch implementation (default: the global one). */
|
|
12
|
+
fetch?: FetchLike;
|
|
13
|
+
/** Retries of requests that are safe to repeat (default 2). */
|
|
14
|
+
maxRetries?: number;
|
|
15
|
+
/** Extra headers on every request. */
|
|
16
|
+
headers?: Record<string, string>;
|
|
17
|
+
}
|
|
18
|
+
/** A document, or the path of a document file (Node). */
|
|
19
|
+
export type DocumentInput = Document | string;
|
|
20
|
+
export interface RenderOptions {
|
|
21
|
+
/** The mp4 in the response (at most 32 MiB) instead of stored with a signed URL. */
|
|
22
|
+
inline?: boolean;
|
|
23
|
+
/** Create the video at this object in your own bucket (`s3://`, `r2://`, `gs://`); create-only. */
|
|
24
|
+
uri?: string;
|
|
25
|
+
/** The stored file's name (default `film.mp4`). */
|
|
26
|
+
name?: string;
|
|
27
|
+
codec?: "h264" | "hevc";
|
|
28
|
+
/** Bits per second; null for the format's default. */
|
|
29
|
+
bitrate?: number | null;
|
|
30
|
+
/** Mix the document's sound (default true). */
|
|
31
|
+
audio?: boolean;
|
|
32
|
+
/** `[from, to]` seconds of the document (default all of it). */
|
|
33
|
+
range?: [number, number] | null;
|
|
34
|
+
/** Ids that make retries safe; one is made up per call when missing. */
|
|
35
|
+
attempt?: Attempt;
|
|
36
|
+
/** The server stops when this passes (at most 10 minutes from receipt). */
|
|
37
|
+
deadline?: Date | string;
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
export interface JobOptions extends Omit<RenderOptions, "inline"> {
|
|
41
|
+
/** POSTed the finished job, signed (see `verifyWebhook`). */
|
|
42
|
+
webhook?: string;
|
|
43
|
+
/** A job without a webhook: poll it with `job.wait()`. */
|
|
44
|
+
job?: boolean;
|
|
45
|
+
}
|
|
46
|
+
export interface FrameOptions {
|
|
47
|
+
/** Seconds (default 0). */
|
|
48
|
+
at?: number;
|
|
49
|
+
format?: "png" | "jpeg";
|
|
50
|
+
signal?: AbortSignal;
|
|
51
|
+
}
|
|
52
|
+
export interface SheetOptions {
|
|
53
|
+
/** Frames spread evenly over the document (default 9). */
|
|
54
|
+
count?: number;
|
|
55
|
+
/** Times in seconds, instead of `count`. */
|
|
56
|
+
at?: number[];
|
|
57
|
+
/** Frames per row (default 3, or 5 for a vertical document). */
|
|
58
|
+
columns?: number;
|
|
59
|
+
format?: "png" | "jpeg";
|
|
60
|
+
signal?: AbortSignal;
|
|
61
|
+
}
|
|
62
|
+
export interface ReviewOptions {
|
|
63
|
+
/** `margin` (default, 4% of the frame) or `social` (clear of short-video apps' buttons and captions). */
|
|
64
|
+
safe?: "margin" | "social";
|
|
65
|
+
/** Seconds between text probes. */
|
|
66
|
+
step?: number;
|
|
67
|
+
signal?: AbortSignal;
|
|
68
|
+
}
|
|
69
|
+
export interface UploadOptions {
|
|
70
|
+
filename?: string;
|
|
71
|
+
contentType?: string;
|
|
72
|
+
signal?: AbortSignal;
|
|
73
|
+
}
|
|
74
|
+
/** Something to upload: a file path (Node), a Blob or File, or bytes. */
|
|
75
|
+
export type UploadInput = string | Blob | Uint8Array | ArrayBuffer;
|
|
76
|
+
/** The jobs API. */
|
|
77
|
+
export declare class Jobs {
|
|
78
|
+
#private;
|
|
79
|
+
/** @internal */
|
|
80
|
+
constructor(client: Ultrafast, transport: Transport);
|
|
81
|
+
/** Starts a job (`POST /v1/jobs`). */
|
|
82
|
+
create(doc: DocumentInput, opts?: JobOptions): Promise<Job>;
|
|
83
|
+
get(id: string, opts?: {
|
|
84
|
+
signal?: AbortSignal;
|
|
85
|
+
}): Promise<Job>;
|
|
86
|
+
/** The caller's jobs, most recent first. */
|
|
87
|
+
list(opts?: {
|
|
88
|
+
limit?: number;
|
|
89
|
+
signal?: AbortSignal;
|
|
90
|
+
}): Promise<Job[]>;
|
|
91
|
+
/** Cancels a queued job. */
|
|
92
|
+
cancel(id: string): Promise<Job>;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* A client of the ultrafast render service: ultrafast Cloud, or your own
|
|
96
|
+
* `ultrafast serve`.
|
|
97
|
+
*
|
|
98
|
+
* ```ts
|
|
99
|
+
* const uf = new Ultrafast(); // ULTRAFAST_API_KEY
|
|
100
|
+
* const doc = await uf.load("film.json");
|
|
101
|
+
* await (await uf.render(doc)).save("film.mp4");
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
export declare class Ultrafast {
|
|
105
|
+
#private;
|
|
106
|
+
readonly baseUrl: string;
|
|
107
|
+
readonly jobs: Jobs;
|
|
108
|
+
constructor(opts?: UltrafastOptions);
|
|
109
|
+
/**
|
|
110
|
+
* Reads a document file (Node). Its relative paths resolve against its
|
|
111
|
+
* directory, kept under a symbol key: copies made with spread or
|
|
112
|
+
* `Object.assign` keep it, JSON does not see it.
|
|
113
|
+
*/
|
|
114
|
+
load(path: string | URL): Promise<Document>;
|
|
115
|
+
/** A starter document: `vertical`, `title`, `square`, `promo`, `explainer`, ... (see `templates()`). */
|
|
116
|
+
new(template: string, opts?: {
|
|
117
|
+
signal?: AbortSignal;
|
|
118
|
+
}): Promise<Document>;
|
|
119
|
+
/** The names `new()` takes. */
|
|
120
|
+
templates(opts?: {
|
|
121
|
+
signal?: AbortSignal;
|
|
122
|
+
}): Promise<string[]>;
|
|
123
|
+
/**
|
|
124
|
+
* The document as it is sent: local files it names uploaded (once per
|
|
125
|
+
* client) and replaced by their asset:// uris, in a copy.
|
|
126
|
+
*/
|
|
127
|
+
prepare(doc: DocumentInput): Promise<Document>;
|
|
128
|
+
/** A video: a `Render` (stored, or `inline`), or with `webhook` or `job: true`, a `Job`. */
|
|
129
|
+
render(doc: DocumentInput, opts: JobOptions & ({
|
|
130
|
+
webhook: string;
|
|
131
|
+
} | {
|
|
132
|
+
job: true;
|
|
133
|
+
})): Promise<Job>;
|
|
134
|
+
render(doc: DocumentInput, opts?: RenderOptions & {
|
|
135
|
+
webhook?: undefined;
|
|
136
|
+
job?: false;
|
|
137
|
+
}): Promise<Render>;
|
|
138
|
+
render(doc: DocumentInput, opts?: (RenderOptions & {
|
|
139
|
+
webhook?: undefined;
|
|
140
|
+
job?: false;
|
|
141
|
+
}) | (JobOptions & {
|
|
142
|
+
inline?: undefined;
|
|
143
|
+
})): Promise<Render | Job>;
|
|
144
|
+
/** One frame, at `at` seconds. */
|
|
145
|
+
frame(doc: DocumentInput, opts?: FrameOptions): Promise<Image>;
|
|
146
|
+
/** A contact sheet: `count` frames over the film, or the times in `at`, each labeled with its time. */
|
|
147
|
+
sheet(doc: DocumentInput, opts?: SheetOptions): Promise<Image>;
|
|
148
|
+
/** Static and render-time problems, as `ultrafast check` reports them. */
|
|
149
|
+
check(doc: DocumentInput, opts?: {
|
|
150
|
+
signal?: AbortSignal;
|
|
151
|
+
}): Promise<CheckResult>;
|
|
152
|
+
/** Renders the film and reports what a viewer would trip on. */
|
|
153
|
+
review(doc: DocumentInput, opts?: ReviewOptions): Promise<Review>;
|
|
154
|
+
/** What rendering will cost (free). */
|
|
155
|
+
estimate(doc: DocumentInput, opts?: {
|
|
156
|
+
range?: [number, number] | null;
|
|
157
|
+
signal?: AbortSignal;
|
|
158
|
+
}): Promise<Estimate>;
|
|
159
|
+
/** Uploads footage, an image, a font or audio; use the asset's `uri` in a document. */
|
|
160
|
+
upload(input: UploadInput, opts?: UploadOptions): Promise<Asset>;
|
|
161
|
+
/** An upload by id. */
|
|
162
|
+
asset(id: string): Promise<Asset>;
|
|
163
|
+
/** Who the key belongs to, and the webhook secret. */
|
|
164
|
+
me(): Promise<Me>;
|
|
165
|
+
/** The server's health (no key needed). */
|
|
166
|
+
health(): Promise<Health>;
|
|
167
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Ultrafast = exports.Jobs = exports.DEFAULT_BASE_URL = void 0;
|
|
4
|
+
const errors_js_1 = require("./errors.js");
|
|
5
|
+
const files_js_1 = require("./files.js");
|
|
6
|
+
const http_js_1 = require("./http.js");
|
|
7
|
+
const results_js_1 = require("./results.js");
|
|
8
|
+
const runtime_js_1 = require("./runtime.js");
|
|
9
|
+
exports.DEFAULT_BASE_URL = "https://api.ultrafast.mov";
|
|
10
|
+
function compact(o) {
|
|
11
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
12
|
+
}
|
|
13
|
+
function parseJson(v) {
|
|
14
|
+
if (!v)
|
|
15
|
+
return undefined;
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(v);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** The jobs API. */
|
|
24
|
+
class Jobs {
|
|
25
|
+
#client;
|
|
26
|
+
#transport;
|
|
27
|
+
/** @internal */
|
|
28
|
+
constructor(client, transport) {
|
|
29
|
+
this.#client = client;
|
|
30
|
+
this.#transport = transport;
|
|
31
|
+
}
|
|
32
|
+
/** Starts a job (`POST /v1/jobs`). */
|
|
33
|
+
async create(doc, opts = {}) {
|
|
34
|
+
return this.#client.render(doc, { ...opts, job: true });
|
|
35
|
+
}
|
|
36
|
+
async get(id, opts = {}) {
|
|
37
|
+
const data = await this.#transport.json({ path: `/v1/jobs/${encodeURIComponent(id)}`, signal: opts.signal });
|
|
38
|
+
return new results_js_1.Job(this.#transport, data);
|
|
39
|
+
}
|
|
40
|
+
/** The caller's jobs, most recent first. */
|
|
41
|
+
async list(opts = {}) {
|
|
42
|
+
const { jobs } = await this.#transport.json({
|
|
43
|
+
path: "/v1/jobs",
|
|
44
|
+
query: { limit: opts.limit },
|
|
45
|
+
signal: opts.signal,
|
|
46
|
+
});
|
|
47
|
+
return jobs.map((j) => new results_js_1.Job(this.#transport, j));
|
|
48
|
+
}
|
|
49
|
+
/** Cancels a queued job. */
|
|
50
|
+
async cancel(id) {
|
|
51
|
+
const data = await this.#transport.json({ method: "DELETE", path: `/v1/jobs/${encodeURIComponent(id)}` });
|
|
52
|
+
return new results_js_1.Job(this.#transport, data);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
exports.Jobs = Jobs;
|
|
56
|
+
/**
|
|
57
|
+
* A client of the ultrafast render service: ultrafast Cloud, or your own
|
|
58
|
+
* `ultrafast serve`.
|
|
59
|
+
*
|
|
60
|
+
* ```ts
|
|
61
|
+
* const uf = new Ultrafast(); // ULTRAFAST_API_KEY
|
|
62
|
+
* const doc = await uf.load("film.json");
|
|
63
|
+
* await (await uf.render(doc)).save("film.mp4");
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
class Ultrafast {
|
|
67
|
+
baseUrl;
|
|
68
|
+
jobs;
|
|
69
|
+
#transport;
|
|
70
|
+
#uploads = new Map();
|
|
71
|
+
#active = 0;
|
|
72
|
+
#waiting = [];
|
|
73
|
+
constructor(opts = {}) {
|
|
74
|
+
const f = opts.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
75
|
+
if (!f)
|
|
76
|
+
throw new errors_js_1.UltrafastError("no fetch in this runtime: pass new Ultrafast({ fetch })", { code: "connection_error" });
|
|
77
|
+
this.baseUrl = (opts.baseUrl ?? (0, runtime_js_1.env)("ULTRAFAST_BASE_URL") ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
78
|
+
this.#transport = new http_js_1.Transport({
|
|
79
|
+
apiKey: opts.apiKey ?? (0, runtime_js_1.env)("ULTRAFAST_API_KEY"),
|
|
80
|
+
baseUrl: this.baseUrl,
|
|
81
|
+
fetch: f,
|
|
82
|
+
maxRetries: opts.maxRetries ?? 2,
|
|
83
|
+
headers: opts.headers,
|
|
84
|
+
});
|
|
85
|
+
this.jobs = new Jobs(this, this.#transport);
|
|
86
|
+
}
|
|
87
|
+
// --- documents ----------------------------------------------------------
|
|
88
|
+
/**
|
|
89
|
+
* Reads a document file (Node). Its relative paths resolve against its
|
|
90
|
+
* directory, kept under a symbol key: copies made with spread or
|
|
91
|
+
* `Object.assign` keep it, JSON does not see it.
|
|
92
|
+
*/
|
|
93
|
+
async load(path) {
|
|
94
|
+
const n = await (0, runtime_js_1.node)("load()");
|
|
95
|
+
const file = typeof path === "string" ? n.path.resolve(path) : n.url.fileURLToPath(path);
|
|
96
|
+
const doc = JSON.parse(await n.fsp.readFile(file, "utf8"));
|
|
97
|
+
Object.defineProperty(doc, files_js_1.BASE_DIR, { value: n.path.dirname(file), enumerable: true });
|
|
98
|
+
return doc;
|
|
99
|
+
}
|
|
100
|
+
/** A starter document: `vertical`, `title`, `square`, `promo`, `explainer`, ... (see `templates()`). */
|
|
101
|
+
async new(template, opts = {}) {
|
|
102
|
+
return this.#transport.json({ path: `/v1/templates/${encodeURIComponent(template)}`, signal: opts.signal });
|
|
103
|
+
}
|
|
104
|
+
/** The names `new()` takes. */
|
|
105
|
+
async templates(opts = {}) {
|
|
106
|
+
const body = await this.#transport.json({ path: "/v1/templates", signal: opts.signal });
|
|
107
|
+
const list = Array.isArray(body) ? body : (body?.templates ?? []);
|
|
108
|
+
return list.map((t) => (typeof t === "string" ? t : String(t.name)));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The document as it is sent: local files it names uploaded (once per
|
|
112
|
+
* client) and replaced by their asset:// uris, in a copy.
|
|
113
|
+
*/
|
|
114
|
+
async prepare(doc) {
|
|
115
|
+
const d = typeof doc === "string" ? await this.load(doc) : doc;
|
|
116
|
+
return (0, files_js_1.rewriteLocalFiles)(d, (file) => this.#uploadCached(file));
|
|
117
|
+
}
|
|
118
|
+
async render(doc, opts = {}) {
|
|
119
|
+
const asJob = opts.webhook !== undefined || opts.job === true;
|
|
120
|
+
if (asJob && opts.inline) {
|
|
121
|
+
throw new errors_js_1.BadRequestError("a job cannot be inline: drop `inline`, or render without `webhook` and `job`", { code: "bad_request" });
|
|
122
|
+
}
|
|
123
|
+
const document = await this.prepare(doc);
|
|
124
|
+
const output = compact({
|
|
125
|
+
inline: opts.inline,
|
|
126
|
+
uri: opts.uri,
|
|
127
|
+
name: opts.name,
|
|
128
|
+
codec: opts.codec,
|
|
129
|
+
bitrate: opts.bitrate,
|
|
130
|
+
audio: opts.audio,
|
|
131
|
+
range: opts.range,
|
|
132
|
+
});
|
|
133
|
+
const body = compact({
|
|
134
|
+
document,
|
|
135
|
+
output,
|
|
136
|
+
attempt: opts.attempt ?? { render_id: (0, runtime_js_1.randomId)("render_"), attempt_id: (0, runtime_js_1.randomId)("attempt_", 12) },
|
|
137
|
+
deadline: opts.deadline instanceof Date ? opts.deadline.toISOString() : opts.deadline,
|
|
138
|
+
webhook: opts.webhook,
|
|
139
|
+
});
|
|
140
|
+
if (asJob) {
|
|
141
|
+
// A resent job request would start a second job: retry only what the server refused.
|
|
142
|
+
const data = await this.#transport.json({ path: "/v1/jobs", json: body, retry: "unsent", signal: opts.signal });
|
|
143
|
+
return new results_js_1.Job(this.#transport, data);
|
|
144
|
+
}
|
|
145
|
+
const res = await this.#transport.request({
|
|
146
|
+
path: "/v1/render",
|
|
147
|
+
json: body,
|
|
148
|
+
accept: opts.inline ? "video/mp4, application/json" : "application/json",
|
|
149
|
+
// With `uri` a retry is a replay (409 with the stored receipt); without
|
|
150
|
+
// it a resent render could render twice, so only what the server refused.
|
|
151
|
+
retry: opts.uri ? "safe" : "unsent",
|
|
152
|
+
pass: [409],
|
|
153
|
+
signal: opts.signal,
|
|
154
|
+
});
|
|
155
|
+
if (res.status === 409) {
|
|
156
|
+
const text = await res.text();
|
|
157
|
+
const parsed = parseJson(text);
|
|
158
|
+
if (parsed && "receipt_version" in parsed)
|
|
159
|
+
return new results_js_1.Render(this.#transport, parsed);
|
|
160
|
+
throw (0, errors_js_1.errorFromResponse)(409, text);
|
|
161
|
+
}
|
|
162
|
+
const type = res.headers.get("content-type") ?? "";
|
|
163
|
+
if (type.startsWith("video/") || type === "application/octet-stream") {
|
|
164
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
165
|
+
const receipt = (parseJson(res.headers.get("x-ultrafast-receipt")) ?? { receipt_version: 1, status: "rendered" });
|
|
166
|
+
receipt.sha256 ??= res.headers.get("x-ultrafast-sha256") ?? undefined;
|
|
167
|
+
return new results_js_1.Render(this.#transport, receipt, bytes);
|
|
168
|
+
}
|
|
169
|
+
return new results_js_1.Render(this.#transport, (await res.json()));
|
|
170
|
+
}
|
|
171
|
+
async #image(path, body, signal) {
|
|
172
|
+
const res = await this.#transport.request({ path, json: compact(body), accept: "image/png, image/jpeg", signal });
|
|
173
|
+
return new results_js_1.Image(new Uint8Array(await res.arrayBuffer()), res.headers.get("content-type")?.split(";")[0] ?? "image/png", parseJson(res.headers.get("x-ultrafast-receipt")));
|
|
174
|
+
}
|
|
175
|
+
/** One frame, at `at` seconds. */
|
|
176
|
+
async frame(doc, opts = {}) {
|
|
177
|
+
const document = await this.prepare(doc);
|
|
178
|
+
return this.#image("/v1/frame", { document, at: opts.at ?? 0, format: opts.format }, opts.signal);
|
|
179
|
+
}
|
|
180
|
+
/** A contact sheet: `count` frames over the film, or the times in `at`, each labeled with its time. */
|
|
181
|
+
async sheet(doc, opts = {}) {
|
|
182
|
+
const document = await this.prepare(doc);
|
|
183
|
+
return this.#image("/v1/sheet", { document, count: opts.count, at: opts.at, columns: opts.columns, format: opts.format }, opts.signal);
|
|
184
|
+
}
|
|
185
|
+
/** Static and render-time problems, as `ultrafast check` reports them. */
|
|
186
|
+
async check(doc, opts = {}) {
|
|
187
|
+
const document = await this.prepare(doc);
|
|
188
|
+
try {
|
|
189
|
+
return await this.#transport.json({ path: "/v1/check", json: { document }, signal: opts.signal });
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
if (e instanceof errors_js_1.InvalidDocumentError)
|
|
193
|
+
return { ok: false, issues: e.issues ?? [] };
|
|
194
|
+
throw e;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/** Renders the film and reports what a viewer would trip on. */
|
|
198
|
+
async review(doc, opts = {}) {
|
|
199
|
+
const document = await this.prepare(doc);
|
|
200
|
+
const data = await this.#transport.json({
|
|
201
|
+
path: "/v1/review",
|
|
202
|
+
json: compact({ document, safe: opts.safe, step: opts.step }),
|
|
203
|
+
signal: opts.signal,
|
|
204
|
+
});
|
|
205
|
+
return new results_js_1.Review(data);
|
|
206
|
+
}
|
|
207
|
+
/** What rendering will cost (free). */
|
|
208
|
+
async estimate(doc, opts = {}) {
|
|
209
|
+
const document = await this.prepare(doc);
|
|
210
|
+
const data = await this.#transport.json({
|
|
211
|
+
path: "/v1/estimate",
|
|
212
|
+
json: { document, range: opts.range ?? null },
|
|
213
|
+
signal: opts.signal,
|
|
214
|
+
});
|
|
215
|
+
return new results_js_1.Estimate(data);
|
|
216
|
+
}
|
|
217
|
+
// --- assets -------------------------------------------------------------
|
|
218
|
+
/** Uploads footage, an image, a font or audio; use the asset's `uri` in a document. */
|
|
219
|
+
async upload(input, opts = {}) {
|
|
220
|
+
if (typeof input === "string") {
|
|
221
|
+
const n = await (0, runtime_js_1.node)("upload(path)");
|
|
222
|
+
const file = n.path.resolve(input);
|
|
223
|
+
const stat = await n.fsp.stat(file);
|
|
224
|
+
const filename = opts.filename ?? n.path.basename(file);
|
|
225
|
+
return this.#send(() => n.stream.Readable.toWeb(n.fs.createReadStream(file)), filename, opts.contentType ?? (0, runtime_js_1.contentTypeFor)(filename), stat.size, opts.signal);
|
|
226
|
+
}
|
|
227
|
+
const isBlob = typeof Blob !== "undefined" && input instanceof Blob;
|
|
228
|
+
const filename = opts.filename ?? (isBlob && "name" in input && typeof input.name === "string" && input.name ? input.name : "upload");
|
|
229
|
+
const contentType = opts.contentType ?? ((isBlob && input.type) || (0, runtime_js_1.contentTypeFor)(filename));
|
|
230
|
+
const body = isBlob ? input : input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
231
|
+
const size = isBlob ? input.size : input.byteLength;
|
|
232
|
+
return this.#send(() => body, filename, contentType, size, opts.signal);
|
|
233
|
+
}
|
|
234
|
+
#send(body, filename, contentType, size, signal) {
|
|
235
|
+
return this.#transport.json({
|
|
236
|
+
path: "/v1/uploads",
|
|
237
|
+
query: { filename },
|
|
238
|
+
body,
|
|
239
|
+
headers: { "content-type": contentType, "content-length": String(size) },
|
|
240
|
+
signal,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
/** An upload by id. */
|
|
244
|
+
async asset(id) {
|
|
245
|
+
return this.#transport.json({ path: `/v1/uploads/${encodeURIComponent(id)}` });
|
|
246
|
+
}
|
|
247
|
+
/** Uploads a document's local file once per client, keyed by path, size and mtime; four at a time. */
|
|
248
|
+
async #uploadCached(file) {
|
|
249
|
+
const n = await (0, runtime_js_1.node)();
|
|
250
|
+
const st = await n.fsp.stat(file);
|
|
251
|
+
const key = `${file}\0${st.size}\0${st.mtimeMs}`;
|
|
252
|
+
let p = this.#uploads.get(key);
|
|
253
|
+
if (!p) {
|
|
254
|
+
p = this.#limit(() => this.upload(file));
|
|
255
|
+
this.#uploads.set(key, p);
|
|
256
|
+
p.catch(() => this.#uploads.delete(key));
|
|
257
|
+
}
|
|
258
|
+
return p;
|
|
259
|
+
}
|
|
260
|
+
async #limit(fn) {
|
|
261
|
+
while (this.#active >= 4)
|
|
262
|
+
await new Promise((r) => this.#waiting.push(r));
|
|
263
|
+
this.#active++;
|
|
264
|
+
try {
|
|
265
|
+
return await fn();
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
this.#active--;
|
|
269
|
+
this.#waiting.shift()?.();
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
// --- account ------------------------------------------------------------
|
|
273
|
+
/** Who the key belongs to, and the webhook secret. */
|
|
274
|
+
async me() {
|
|
275
|
+
return this.#transport.json({ path: "/v1/me" });
|
|
276
|
+
}
|
|
277
|
+
/** The server's health (no key needed). */
|
|
278
|
+
async health() {
|
|
279
|
+
return this.#transport.json({ path: "/v1/health", pass: [503] });
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
exports.Ultrafast = Ultrafast;
|