@altenginenet/sdk 0.0.0-stage → 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 altlimit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,430 @@
1
- # Temporary Holding Version
1
+ # @altenginenet/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official JavaScript/TypeScript SDK for [altengine](https://www.altengine.net) —
4
+ managed **datastore**, **search**, realtime **channels**, **blob** storage,
5
+ **containers**, **mailboxes** and **task queues** behind one API key. Zero dependencies, fetch-based, works in
6
+ Node ≥20, browsers, and edge runtimes.
7
+
8
+ Install the SDK in your project:
9
+
10
+ ```bash
11
+ npm install @altenginenet/sdk
12
+ ```
13
+
14
+ To install from the development checkout, run
15
+
16
+ ```bash
17
+ git clone https://github.com/altlimit/altengine
18
+ cd altengine/js && npm install && npm run build
19
+ ```
20
+
21
+ ## Your first datastore write
22
+
23
+ From a checkout, build the SDK as shown above and start the emulator with
24
+ `altengine dev` in a second terminal. Run the example from the `js` directory:
25
+
26
+ ```bash
27
+ ALTENGINE_URL=http://127.0.0.1:9191 ALTENGINE_API_KEY=dev ALTENGINE_DATASTORE=demo node examples/first-write.mjs
28
+ ```
29
+
30
+ It prints `first-write Hello from AltEngine` after reading back the document.
31
+ Rerunning it updates the same key in the `sdk-quickstart` namespace.
32
+
33
+ To run against hosted AltEngine, create a datastore instance and grant a project
34
+ API key read and write access to it. Set `ALTENGINE_DATASTORE` to the instance
35
+ name and supply `ALTENGINE_API_KEY` through your server's secret configuration.
36
+ Leave `ALTENGINE_URL` unset to use the production endpoint. From a server-side
37
+ Node project with the release installed, run the same program:
38
+
39
+ ```bash
40
+ node node_modules/@altenginenet/sdk/examples/first-write.mjs
41
+ ```
42
+
43
+ ## Setup
44
+
45
+ ```ts
46
+ import { AltEngine } from "@altenginenet/sdk";
47
+
48
+ const ae = new AltEngine({ apiKey: "ae_..." }); // production: https://api.altengine.net
49
+ ```
50
+
51
+ Everything is overridable, nothing is required:
52
+
53
+ - `apiKey` — falls back to the `ALTENGINE_API_KEY` env var
54
+ - `dev: true` — target the [local emulator](https://github.com/altlimit/altengine)
55
+ at `http://127.0.0.1:9191` (`altengine dev`)
56
+ - `baseUrl` — explicit origin; also settable via the `ALTENGINE_URL` env var
57
+ (resolution: `baseUrl` → `dev` → `ALTENGINE_URL` → production)
58
+
59
+ ```ts
60
+ const local = new AltEngine({ dev: true, apiKey: "dev" }); // emulator
61
+ // ALTENGINE_URL=http://127.0.0.1:9191 node app.js // same, via env
62
+ ```
63
+
64
+ Retryable failures (429 with `Retry-After`, 502/503/504, network errors) are retried
65
+ up to 3 times with jittered backoff — except transactions, publishes and datastore puts with server-generated keys, which are
66
+ never auto-retried. Errors throw `AltEngineError` with `code`, `status`, `details`,
67
+ and `retryAfter`.
68
+
69
+ ## Datastore
70
+
71
+ JSON documents in collections, per-namespace, with index-served queries,
72
+ aggregates, and atomic transactions.
73
+
74
+ ```ts
75
+ const db = ae.datastore("myapp", { namespace: "prod" });
76
+
77
+ const { keys } = await db.put("todos", [{ data: { title: "ship SDK", done: false } }]);
78
+ const doc = await db.get("todos", keys[0]); // null when missing
79
+ const docs = await db.get("todos", keys); // array in → array out, nulls for missing
80
+ await db.delete("todos", keys); // missing keys are no-ops
81
+
82
+ // Queries (cursor pagination handled by queryAll)
83
+ const page = await db.query("todos", {
84
+ where: [{ field: "done", op: "=", value: false }],
85
+ order: [{ field: "priority", dir: "desc" }],
86
+ limit: 100,
87
+ });
88
+ for await (const d of db.queryAll("todos", { where: [{ field: "owner", op: "=", value: "ana" }] })) {
89
+ // …
90
+ }
91
+
92
+ // Aggregates
93
+ const { groups } = await db.aggregate("todos", {
94
+ group: ["owner"],
95
+ metrics: [{ fn: "count", as: "n" }, { fn: "sum", field: "priority", as: "total" }],
96
+ });
97
+
98
+ // Transactions (atomic within a namespace; failed check throws 409)
99
+ await db.transaction([
100
+ { op: "check", collection: "users", key: "u1", exists: true },
101
+ { op: "mutate", collection: "counters", key: "todos", increment: { total: 1 }, upsert: true },
102
+ ]);
103
+
104
+ // Indexes
105
+ await db.indexes.create("todos", { fields: ["owner", "created:desc"] });
106
+ ```
107
+
108
+ ## Search
109
+
110
+ Full-text search with typed fields, facets, snippets, sorting, and cursors.
111
+
112
+ ```ts
113
+ import { f, facet } from "@altenginenet/sdk";
114
+
115
+ const idx = ae.search("myapp").index("products");
116
+
117
+ await idx.put([{
118
+ id: "p1",
119
+ fields: [
120
+ f.text("title", "Blue Suede Shoes"),
121
+ f.atom("sku", "BS-001"),
122
+ f.number("price", 59),
123
+ f.date("added", new Date()),
124
+ f.geo("store", { lat: 37.77, lng: -122.41 }),
125
+ ],
126
+ facets: [facet.atom("category", "shoes"), facet.number("price", 59)],
127
+ }]);
128
+
129
+ const doc = await idx.get("p1"); // null when missing
130
+ const docs = await idx.get(["p1", "nope"]); // array in → array out, nulls for missing
131
+
132
+ const res = await idx.search({
133
+ query: 'shoes price<100',
134
+ facets: ["category"],
135
+ snippet: { fields: ["title"] },
136
+ sort: [{ expr: "price" }],
137
+ limit: 20,
138
+ });
139
+
140
+ for await (const hit of idx.searchAll({ query: "shoes" })) { /* cursor-paged */ }
141
+ ```
142
+
143
+ ## Channels
144
+
145
+ Server side — mint subscriber tokens, publish, read presence:
146
+
147
+ ```ts
148
+ const ch = ae.channel("myapp");
149
+ const tok = await ch.createToken({ channels: ["room:1"], ttl_seconds: 3600, presence_id: "u42" });
150
+ await ch.publish("room:1", { hello: "world" });
151
+ const roster = await ch.presence("room:1");
152
+ ```
153
+
154
+ Browser side — hand the page a token from your backend and subscribe over
155
+ WebSocket (auto-reconnect, resubscribe, keepalive):
156
+
157
+ ```ts
158
+ import { ChannelSocket } from "@altenginenet/sdk/channel";
159
+
160
+ const sock = new ChannelSocket({
161
+ getToken: () => fetch("/api/channel-token").then((r) => r.json()), // the token response: { token, ws_endpoint, protocols, … }
162
+ });
163
+ sock.on("message", ({ channel, data }) => render(data));
164
+ await sock.connect();
165
+ await sock.subscribe(["room:2"]);
166
+ ```
167
+
168
+ The `@altenginenet/sdk/channel` subpath contains no API-key code — safe to bundle
169
+ into client apps.
170
+
171
+ ## Automation
172
+
173
+ Run scripts on your own Windows machines — driving desktop applications and
174
+ internal endpoints nothing on the internet can reach. Scripts are deployed with
175
+ the CLI (`altengine automation deploy`); this starts them and reads what they
176
+ produced.
177
+
178
+ ```ts
179
+ const auto = ae.automation("fleet");
180
+
181
+ // Start and wait. The run is finished when its OUTPUT has landed, not when the
182
+ // script returned — so a `done` here always has its files, with live links.
183
+ const { run, artifacts } = await auto.run(
184
+ { script: "nightly-export", params: { date: "2026-08-30" }, labels: ["site-dallas"] },
185
+ { onPoll: (r) => console.log(r.status, r.phase ?? "") },
186
+ );
187
+ for (const a of artifacts) console.log(a.name, a.size_bytes, a.url);
188
+
189
+ // Or start and come back later.
190
+ const started = await auto.start({ script: "nightly-export" });
191
+ const page = await auto.logs(started.id);
192
+ await auto.cancel(started.id);
193
+ ```
194
+
195
+ A `queued` run is not a failure: no matching machine is online yet, and an office
196
+ PC being asleep is the ordinary case. `wait`'s `timeoutMs` bounds the WAIT, not
197
+ the run — giving up leaves the job running on the machine, so call `cancel` if
198
+ that is what you meant.
199
+
200
+ A run's completion webhook is signed with the instance's webhook signing secret
201
+ (`whsec_…`, shown to an organization owner). Verify it against the raw body:
202
+
203
+ ```ts
204
+ import { verifyWebhook } from "@altenginenet/sdk";
205
+
206
+ const ok = await verifyWebhook({
207
+ secret: process.env.ALTENGINE_WEBHOOK_SECRET!,
208
+ body: await request.text(), // the raw body, not a re-serialised parse
209
+ signature: request.headers.get("x-altengine-signature"),
210
+ timestamp: request.headers.get("x-altengine-timestamp"),
211
+ // toleranceMs: 5 * 60 * 1000 (the default)
212
+ });
213
+ ```
214
+
215
+ Organization API key only. End-user identity tokens are refused here as they are
216
+ for containers: a run spends time on hardware you own, and access rules bound
217
+ what a user may read, not what they may spend.
218
+
219
+ ## Blob
220
+
221
+ Files, stored and served. **The bytes never travel through the API**: every
222
+ upload and download goes to a presigned URL, straight to storage.
223
+
224
+ ```ts
225
+ const files = ae.blob("assets");
226
+
227
+ // `put` picks the transfer — one PUT, or a multipart upload for a Blob/File
228
+ // bigger than storage takes in a single request.
229
+ const rec = await files.put("invoice.pdf", pdfBytes, { contentType: "application/pdf" });
230
+ rec.blobkey; // blob:<instance>:<id> — the handle to store in a document
231
+ rec.url; // the public URL, or null when the object is private
232
+
233
+ const { download_url, expires_at } = await files.get(rec.id); // signed, minutes
234
+ const bytes = await files.bytes(rec.id);
235
+
236
+ for await (const b of files.listAll({ prefix: "invoices/" })) console.log(b.name, b.size);
237
+ await files.setPublic(rec.id);
238
+ await files.delete([rec.id]);
239
+ ```
240
+
241
+ For a browser upload, your backend decides whether this user may upload and how
242
+ big the file may be, then hands over a URL that does exactly that:
243
+
244
+ ```ts
245
+ const minted = await files.uploadUrl({ name, size, content_type: type });
246
+ // the page PUTs the bytes to minted.upload_url with that content-type
247
+ ```
248
+
249
+ The size is signed into the URL, so it is the real bound on what whoever holds it
250
+ can make you store. There is no commit step — the row is promoted by the side
251
+ that received the bytes, so a `get` straight after an upload reads `ready`.
252
+
253
+ A container job that was given a store reads it from its own environment:
254
+
255
+ ```ts
256
+ import { blobFromJobEnv } from "@altenginenet/sdk";
257
+
258
+ const out = blobFromJobEnv(); // AE_BLOB_URL + AE_BLOB_TOKEN
259
+ await out.put("result.csv", csv, { contentType: "text/csv" });
260
+ ```
261
+
262
+ That token puts and gets. It cannot `list` the store, cannot publish (`setPublic`,
263
+ or `public: true` on an upload) and cannot delete — each a 403 naming what was
264
+ refused, never a quiet downgrade.
265
+
266
+ ## Containers
267
+
268
+ A Docker image run as a background job, for work that will not fit in a function.
269
+
270
+ ```ts
271
+ const jobs = ae.container("batch");
272
+
273
+ const job = await jobs.run({
274
+ image: "ghcr.io/me/worker:1",
275
+ cmd: ["./run", "--period", "2026-08"],
276
+ size: "medium",
277
+ });
278
+ const done = await jobs.wait(job.id, { onPoll: (j) => console.log(j.status) });
279
+ console.log(done.exit_code, done.cost_usd);
280
+
281
+ const { lines, cursor } = await jobs.logs(job.id);
282
+ await jobs.cancel(job.id);
283
+ const { sizes, allowed_images, max_timeout_ms } = await jobs.sizes();
284
+ ```
285
+
286
+ Only images on the instance's allowlist launch; an empty allowlist runs nothing.
287
+ `run` returns as soon as the machine exists — a job's output goes to blob or to a
288
+ completion function, not back through this call. `wait`'s `timeoutMs` bounds the
289
+ wait, not the job: giving up leaves the machine running and billing, so call
290
+ `cancel` if that is what you meant.
291
+
292
+ `list` is keyset-paged and its `cursor` feeds back as `before`; `listAll` walks
293
+ the pages for you.
294
+
295
+ Organization API key only, like automation.
296
+
297
+ ## Mailbox
298
+
299
+ Email addresses an app or agent owns. Any name works: `<slug>.<anything>@<domain>`
300
+ receives mail with no call needed.
301
+
302
+ ```ts
303
+ const mb = ae.mailbox("acme");
304
+
305
+ // Start waiting BEFORE handing the address out, so older mail is not mistaken for it.
306
+ const { messages } = await mb.wait({ after: "now", to: "signup", timeoutSeconds: 30 });
307
+ const msg = await mb.get(messages[0].id);
308
+
309
+ await mb.reply(msg.id, {
310
+ text: "Invoice attached.",
311
+ attachments: [{ filename: "invoice.pdf", contentType: "application/pdf", content: pdfBytes }],
312
+ });
313
+ await mb.send({ from: "billing", to: ["jane@example.com"], subject: "Receipt", text: "…" });
314
+
315
+ const { url } = await mb.attachment(msg.id, 0); // short-lived; no key needed to fetch it
316
+ await mb.keep(msg.id, 90); // 1–90 days from now
317
+ await mb.markRead(msg.id);
318
+
319
+ const page = await mb.list({ direction: "in", unread: true, limit: 25 }); // pass page.cursor back
320
+ await mb.addresses.create({ local: "billing", label: "receipts" });
321
+ ```
322
+
323
+ `content` is base64 text, or a `Uint8Array`, `ArrayBuffer` or `Blob` that the SDK
324
+ encodes. Up to 32 attachments; the whole message must stay under 5 MB once encoded
325
+ (about 3.6 MB of files), or the send fails with 413. `send` and `reply` are never
326
+ retried. In the default `reply` send mode, a recipient must have written to the
327
+ mailbox first, in authenticated mail.
328
+
329
+ `wait` returns `{ messages, cursor }` and is empty on timeout; call it again from
330
+ `cursor`. Organization API key only.
331
+
332
+ ## Tasks
333
+
334
+ Queues of work. A push queue delivers each task to a function, a channel or a signed
335
+ webhook, retrying with backoff until it is accepted; a pull queue holds tasks for workers.
336
+
337
+ ```ts
338
+ const tq = ae.tasks("jobs");
339
+
340
+ await tq.createQueue("emails", { target: { function: "app/send-email" }, ratePerSecond: 5 });
341
+ await tq.add("emails", { name: "welcome-42", payload: { userId: 42 }, delay: 60 });
342
+
343
+ // A pull queue: lease, work, ack — or give it back.
344
+ await tq.createQueue("reports", { mode: "pull" });
345
+ for (const t of await tq.lease("reports", { count: 10, leaseSeconds: 120 })) {
346
+ try {
347
+ await tq.ack(t.id, t.leaseId, await build(t.payload));
348
+ } catch (e) {
349
+ await tq.release(t.id, t.leaseId, { error: String(e), delaySeconds: 30 });
350
+ }
351
+ }
352
+
353
+ for await (const t of tq.listAll("emails", { state: "failed" })) await tq.run(t.id); // retry
354
+ ```
355
+
356
+ A task with a `name` is added once: a name already taken comes back as `{ ok: false,
357
+ code: "TASK_EXISTS" }`, not a throw, while the finished task's record is kept (the
358
+ instance's `retentionDays`). An add is retried on a transient failure only when every task
359
+ in it is named.
360
+
361
+ A function or webhook target receives `TaskDelivery` — `{ task, payload }` — and must
362
+ answer 2xx before `task.deadlineAt` — the queue's `deadlineSeconds` (15–840, default 600),
363
+ or the task's own. A timeout, 408, 429 or 5xx is retried; any other 4xx fails the task at
364
+ once. A target past its deadline is not stopped, so delivery is at least once, so handle `task.id` idempotently. The answer may steer the
365
+ retry with `Retry-After`, `x-task-retry: never | retry | defer` and
366
+ `x-task-max-attempts` (`TASK_RETRY_HEADER` and friends). Webhook deliveries are signed
367
+ like automation's: check them with `verifyWebhook`. Organization API key only.
368
+
369
+ ### Levels
370
+
371
+ A grant level is a ceiling, and they are cumulative: `read` < `write` < `full`.
372
+
373
+ | Level | Blob | Container | Mailbox | Tasks |
374
+ |---|---|---|---|---|
375
+ | `read` | `get`, `bytes`, `list` | `get`, `list`, `logs`, `sizes` | `info`, `list`, `wait`, `get`, `raw`, `attachment`, `addresses.list` | `info`, `queues`, `queue`, `list`, `get` |
376
+ | `write` | `put`, `uploadUrl`, `setPublic` | `run`, `cancel` | `send`, `reply`, `markRead`, `keep` (later date only), `addresses.create`, `addresses.disable` | `add`, `run`, `cancel`, `lease`, `ack`, `extend`, `release` |
377
+ | `full` | `delete` | — | `delete`, `keep` to an earlier date | `createQueue`, `updateQueue`, `pauseQueue`, `resumeQueue`, `purgeQueue`, `deleteQueue` |
378
+
379
+ A channel target is a publish: naming one, on a queue or a task, also takes `write` on
380
+ that channel instance.
381
+
382
+ ## Auth
383
+
384
+ Auth gives your **end users** accounts and identity tokens, so a browser app can
385
+ talk to Datastore and Channel **directly — with no backend of your own**. Access
386
+ rules on the auth instance decide what each user may read and write, which is what
387
+ makes it safe to hold that token in a browser.
388
+
389
+ ```ts
390
+ import { AuthClient } from "@altenginenet/sdk/auth";
391
+ import { AltEngine } from "@altenginenet/sdk";
392
+
393
+ const auth = new AuthClient({ instance: "myapp-auth" });
394
+
395
+ // Render a sign-in form that matches the instance's configured fields.
396
+ const cfg = await auth.config(); // { identity_field, fields, methods, ... }
397
+
398
+ const res = await auth.signIn("alice@example.com", "hunter2");
399
+ if (res.status === "mfa_required") {
400
+ await auth.verifyMfa(res.mfaToken, promptForCode());
401
+ }
402
+
403
+ // Hand the client to the SDK — every request now carries the user's id_token,
404
+ // refreshed automatically before it expires.
405
+ const ae = new AltEngine({ auth });
406
+ const { documents } = await ae.datastore("myapp").query("posts", { limit: 20 });
407
+ ```
408
+
409
+ Also available: `signUp`, `passwordlessStart`/`passwordlessVerify` (emailed
410
+ one-time code), `passwordResetStart`/`passwordResetVerify`, `me`, `refresh`, and
411
+ `signOut`. `auth.onChange(fn)` fires on sign-in/sign-out so your UI can react, and
412
+ `auth.user` / `auth.isSignedIn` survive a page reload.
413
+
414
+ The session persists in `localStorage` by default; pass `storage: memoryStorage()`
415
+ (or your own `TokenStorage`) to change that. Like the channel subpath,
416
+ `@altenginenet/sdk/auth` contains no API-key code.
417
+
418
+ > An org API key is a **backend** credential — never ship one to a browser. That
419
+ > is why passing `auth` takes precedence over `apiKey`.
420
+
421
+ ## Local development
422
+
423
+ Run the [altengine emulator](https://github.com/altlimit/altengine) and construct
424
+ the client with `dev: true` (or set `ALTENGINE_URL`) — any non-empty API key works:
425
+
426
+ ```bash
427
+ alt install altlimit/altengine && altengine dev
428
+ ```
429
+
430
+ Get an API key and instances for production at [www.altengine.net](https://www.altengine.net).