@permute/sdk 0.4.0 → 0.5.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 +89 -0
- package/dist/deploy.d.ts +20 -0
- package/dist/deploy.js +143 -0
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -442,6 +442,46 @@ Identical contents reuse existing files. Changed contents at the same path are s
|
|
|
442
442
|
|
|
443
443
|
Visitors sign in through Permute and need app read permission. HTML receives a revision-specific base URL; use relative URLs for bundled and public assets. Inline scripts, external requests, workers, and server runtimes are not supported. Keep API keys and secrets out of compiled browser files. Restore a historical revision with `client.revisions.restore`, then publish the resulting draft to roll back. See the [complete app guide](https://permute.ai/docs/guides/deploy-app) for creation, directory uploads, updates, and rollback.
|
|
444
444
|
|
|
445
|
+
### Deploy a build directory (SDK 0.5.0+)
|
|
446
|
+
|
|
447
|
+
The Node/Bun entry `@permute/sdk/deploy` combines validation, upload, draft save,
|
|
448
|
+
and publication for an existing live app. Available in SDK 0.5.0 and later; the
|
|
449
|
+
individual calls above remain available for separate draft review and publication.
|
|
450
|
+
|
|
451
|
+
```ts
|
|
452
|
+
import { deployApp } from '@permute/sdk/deploy';
|
|
453
|
+
|
|
454
|
+
const deployed = await deployApp(client, { appId, directory: './dist' });
|
|
455
|
+
console.log(deployed.url, deployed.revisionId, deployed.changed);
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
The helper rejects symbolic links, unsupported paths, missing `index.html`, and
|
|
459
|
+
oversized builds before uploading. It requires the current draft to be published;
|
|
460
|
+
after reviewing an existing draft, pass its exact `expectedDraft` to approve
|
|
461
|
+
replacing it. Omitted `actions` and `sourceIds` preserve current bindings (an empty
|
|
462
|
+
array clears them). To change action bindings, supply explicit published revisions:
|
|
463
|
+
|
|
464
|
+
```ts
|
|
465
|
+
await deployApp(client, {
|
|
466
|
+
appId,
|
|
467
|
+
directory: './dist',
|
|
468
|
+
actions: [{ actionId, revisionId: publishedActionRevisionId }],
|
|
469
|
+
sourceIds: [databaseId],
|
|
470
|
+
});
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
An unchanged build returns `changed: false` without uploading, saving, or publishing
|
|
474
|
+
(files, SPA mode, and any supplied bindings must match). It rechecks refs before
|
|
475
|
+
reporting no change. An approved unpublished draft is still published so settings
|
|
476
|
+
edits are preserved. Changed deployments return `changed: true`.
|
|
477
|
+
|
|
478
|
+
It stops if refs change and never retries mutations. After a failed or lost response,
|
|
479
|
+
inspect app history before retrying: uploads may exist, a draft may be saved, or
|
|
480
|
+
publication may already have completed. `deployment_conflict` requires review;
|
|
481
|
+
`invalid_build` requires fixing the local build. Use the individual calls above
|
|
482
|
+
when saving a draft for later review. The helper does not build, provision, or wait
|
|
483
|
+
for hosting, and must not be imported into browser code.
|
|
484
|
+
|
|
445
485
|
### Inside a hosted app
|
|
446
486
|
|
|
447
487
|
Use the browser entry with the app's existing sign-in session (no API key in frontend code):
|
|
@@ -467,6 +507,18 @@ Read scope is source-level; client-supplied SQL is not a row-level authorization
|
|
|
467
507
|
Keep the same request ID and input when retrying an uncertain action response. The client
|
|
468
508
|
does not retry writes automatically. A 401 requires signing in again.
|
|
469
509
|
|
|
510
|
+
For recovery across reloads, retain `{ baseUrl: document.baseURI, actionId, request }`
|
|
511
|
+
before sending (using storage appropriate to the input's sensitivity). After sign-in
|
|
512
|
+
or a newer app release, create `new PermuteAppClient({ baseUrl: pending.baseUrl })`
|
|
513
|
+
and invoke `pending.actionId` with `pending.request` as the same user. This keeps
|
|
514
|
+
the original app/action revision as well as the request ID and input. Never store
|
|
515
|
+
session cookies or API credentials with pending requests.
|
|
516
|
+
|
|
517
|
+
A later 401, 403, or 409 does not prove that an earlier attempt failed to commit.
|
|
518
|
+
Keep an uncertain request until its outcome is reconciled; do not silently clear
|
|
519
|
+
it, change its input, or generate a replacement ID. An edited payload is a new
|
|
520
|
+
operation only after resolving any earlier uncertain write.
|
|
521
|
+
|
|
470
522
|
## Business actions
|
|
471
523
|
|
|
472
524
|
Use `client.actions.create`, `definition`, and `saveDefinition` to author a typed
|
|
@@ -476,6 +528,43 @@ handler with selected database tables or connector accounts. Publish with
|
|
|
476
528
|
requires admin permission. See the [business action guide](https://permute.ai/docs/guides/business-actions)
|
|
477
529
|
for the complete create, save, publish, and invoke workflow.
|
|
478
530
|
|
|
531
|
+
### Expected failures in handlers
|
|
532
|
+
|
|
533
|
+
Use `reject(code, message, details?)` for a deliberate business rejection:
|
|
534
|
+
|
|
535
|
+
```js
|
|
536
|
+
exports.handler = ({ input, db, reject }) => {
|
|
537
|
+
if (!input.name.trim()) reject('validation_failed', 'Enter a name.', { field: 'name' });
|
|
538
|
+
db.insert('customers', input);
|
|
539
|
+
return input;
|
|
540
|
+
};
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
Rejection stops the handler and discards staged database writes. It cannot undo
|
|
544
|
+
connector calls already sent. Messages and details are public to callers; never
|
|
545
|
+
put credentials or private diagnostic data in them. A rejection message permits
|
|
546
|
+
1–1,000 characters, with up to 20 string detail fields (keys 1–100 characters,
|
|
547
|
+
values up to 500). Invalid rejections and unexpected exceptions return a safe
|
|
548
|
+
`execution_failed` response; exception text stays in server logs.
|
|
549
|
+
|
|
550
|
+
Both SDK entries expose `PermuteApiError.code`, `.status`, and `.details`.
|
|
551
|
+
Branch on the code (not message text):
|
|
552
|
+
|
|
553
|
+
| Code | HTTP | Recovery |
|
|
554
|
+
| -------------------------------- | -------- | --------------------------------------------------------------------- |
|
|
555
|
+
| `validation_failed` | 400 | Correct input; submit the changed input as a new request. |
|
|
556
|
+
| `record_conflict` | 409 | Reload current data and resolve the stale edit. |
|
|
557
|
+
| `invalid_transition` | 409 | Choose an allowed transition from the current state. |
|
|
558
|
+
| `permission_denied`, `not_found` | 403, 404 | Check current access or the selected record. |
|
|
559
|
+
| `request_conflict` | 409 | This ID already identifies different input; do not reuse it. |
|
|
560
|
+
| `request_in_progress` | 409 | Wait, then retry the identical request. |
|
|
561
|
+
| `outcome_unknown` | 409 | Retain the request ID; inspect external effects before any new write. |
|
|
562
|
+
| `execution_failed` | 500 | Inspect server logs; retry only with the same request ID and input. |
|
|
563
|
+
|
|
564
|
+
Handlers may reject with the first five codes. Transport/authentication failures
|
|
565
|
+
can still use the API's general error codes. A rejection after an external call
|
|
566
|
+
does not establish that nothing happened; reconcile provider state first.
|
|
567
|
+
|
|
479
568
|
### Connector bindings
|
|
480
569
|
|
|
481
570
|
An action definition can bind multiple connector accounts by name alongside its database
|
package/dist/deploy.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { PermuteClient } from './client.js';
|
|
2
|
+
import type { AppSiteSaveRequest, PermuteRequestOptions } from './types.js';
|
|
3
|
+
export interface DeployAppOptions {
|
|
4
|
+
appId: string;
|
|
5
|
+
directory: string;
|
|
6
|
+
/** Defaults to true. */
|
|
7
|
+
spa?: boolean;
|
|
8
|
+
/** Explicitly approve replacing this exact draft. Omit to require a clean published app. */
|
|
9
|
+
expectedDraft?: AppSiteSaveRequest['expectedDraft'];
|
|
10
|
+
/** Omit to preserve bindings; [] removes them. Revisions must already be published. */
|
|
11
|
+
actions?: AppSiteSaveRequest['actions'];
|
|
12
|
+
/** Omit to preserve source bindings; [] removes them. */
|
|
13
|
+
sourceIds?: AppSiteSaveRequest['sourceIds'];
|
|
14
|
+
}
|
|
15
|
+
/** Upload, save, and publish an existing live app. Builds and provisions nothing; never retries mutations. */
|
|
16
|
+
export declare function deployApp(client: PermuteClient, options: DeployAppOptions, requestOptions?: PermuteRequestOptions): Promise<{
|
|
17
|
+
url: string;
|
|
18
|
+
revisionId: string;
|
|
19
|
+
changed: boolean;
|
|
20
|
+
}>;
|
package/dist/deploy.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { lstat, readdir, open } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
6
|
+
import { Ajv } from 'ajv';
|
|
7
|
+
import { PermuteApiError } from './errors.js';
|
|
8
|
+
import { publicApiRoutes } from './generated/runtime-contract.js';
|
|
9
|
+
const ajv = new Ajv({ strict: false, allErrors: true, validateFormats: false });
|
|
10
|
+
const validateUploads = ajv.compile(publicApiRoutes.appsUploadsCreate.bodySchema);
|
|
11
|
+
const validateSite = ajv.compile(publicApiRoutes.appsSiteUpdate.bodySchema);
|
|
12
|
+
function conflict(message) {
|
|
13
|
+
throw new PermuteApiError({ status: 409, code: 'deployment_conflict', message });
|
|
14
|
+
}
|
|
15
|
+
/** Node/Bun only. Validate the complete build before making any upload or draft mutation. */
|
|
16
|
+
async function readBuild(directory, body, spa, signal) {
|
|
17
|
+
const entries = [];
|
|
18
|
+
const walk = async (absolutePath, path) => {
|
|
19
|
+
signal?.throwIfAborted();
|
|
20
|
+
const stat = await lstat(absolutePath);
|
|
21
|
+
if (stat.isSymbolicLink())
|
|
22
|
+
throw new Error(`Build contains a symbolic link: ${path || directory}`);
|
|
23
|
+
if (stat.isDirectory()) {
|
|
24
|
+
for (const name of (await readdir(absolutePath)).sort()) {
|
|
25
|
+
await walk(join(absolutePath, name), path ? `${path}/${name}` : name);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
else if (stat.isFile() && path) {
|
|
29
|
+
entries.push({ path, absolutePath, size: stat.size, sha256: '0'.repeat(64) });
|
|
30
|
+
if (!validateUploads({ files: entries.map(({ absolutePath: _, ...file }) => file) })) {
|
|
31
|
+
throw new PermuteApiError({
|
|
32
|
+
status: 0,
|
|
33
|
+
code: 'invalid_build',
|
|
34
|
+
message: 'Build files exceed app limits or contain an unsupported path.',
|
|
35
|
+
details: validateUploads.errors,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else
|
|
40
|
+
throw new Error(`Unsupported build entry: ${path || directory}`);
|
|
41
|
+
};
|
|
42
|
+
await walk(directory, '');
|
|
43
|
+
const manifest = entries.map(({ absolutePath: _, ...file }) => file);
|
|
44
|
+
// JSON Schema cannot express the server's manifest refinements. Check these before uploading.
|
|
45
|
+
if (!manifest.some((file) => file.path === 'index.html') ||
|
|
46
|
+
manifest.reduce((total, file) => total + file.size, 0) > 50 * 1024 * 1024 ||
|
|
47
|
+
new Set(body.actions?.map((action) => action.actionId)).size !== (body.actions?.length ?? 0) ||
|
|
48
|
+
new Set(body.sourceIds).size !== (body.sourceIds?.length ?? 0) ||
|
|
49
|
+
!validateSite({ ...body, site: { files: manifest, spa } })) {
|
|
50
|
+
throw new PermuteApiError({
|
|
51
|
+
status: 0,
|
|
52
|
+
code: 'invalid_build',
|
|
53
|
+
message: 'Invalid app build or bindings. Include index.html, stay within 50 MiB, and use valid app settings.',
|
|
54
|
+
details: validateSite.errors,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
const files = [];
|
|
58
|
+
for (const entry of entries) {
|
|
59
|
+
signal?.throwIfAborted();
|
|
60
|
+
const file = await open(entry.absolutePath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
61
|
+
try {
|
|
62
|
+
const stat = await file.stat();
|
|
63
|
+
if (!stat.isFile() || stat.size !== entry.size)
|
|
64
|
+
throw new Error(`Build changed: ${entry.path}`);
|
|
65
|
+
const data = Buffer.alloc(entry.size + 1);
|
|
66
|
+
let length = 0;
|
|
67
|
+
while (length < data.byteLength) {
|
|
68
|
+
signal?.throwIfAborted();
|
|
69
|
+
const { bytesRead } = await file.read(data, length, data.byteLength - length, null);
|
|
70
|
+
if (!bytesRead)
|
|
71
|
+
break;
|
|
72
|
+
length += bytesRead;
|
|
73
|
+
}
|
|
74
|
+
if (length !== entry.size)
|
|
75
|
+
throw new Error(`Build changed: ${entry.path}`);
|
|
76
|
+
files.push({ path: entry.path, data: data.subarray(0, length) });
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
await file.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return files;
|
|
83
|
+
}
|
|
84
|
+
/** Upload, save, and publish an existing live app. Builds and provisions nothing; never retries mutations. */
|
|
85
|
+
export async function deployApp(client, options, requestOptions) {
|
|
86
|
+
const { appId, directory, spa = true, ...bindings } = structuredClone(options);
|
|
87
|
+
const app = await client.apps.get(appId, requestOptions);
|
|
88
|
+
if (app.deployment?.status !== 'live')
|
|
89
|
+
throw new Error('App hosting must be live before deploying. Inspect client.apps.get(appId).');
|
|
90
|
+
const history = await client.revisions.list(appId, requestOptions);
|
|
91
|
+
const expected = bindings.expectedDraft ?? app.draft;
|
|
92
|
+
if (history.draft?.revisionId !== expected.revisionId ||
|
|
93
|
+
history.draft.sequence !== expected.sequence ||
|
|
94
|
+
app.draft.revisionId !== expected.revisionId ||
|
|
95
|
+
app.draft.sequence !== expected.sequence) {
|
|
96
|
+
conflict('App draft changed. Read and review it before deploying.');
|
|
97
|
+
}
|
|
98
|
+
if (!bindings.expectedDraft && history.draft.revisionId !== history.published?.revisionId) {
|
|
99
|
+
conflict('App has an unpublished draft. Review it and supply its expectedDraft to replace it.');
|
|
100
|
+
}
|
|
101
|
+
const body = { ...bindings, expectedDraft: expected };
|
|
102
|
+
const files = await readBuild(directory, body, spa, requestOptions?.signal);
|
|
103
|
+
// Only a clean published draft can be skipped: an approved draft may also contain settings edits.
|
|
104
|
+
if (history.published && history.draft.revisionId === history.published.revisionId) {
|
|
105
|
+
const revision = await client.revisions.get(appId, history.published.revisionId, requestOptions);
|
|
106
|
+
const previous = {
|
|
107
|
+
expectedDraft: expected,
|
|
108
|
+
site: revision.value.site,
|
|
109
|
+
actions: revision.value.actions,
|
|
110
|
+
sourceIds: revision.value.sourceIds,
|
|
111
|
+
};
|
|
112
|
+
const localManifest = files.map(({ path, data }) => ({
|
|
113
|
+
path,
|
|
114
|
+
size: data.length,
|
|
115
|
+
sha256: createHash('sha256').update(data).digest('hex'),
|
|
116
|
+
}));
|
|
117
|
+
if (validateSite(previous) &&
|
|
118
|
+
previous.site.spa === spa &&
|
|
119
|
+
isDeepStrictEqual(new Map(previous.site.files.map((file) => [file.path, file])), new Map(localManifest.map((file) => [file.path, file]))) &&
|
|
120
|
+
(bindings.actions === undefined ||
|
|
121
|
+
isDeepStrictEqual(new Map((previous.actions ?? []).map((action) => [action.actionId, action.revisionId])), new Map(bindings.actions.map((action) => [action.actionId, action.revisionId])))) &&
|
|
122
|
+
(bindings.sourceIds === undefined ||
|
|
123
|
+
isDeepStrictEqual(new Set(previous.sourceIds ?? []), new Set(bindings.sourceIds)))) {
|
|
124
|
+
const current = await client.revisions.list(appId, requestOptions);
|
|
125
|
+
if (current.version !== history.version)
|
|
126
|
+
conflict('App changed during inspection. Review the current refs.');
|
|
127
|
+
return { url: app.deployment.url, revisionId: history.published.revisionId, changed: false };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const manifest = await client.apps.uploadFiles(appId, files, requestOptions);
|
|
131
|
+
const saved = await client.apps.saveSite(appId, { ...body, site: { files: manifest, spa } }, requestOptions);
|
|
132
|
+
const ready = await client.revisions.list(appId, requestOptions);
|
|
133
|
+
if (ready.draft?.revisionId !== saved.draft.revisionId ||
|
|
134
|
+
ready.draft.sequence !== saved.draft.sequence ||
|
|
135
|
+
ready.published?.revisionId !== history.published?.revisionId ||
|
|
136
|
+
ready.published?.sequence !== history.published?.sequence) {
|
|
137
|
+
conflict('App changed during deployment. Review the current refs before retrying.');
|
|
138
|
+
}
|
|
139
|
+
const published = await client.revisions.publish(appId, { expectedVersion: ready.version }, requestOptions);
|
|
140
|
+
if (published.published?.revisionId !== saved.draft.revisionId)
|
|
141
|
+
throw new Error('Publication returned an unexpected revision. Inspect app history before retrying.');
|
|
142
|
+
return { url: app.deployment.url, revisionId: published.published.revisionId, changed: true };
|
|
143
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@permute/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "TypeScript client for the Permute public API",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -33,6 +33,11 @@
|
|
|
33
33
|
"types": "./dist/app.d.ts",
|
|
34
34
|
"import": "./dist/app.js",
|
|
35
35
|
"default": "./dist/app.js"
|
|
36
|
+
},
|
|
37
|
+
"./deploy": {
|
|
38
|
+
"types": "./dist/deploy.d.ts",
|
|
39
|
+
"import": "./dist/deploy.js",
|
|
40
|
+
"default": "./dist/deploy.js"
|
|
36
41
|
}
|
|
37
42
|
},
|
|
38
43
|
"publishConfig": {
|
|
@@ -53,10 +58,10 @@
|
|
|
53
58
|
},
|
|
54
59
|
"devDependencies": {
|
|
55
60
|
"@types/bun": "1.3.13",
|
|
56
|
-
"@types/node": "^24",
|
|
61
|
+
"@types/node": "^24.19.1",
|
|
57
62
|
"openapi-typescript": "^7.13.0",
|
|
58
63
|
"prettier": "3.6.2",
|
|
59
64
|
"typescript": "^5.9.3",
|
|
60
|
-
"vitest": "^4.1.
|
|
65
|
+
"vitest": "^4.1.11"
|
|
61
66
|
}
|
|
62
67
|
}
|