@simpleplatform/sdk 2.4.2 → 2.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 CHANGED
@@ -31,16 +31,16 @@ simple.Handle(async (request) => {
31
31
 
32
32
  The TypeScript SDK is organized into focused modules for different capabilities:
33
33
 
34
- | Module | Import | Purpose |
35
- | ------------ | ------------------------------ | ---------------------------------------------- |
36
- | **Core** | `@simpleplatform/sdk` | Request handling and action execution |
37
- | **AI** | `@simpleplatform/sdk/ai` | AI operations (extract, summarize, transcribe) |
38
- | **GraphQL** | `@simpleplatform/sdk/graphql` | Database queries and mutations |
39
- | **HTTP** | `@simpleplatform/sdk/http` | External HTTP requests |
40
- | **Security** | `@simpleplatform/sdk/security` | Security policy authoring |
41
- | **Settings** | `@simpleplatform/sdk/settings` | Application settings retrieval |
42
- | **Storage** | `@simpleplatform/sdk/storage` | File upload, and reading a stored file's bytes |
43
- | **Space** | `@simpleplatform/sdk/space` | Records, data, tasks, and documents in a Space |
34
+ | Module | Import | Purpose |
35
+ | ------------ | ------------------------------ | ------------------------------------------------------- |
36
+ | **Core** | `@simpleplatform/sdk` | Request handling and action execution |
37
+ | **AI** | `@simpleplatform/sdk/ai` | AI operations (extract, summarize, transcribe) |
38
+ | **GraphQL** | `@simpleplatform/sdk/graphql` | Database queries and mutations |
39
+ | **HTTP** | `@simpleplatform/sdk/http` | External HTTP requests |
40
+ | **Security** | `@simpleplatform/sdk/security` | Security policy authoring |
41
+ | **Settings** | `@simpleplatform/sdk/settings` | Application settings retrieval |
42
+ | **Storage** | `@simpleplatform/sdk/storage` | File upload, and reading a stored file's bytes |
43
+ | **Space** | `@simpleplatform/sdk/space` | Records, data, tasks, documents, and actions in a Space |
44
44
 
45
45
  ## Embedded Spaces
46
46
 
@@ -304,6 +304,83 @@ The handle is `{ file_hash, filename, mime_type, size, storage_path, scope? }`.
304
304
  to `application/octet-stream`. A staged document is not attached to anything
305
305
  yet; attach its handle through the workflow that owns the record.
306
306
 
307
+ ### Space actions
308
+
309
+ `simple.actions.run()` runs an action of the Space's own app where the app
310
+ declares it runs, as the signed-in user, and returns the action's JSON result:
311
+ a `server` action on the server, a `client` or `both` action in the browser, in
312
+ the platform page's own workers. The host makes the
313
+ call, so the Space makes no network request of its own: it names no domain,
314
+ needs no `network` permission to reach the platform, and handles no sign-in.
315
+ Actions work in standalone and record Spaces alike.
316
+
317
+ ```typescript
318
+ interface AttachResult { data: { document_id: string, status: string } }
319
+
320
+ const result = await simple.actions.run<AttachResult>(
321
+ 'document-attach',
322
+ { document_id: 'DOC000001', job_id: 'JOB000007' },
323
+ { timeoutMs: 120_000 }, // Optional: how long the host waits, in milliseconds.
324
+ )
325
+ ```
326
+
327
+ `action` is the action's name alone, such as `document-attach`: lowercase
328
+ letters, digits, and hyphens, starting with a letter or a digit. The host adds
329
+ the Space's own app, so a Space runs only its own app's actions and never names
330
+ an app. `input` is any JSON value and reaches the action as its payload; pass
331
+ `{}` or `null` when the action takes none. The result is the action's JSON
332
+ result as it returned it, unchecked: `TResult` is the caller's description of
333
+ it.
334
+
335
+ `timeoutMs` defaults to 60,000, and the host accepts 1,000 to 1,200,000. When it
336
+ runs out, the host stops waiting and the call rejects with `timeout`. If the
337
+ host's answer never comes, as when the host has closed its end of the
338
+ connection, the SDK stops waiting 5,000 ms after the timeout and rejects with
339
+ `timeout` itself, so a call always ends. Either way the action may still
340
+ complete, so a caller whose action writes should re-read before
341
+ offering to run it again.
342
+
343
+ A request the SDK can tell is malformed is refused before it is sent, with
344
+ `SpaceProtocolError` code `invalid_request`: a name outside that pattern, an
345
+ input that is not a JSON value, or a `timeoutMs` that is not a number. The host
346
+ checks the range of `timeoutMs`.
347
+
348
+ A call that does not return a result rejects with `SpaceProtocolError`, and its
349
+ `code` says why:
350
+
351
+ | `code` | When | `details` |
352
+ | ---------------------- | ------------------------------------------------------------------------- | ------------------ |
353
+ | `invalid_request` | The name, input, or options are malformed, or `timeoutMs` is out of range | None |
354
+ | `unsupported_protocol` | The host does not support the protocol version | None |
355
+ | `unavailable` | The host did not negotiate actions, or cannot run them | None |
356
+ | `timeout` | The action did not answer within `timeoutMs`, or the host did not answer | None |
357
+ | `action_failed` | The server answered with a status other than 2xx, or with an error result | `{ status, body }` |
358
+ | `network` | The host could not make the request | None |
359
+
360
+ For `action_failed`, `details` is an `ActionFailedDetails`: `status` is the
361
+ HTTP status the server answered with, and `body` is the response body as
362
+ parsed JSON, or `null` when it was not JSON. An action the host ran in the
363
+ browser carries 200 and the same `{ error: [...] }` body shape the server
364
+ gives for the same failure. Neither the host nor the SDK
365
+ changes the body, so an action's own error envelope is read from it:
366
+
367
+ ```typescript
368
+ import type { ActionFailedDetails } from '@simpleplatform/sdk/space'
369
+ import { SpaceProtocolError } from '@simpleplatform/sdk/space'
370
+
371
+ try {
372
+ await simple.actions.run('document-attach', { document_id: 'DOC000001' })
373
+ }
374
+ catch (error) {
375
+ if (!(error instanceof SpaceProtocolError) || error.code !== 'action_failed')
376
+ throw error
377
+
378
+ const { body, status } = error.details as ActionFailedDetails
379
+ // body is the action's own response, such as its error envelope.
380
+ console.warn(status, body)
381
+ }
382
+ ```
383
+
307
384
  ---
308
385
 
309
386
  ## API Documentation
@@ -90,6 +90,34 @@ export interface DocumentStageResult {
90
90
  export interface SimpleDocumentsClient {
91
91
  stage: (document: DocumentStageInput) => Promise<DocumentStageResult>;
92
92
  }
93
+ export interface ActionRunOptions {
94
+ /**
95
+ * How long the host waits for the action before it stops and answers
96
+ * `timeout`, in milliseconds. The host uses 60,000 when it is left out and
97
+ * accepts 1,000 to 1,200,000.
98
+ */
99
+ timeoutMs?: number;
100
+ }
101
+ /** The `details` of a `SpaceProtocolError` whose code is `action_failed`. */
102
+ export interface ActionFailedDetails {
103
+ /** The action's response body as parsed JSON, or `null` when it was not JSON. */
104
+ body: JsonValue;
105
+ /**
106
+ * The HTTP status the server answered with. An action the host ran in the
107
+ * browser (declared `client` or `both`) carries 200, the status the server
108
+ * gives the same failure, and its `body` has the same `{ error: [...] }` shape.
109
+ */
110
+ status: number;
111
+ }
112
+ export interface SimpleActionsClient {
113
+ /**
114
+ * Runs an action of this Space's own app where the app declares it runs
115
+ * (on the server, or in the browser for a `client` or `both` action), as
116
+ * the signed-in user, and returns its JSON result as the action returned it. The host
117
+ * adds the app, so `action` is the name alone, such as `document-attach`.
118
+ */
119
+ run: <TResult = unknown>(action: string, input: unknown, options?: ActionRunOptions) => Promise<TResult>;
120
+ }
93
121
  export interface SpaceDataTransport {
94
122
  execute: <TResult = unknown>(document: string, variables?: GraphQLVariables) => Promise<TResult>;
95
123
  }
@@ -104,6 +132,7 @@ export interface RecordHandle {
104
132
  update: (values: Readonly<Record<string, unknown>>) => Promise<RecordUpdateResult>;
105
133
  }
106
134
  export interface SimpleClient {
135
+ actions: SimpleActionsClient;
107
136
  context: SpaceContext;
108
137
  data: SimpleDataClient;
109
138
  documents: SimpleDocumentsClient;
@@ -179,6 +208,17 @@ export interface TaskReplyRequest {
179
208
  protocol: typeof PROTOCOL_VERSION;
180
209
  requestId: string;
181
210
  }
211
+ export interface ActionRunRequest {
212
+ operation: 'action.run';
213
+ payload: {
214
+ /** The action's name within the Space's own app; the host adds the app. */
215
+ action: string;
216
+ input: JsonValue;
217
+ timeoutMs?: number;
218
+ };
219
+ protocol: typeof PROTOCOL_VERSION;
220
+ requestId: string;
221
+ }
182
222
  export interface DocumentStageRequest {
183
223
  operation: 'document.stage';
184
224
  payload: {
@@ -190,7 +230,7 @@ export interface DocumentStageRequest {
190
230
  protocol: typeof PROTOCOL_VERSION;
191
231
  requestId: string;
192
232
  }
193
- export type ProtocolRequest = CurrentRecordRequest | DocumentStageRequest | RecordSubmitRequest | RecordUpdateRequest | TaskCreateRequest | TaskReplyRequest;
233
+ export type ProtocolRequest = ActionRunRequest | CurrentRecordRequest | DocumentStageRequest | RecordSubmitRequest | RecordUpdateRequest | TaskCreateRequest | TaskReplyRequest;
194
234
  export interface ProtocolSuccessResponse<TResult> {
195
235
  ok: true;
196
236
  protocol: typeof PROTOCOL_VERSION;
@@ -208,11 +248,14 @@ export interface SpaceTransport {
208
248
  /**
209
249
  * `transfer` names buffers inside the request whose ownership moves to the
210
250
  * host with it instead of being copied. A transport that cannot transfer
211
- * sends them by value.
251
+ * sends them by value. When `signal` aborts, the transport forgets the
252
+ * request, so a late answer is dropped, and rejects with the signal's reason.
212
253
  */
213
- request: <TResult>(request: ProtocolRequest, transfer?: ArrayBuffer[]) => Promise<ProtocolResponse<TResult>>;
254
+ request: <TResult>(request: ProtocolRequest, transfer?: ArrayBuffer[], signal?: AbortSignal) => Promise<ProtocolResponse<TResult>>;
214
255
  }
215
256
  export interface SimpleClientOptions {
257
+ /** Present only when the host negotiated the action protocol. */
258
+ actionTransport?: SpaceTransport;
216
259
  context?: SpaceContext;
217
260
  dataTransport?: SpaceDataTransport;
218
261
  /** Present only when the host negotiated the document protocol. */
@@ -230,5 +273,5 @@ export interface SimpleClientOptions {
230
273
  * contract can be exercised in a first-party direct adapter and in any UI
231
274
  * framework without importing browser-specific code.
232
275
  */
233
- export declare function createSimpleClient({ context, dataTransport, documentTransport, nextRequestId, taskTransport, transport, }: SimpleClientOptions): SimpleClient;
276
+ export declare function createSimpleClient({ actionTransport, context, dataTransport, documentTransport, nextRequestId, taskTransport, transport, }: SimpleClientOptions): SimpleClient;
234
277
  export declare function isSpaceContext(value: unknown): value is SpaceContext;
@@ -34,9 +34,10 @@ export class SpaceDataError extends Error {
34
34
  * contract can be exercised in a first-party direct adapter and in any UI
35
35
  * framework without importing browser-specific code.
36
36
  */
37
- export function createSimpleClient({ context = { kind: 'standalone' }, dataTransport, documentTransport, nextRequestId = createRequestId, taskTransport, transport, }) {
37
+ export function createSimpleClient({ actionTransport, context = { kind: 'standalone' }, dataTransport, documentTransport, nextRequestId = createRequestId, taskTransport, transport, }) {
38
38
  const immutableContext = immutableSpaceContext(context);
39
39
  return {
40
+ actions: createActionsClient(actionTransport, nextRequestId),
40
41
  context: immutableContext,
41
42
  data: {
42
43
  mutate: (document, variables) => executeData(dataTransport, document, variables),
@@ -99,6 +100,34 @@ function executeData(dataTransport, document, variables) {
99
100
  }
100
101
  return dataTransport.execute(document, variables);
101
102
  }
103
+ /**
104
+ * The host binds the Space's own app to every action it runs, so a Space names
105
+ * only the action and cannot reach another app's. Actions are not tied to a
106
+ * page record, so they are available in any Space whose host negotiated the
107
+ * action protocol, standalone or record.
108
+ */
109
+ function createActionsClient(transport, nextRequestId) {
110
+ return {
111
+ async run(action, input, options) {
112
+ if (!transport) {
113
+ throw new SpaceProtocolError({
114
+ code: 'unavailable',
115
+ message: 'Actions are unavailable because the Space host did not negotiate the action protocol.',
116
+ });
117
+ }
118
+ const payload = readActionRunPayload(action, input, options);
119
+ const request = {
120
+ operation: 'action.run',
121
+ payload,
122
+ protocol: PROTOCOL_VERSION,
123
+ requestId: nextRequestId(),
124
+ };
125
+ const response = await requestWithin(transport, request, actionWaitMs(payload.timeoutMs));
126
+ // Any JSON value is a valid result, so it is returned as the host sent it.
127
+ return readResponse(response, request);
128
+ },
129
+ };
130
+ }
102
131
  /**
103
132
  * A staged document is stored without being attached to a record, so staging
104
133
  * is available in any Space whose host negotiated the document protocol.
@@ -288,6 +317,69 @@ function readTaskReplyPayload(reply) {
288
317
  taskId: reply.taskId,
289
318
  };
290
319
  }
320
+ /** An action's name within its app, as the host checks it before adding the app. */
321
+ const ACTION_NAME = /^[a-z0-9][a-z0-9-]*$/;
322
+ /** The host's timeout for an action run that names none. */
323
+ const DEFAULT_ACTION_TIMEOUT_MS = 60000;
324
+ /** How much longer than the host's timeout the client waits for its answer. */
325
+ const ACTION_ANSWER_GRACE_MS = 5000;
326
+ /** The longest delay `setTimeout` keeps; it runs a longer one at once. */
327
+ const MAX_TIMER_MS = 2147483647;
328
+ /**
329
+ * How long a run waits for the host. The host answers `timeout` itself at the
330
+ * timeout, so this wait only ends a run whose answer never comes, as when the
331
+ * host has closed its port. A timeout the host refuses is answered at once, so
332
+ * it only needs to give a delay a timer can hold.
333
+ */
334
+ function actionWaitMs(timeoutMs) {
335
+ const hostTimeoutMs = Math.max(timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS, 0);
336
+ return Math.min(hostTimeoutMs + ACTION_ANSWER_GRACE_MS, MAX_TIMER_MS);
337
+ }
338
+ /**
339
+ * Sends a request and waits at most `waitMs` for its answer. After that it
340
+ * rejects with `timeout` and aborts the transport's wait, so the request is
341
+ * not kept pending on a port the host may no longer read.
342
+ */
343
+ async function requestWithin(transport, request, waitMs) {
344
+ const controller = new AbortController();
345
+ let timer;
346
+ const expired = new Promise((_resolve, reject) => {
347
+ timer = setTimeout(() => {
348
+ const error = new SpaceProtocolError({
349
+ code: 'timeout',
350
+ message: `The Space host did not answer ${request.operation} within ${waitMs} milliseconds, so its outcome is unknown.`,
351
+ });
352
+ controller.abort(error);
353
+ reject(error);
354
+ }, waitMs);
355
+ });
356
+ try {
357
+ return await Promise.race([transport.request(request, undefined, controller.signal), expired]);
358
+ }
359
+ finally {
360
+ clearTimeout(timer);
361
+ }
362
+ }
363
+ /**
364
+ * Checks an action run before it is sent. The timeout's range is the host's to
365
+ * enforce, so only its type is checked here, and it is sent only when given.
366
+ */
367
+ function readActionRunPayload(action, input, options) {
368
+ if (typeof action !== 'string' || !ACTION_NAME.test(action))
369
+ throw invalidRequest('An action is named alone, in lowercase letters, digits, and hyphens, such as "document-attach".');
370
+ if (!isJsonValue(input))
371
+ throw invalidRequest('An action input must be a JSON value, and everything in it a JSON value.');
372
+ if (options !== undefined && !isObjectRecord(options))
373
+ throw invalidRequest('Action options must be an object.');
374
+ const timeoutMs = options?.timeoutMs;
375
+ if (timeoutMs !== undefined && (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs)))
376
+ throw invalidRequest('An action timeout must be a number of milliseconds.');
377
+ return {
378
+ action,
379
+ input,
380
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
381
+ };
382
+ }
291
383
  /**
292
384
  * The task.create contract takes an object for input, never null, an array, or
293
385
  * a single value, so a caller learns that here instead of from the host.
@@ -298,7 +390,7 @@ function isJsonObject(value) {
298
390
  /**
299
391
  * Accepts only what JSON carries unchanged. A structured clone would pass a
300
392
  * Date, Map, or class instance through a MessagePort and a JSON transport
301
- * would not, so the task input is held to JSON on every transport.
393
+ * would not, so task and action input are held to JSON on every transport.
302
394
  */
303
395
  function isJsonValue(value, ancestors = new Set()) {
304
396
  if (value === null || typeof value === 'boolean' || typeof value === 'string')
@@ -1,7 +1,7 @@
1
1
  import type { SimpleClient } from './core.js';
2
2
  import { SpaceDataError, SpaceProtocolError } from './core.js';
3
3
  export { SpaceDataError, SpaceProtocolError, };
4
- export type { DocumentStageInput, DocumentStageResult, GraphQLVariables, JsonObject, JsonValue, RecordErrorSnapshot, RecordFieldSnapshot, RecordFormError, RecordHandle, RecordSnapshot, RecordSubmitResult, RecordUpdateResult, SimpleClient, SimpleDataClient, SimpleDocumentsClient, SimpleTasksClient, SpaceContext, SpaceDataErrorPayload, SpaceProtocolErrorPayload, StagedDocumentHandle, TaskCreateInput, TaskCreateResult, TaskReplyInput, TaskReplyResult, TaskStatus, } from './core.js';
4
+ export type { ActionFailedDetails, ActionRunOptions, DocumentStageInput, DocumentStageResult, GraphQLVariables, JsonObject, JsonValue, RecordErrorSnapshot, RecordFieldSnapshot, RecordFormError, RecordHandle, RecordSnapshot, RecordSubmitResult, RecordUpdateResult, SimpleActionsClient, SimpleClient, SimpleDataClient, SimpleDocumentsClient, SimpleTasksClient, SpaceContext, SpaceDataErrorPayload, SpaceProtocolErrorPayload, StagedDocumentHandle, TaskCreateInput, TaskCreateResult, TaskReplyInput, TaskReplyResult, TaskStatus, } from './core.js';
5
5
  interface MessagePortLike {
6
6
  onmessage: null | ((event: {
7
7
  data: unknown;
@@ -29,6 +29,7 @@ export interface ConnectSpaceOptions {
29
29
  * Connects any embedded Space to its parent through the dedicated MessagePort
30
30
  * handshake. Each protocol capability is offered in `SPACE_READY` and becomes
31
31
  * available only when the host negotiates it in `INIT_RPC`: record operations
32
- * for a configured record view, and task and document operations in any Space.
32
+ * for a configured record view, and task, document, and action operations in
33
+ * any Space.
33
34
  */
34
35
  export declare function connectSpace({ targetOrigin, window }: ConnectSpaceOptions): Promise<SimpleClient>;
@@ -4,7 +4,8 @@ export { SpaceDataError, SpaceProtocolError, };
4
4
  * Connects any embedded Space to its parent through the dedicated MessagePort
5
5
  * handshake. Each protocol capability is offered in `SPACE_READY` and becomes
6
6
  * available only when the host negotiates it in `INIT_RPC`: record operations
7
- * for a configured record view, and task and document operations in any Space.
7
+ * for a configured record view, and task, document, and action operations in
8
+ * any Space.
8
9
  */
9
10
  export function connectSpace({ targetOrigin, window = globalThis.window }) {
10
11
  if (!window) {
@@ -36,6 +37,7 @@ export function connectSpace({ targetOrigin, window = globalThis.window }) {
36
37
  const transport = createMessagePortTransport(port);
37
38
  const protocols = event.data.protocols;
38
39
  resolve(createSimpleClient({
40
+ actionTransport: protocols?.action === PROTOCOL_VERSION ? transport : undefined,
39
41
  context: event.data.context,
40
42
  dataTransport: transport,
41
43
  documentTransport: protocols?.document === PROTOCOL_VERSION ? transport : undefined,
@@ -46,6 +48,7 @@ export function connectSpace({ targetOrigin, window = globalThis.window }) {
46
48
  window.addEventListener('message', onMessage);
47
49
  window.parent.postMessage({
48
50
  protocols: {
51
+ action: [PROTOCOL_VERSION],
49
52
  document: [PROTOCOL_VERSION],
50
53
  record: [PROTOCOL_VERSION],
51
54
  task: [PROTOCOL_VERSION],
@@ -99,11 +102,19 @@ function createMessagePortTransport(port) {
99
102
  });
100
103
  });
101
104
  },
102
- request: (request, transfer = []) => {
103
- return new Promise((resolve) => {
105
+ request: (request, transfer = [], signal) => {
106
+ return new Promise((resolve, reject) => {
107
+ const abort = () => {
108
+ pending.delete(request.requestId);
109
+ reject(signal?.reason);
110
+ };
104
111
  pending.set(request.requestId, {
105
- resolve: response => resolve(response),
112
+ resolve: (response) => {
113
+ signal?.removeEventListener('abort', abort);
114
+ resolve(response);
115
+ },
106
116
  });
117
+ signal?.addEventListener('abort', abort, { once: true });
107
118
  port.postMessage({ request, type: 'SPACE_PROTOCOL_REQUEST' }, transfer);
108
119
  });
109
120
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpleplatform/sdk",
3
- "version": "2.4.2",
3
+ "version": "2.5.0",
4
4
  "description": "Simple Platform Typescript SDK",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://docs.simple.dev",