@simpleplatform/sdk 4.0.1 → 4.2.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
@@ -10,6 +10,20 @@ Install the SDK using [pnpm](https://pnpm.io):
10
10
  pnpm add @simpleplatform/sdk
11
11
  ```
12
12
 
13
+ ## Upgrading from 4.0 to 4.1
14
+
15
+ Version 4.1 removes the `temperature` and `reasoningBudget` options from
16
+ `extract`, `summarize` and `transcribe`, because they never had an effect on
17
+ the result. Where your code sets or reads either one, remove it; results stay
18
+ the same.
19
+
20
+ **A test that builds the client by hand** adds what the client gained, or it
21
+ stops type checking: `navigation`, `ui`, and `open` beside `current` under
22
+ `records` (for example `records: { current: vi.fn(), open: vi.fn() }`). Its
23
+ `navigation.open` must accept both `NavigationOpenOptions` and
24
+ `NavigationOpenUrlOptions`; one typed for only `NavigationOpenOptions` no
25
+ longer type checks.
26
+
13
27
  ## Upgrading from 2.x to 3
14
28
 
15
29
  Version 3 is the first release that carries the Space calls added after 2.5.0.
@@ -25,10 +39,6 @@ One of those changes renamed how a Space connects, which is why this is a major.
25
39
  | `ConnectSpaceOptions` | `ConnectOptions` |
26
40
  | `SpaceWindowLike`, `SpaceMessageEvent` | No longer exported. A test declares its own. |
27
41
 
28
- **A test that builds the client by hand** adds what the client gained, or it
29
- stops type checking: `navigation`, `ui`, and `open` beside `current` under
30
- `records` (for example `records: { current: vi.fn(), open: vi.fn() }`).
31
-
32
42
  **Two behaviours change with no change in your code:**
33
43
 
34
44
  - `connect()` sets `overscroll-behavior-y: none` on the Space's root element,
@@ -79,7 +89,7 @@ simple.Handle(async (request) => {
79
89
  The TypeScript SDK is organized into focused modules for different capabilities:
80
90
 
81
91
  | **Core** | `@simpleplatform/sdk` | Request handling and action execution |
82
- | **AI** | `@simpleplatform/sdk/ai` | AI operations (extract, summarize, transcribe) |
92
+ | **AI** | `@simpleplatform/sdk/ai` | AI operations (extract, summarize, transcribePages) |
83
93
  | **GraphQL** | `@simpleplatform/sdk/graphql` | Database queries and mutations |
84
94
  | **HTTP** | `@simpleplatform/sdk/http` | External HTTP requests |
85
95
  | **Security** | `@simpleplatform/sdk/security` | Security policy authoring |
@@ -96,7 +106,8 @@ Action/WASM API, so Action code never imports browser globals by accident.
96
106
  ```typescript
97
107
  import { connect } from '@simpleplatform/sdk/space'
98
108
 
99
- const simple = await connect({ targetOrigin: new URL(document.referrer).origin })
109
+ const targetOrigin = import.meta.env.VITE_SIMPLE_HOST_ORIGIN
110
+ const simple = await connect({ targetOrigin })
100
111
  const record = await simple.records.current()
101
112
 
102
113
  await record.update({ first_name: 'Ada' }) // Stages values and runs update Behavior.
@@ -109,9 +120,9 @@ if (!result.ok) {
109
120
  ```
110
121
 
111
122
  Connect once when the Space starts and reuse the returned client. One embedded iframe has one host MessagePort handshake.
112
- `targetOrigin` is the host's origin, not a full URL. If the embedding setup
113
- does not provide a referrer, supply the host origin from the Space's trusted
114
- configuration.
123
+ `targetOrigin` is the exact HTTP(S) host origin, not a full URL. In a Vite Space,
124
+ set `VITE_SIMPLE_HOST_ORIGIN` from trusted deployment configuration; the SDK
125
+ does not infer it from `document.referrer`.
115
126
 
116
127
  `simple.records.current()` returns the platform-owned record for the current
117
128
  record page. Its handle exposes immutable snapshots, `update(values)`, and
@@ -309,6 +320,28 @@ for platform targets a browser has no name for.
309
320
  `open()` returns `void` as soon as the request is posted. The host gives no
310
321
  confirmation, and a host without the navigation handler ignores the message.
311
322
 
323
+ To open an address outside the platform, pass an absolute HTTPS `url` in place
324
+ of the `path`. It opens only in a new tab, so `target: 'new-tab'` is required.
325
+ `open()` takes `NavigationOpenOptions` (`{ path, target? }`) or
326
+ `NavigationOpenUrlOptions` (`{ url, target: 'new-tab' }`):
327
+
328
+ ```ts
329
+ simple.navigation.open({ target: 'new-tab', url: 'https://example.com/help' })
330
+ ```
331
+
332
+ The platform opens it with `noopener` and `noreferrer`, so the new tab has no
333
+ handle back to the platform tab. `open()` first answers `'unavailable'` when
334
+ the host is not HTTPS or has no navigation bridge. Only then does it check the
335
+ `url`, and throw `SpaceProtocolError` with code `'invalid_request'` for a `url` with
336
+ `'same-tab'` or with no target, a `url` that is not HTTPS, a `url` that
337
+ carries a username or a password, and options that hold both a `path` and a
338
+ `url`, or neither. The SDK sends the address as the browser parses it. A
339
+ platform that opens only its own pages does not open it, and sends no reply.
340
+
341
+ The platform opens an outside address only when the Space lists its origin
342
+ under `permissions.links` in its manifest, for example `https://*.example.com`.
343
+ An unlisted address does not open.
344
+
312
345
  ### Space context
313
346
 
314
347
  `simple.context` is explicit host-provided page context. It is never inferred
@@ -749,7 +782,7 @@ an editor with TSDoc support recognizes it instead of flagging it as unknown.
749
782
 
750
783
  The AI module provides powerful capabilities for working with unstructured data.
751
784
 
752
- The `transcription` option on `extract`, `summarize`, `transcribe`, and `transcribePages` selects the reader for scanned pages; omission or `'standard'` preserves the default behavior.
785
+ The `transcription` option on `extract`, `summarize`, and `transcribePages` selects the reader for scanned pages; omission or `'standard'` preserves the default behavior.
753
786
  `'precise'` costs more and is for pages where exact characters matter (codes, part numbers); text pages are unaffected.
754
787
 
755
788
  ```typescript
@@ -803,29 +836,6 @@ const result = await summarize(
803
836
  console.log(result.data) // "This document outlines..."
804
837
  ```
805
838
 
806
- #### Transcribe Audio/Video
807
-
808
- Transcribe audio or video files with optional participant identification:
809
-
810
- ```typescript
811
- import { transcribe } from '@simpleplatform/sdk/ai'
812
-
813
- const result = await transcribe(
814
- audioFile,
815
- {
816
- includeTimestamps: true,
817
- includeTranscript: true,
818
- participants: ['Customer', 'Support Agent'],
819
- summarize: true
820
- },
821
- request.context
822
- )
823
-
824
- console.log(result.data.transcript) // "[00:15] Customer: I need help with..."
825
- console.log(result.data.summary) // "Customer called regarding..."
826
- console.log(result.data.participants) // ["Customer", "Support Agent"]
827
- ```
828
-
829
839
  #### Transcribe PDF Pages
830
840
 
831
841
  Read the pages of a PDF that have no usable text of their own — scans,
package/dist/ai.d.ts CHANGED
@@ -133,12 +133,6 @@ export interface AICommonOptions {
133
133
  * process in the generated output. Defaults to true.
134
134
  */
135
135
  reasoning?: boolean;
136
- /**
137
- * The maximum number of tokens to spend on the reasoning process.
138
- * If omitted, the platform chooses a sensible default.
139
- * Ignored if `reasoning` is false.
140
- */
141
- reasoningBudget?: number;
142
136
  /**
143
137
  * If true, forces the AI to re-process the input, ignoring
144
138
  * any previously cached results in the AI Memcache. Defaults to false.
@@ -149,11 +143,6 @@ export interface AICommonOptions {
149
143
  * high-level instructions for the entire task.
150
144
  */
151
145
  systemPrompt?: string;
152
- /**
153
- * (Optional) Controls the creativity of the model. A value from 0.0 (most
154
- * deterministic) to 1.0 (most creative). Defaults to the model's standard.
155
- */
156
- temperature?: number;
157
146
  /**
158
147
  * (Optional) The maximum time in milliseconds to wait for the AI operation.
159
148
  * If this timeout is exceeded, the promise will reject. Defaults to 30,000ms.
@@ -183,7 +172,7 @@ export interface AIExtractOptions extends AICommonOptions {
183
172
  export interface AISummarizeOptions extends AICommonOptions {
184
173
  }
185
174
  /**
186
- * Configuration options for audio/video transcription.
175
+ * Configuration options for the withdrawn `transcribe`.
187
176
  * Extends common options but excludes `prompt` as it's generated internally.
188
177
  */
189
178
  export interface AITranscribeOptions extends Omit<AICommonOptions, 'prompt'> {
@@ -371,38 +360,12 @@ export declare function extract(input: AIDocumentInput | DocumentHandle | object
371
360
  */
372
361
  export declare function summarize(input: AIDocumentInput | DocumentHandle | object | string, options: AISummarizeOptions, context: Context): Promise<AIExecutionResult>;
373
362
  /**
374
- * Transcribes audio or video from a document handle using the Simple AI engine.
375
- *
376
- * This function internally uses the `extract` operation with a dynamically generated
377
- * schema based on the requested options. It supports participant identification,
378
- * timestamps, and summarization.
379
- *
380
- * @param input The audio or video file as a DocumentHandle.
381
- * @param options The configuration for the transcription operation.
382
- * @param context The execution context provided by the host.
383
- * @returns A promise that resolves to an `AIExecutionResult` with structured transcription data.
384
- * @throws Will throw an error if the operation fails or inputs are invalid.
385
- *
386
- * @example
387
- * // Basic transcript
388
- * const result = await transcribe(audioHandle, { includeTranscript: true }, context)
389
- * // Returns: { language: "en", transcript: "..." }
363
+ * Withdrawn: audio and video files are not transcribed. To read the pages of
364
+ * a PDF from their images, use `transcribePages`.
390
365
  *
391
- * @example
392
- * // Transcript with participant identification
393
- * const result = await transcribe(audioHandle, {
394
- * includeTranscript: true,
395
- * participants: ['Customer', 'Support Agent']
396
- * }, context)
397
- * // Returns: { language: "en", transcript: "Customer: Hello...\nSupport Agent: Hi...", participants: [...] }
366
+ * Kept so that existing callers still build.
398
367
  *
399
- * @example
400
- * // Summary with auto-detected participants
401
- * const result = await transcribe(videoHandle, {
402
- * summarize: true,
403
- * participants: true
404
- * }, context)
405
- * // Returns: { language: "en", summary: "...", participants: ["Participant 1", "Participant 2"] }
368
+ * @deprecated Use `transcribePages` for the pages of a PDF.
406
369
  */
407
370
  export declare function transcribe(input: DocumentHandle, options: AITranscribeOptions, context: Context): Promise<AIExecutionResult>;
408
371
  /**
package/dist/ai.js CHANGED
@@ -51,7 +51,7 @@ async function _uploadPendingFiles(obj, context) {
51
51
  * @internal
52
52
  */
53
53
  async function _executeAIOperation(operation, input, options, context) {
54
- const { model, prompt, reasoning = true, reasoningBudget, regenerate = false, systemPrompt, temperature, timeout, transcription, } = options;
54
+ const { model, prompt, reasoning = true, regenerate = false, systemPrompt, timeout, transcription, } = options;
55
55
  if (transcription !== undefined && transcription !== 'standard' && transcription !== 'precise') {
56
56
  throw new Error('The `transcription` option must be "standard" or "precise".');
57
57
  }
@@ -59,8 +59,6 @@ async function _executeAIOperation(operation, input, options, context) {
59
59
  // 1. Construct the universal options payload for caching and execution.
60
60
  const universalOptions = {
61
61
  ...(transcription !== undefined && { transcription }),
62
- ...(temperature !== undefined && { temperature }),
63
- ...(reasoningBudget !== undefined && { reasoningBudget }),
64
62
  ...({ reasoning }),
65
63
  };
66
64
  // 2. Construct the full payload for the `ai-orchestrator` Go primitive.
@@ -180,38 +178,12 @@ export async function summarize(input, options, context) {
180
178
  return _executeAIOperation('summarize', input, options, context);
181
179
  }
182
180
  /**
183
- * Transcribes audio or video from a document handle using the Simple AI engine.
181
+ * Withdrawn: audio and video files are not transcribed. To read the pages of
182
+ * a PDF from their images, use `transcribePages`.
184
183
  *
185
- * This function internally uses the `extract` operation with a dynamically generated
186
- * schema based on the requested options. It supports participant identification,
187
- * timestamps, and summarization.
184
+ * Kept so that existing callers still build.
188
185
  *
189
- * @param input The audio or video file as a DocumentHandle.
190
- * @param options The configuration for the transcription operation.
191
- * @param context The execution context provided by the host.
192
- * @returns A promise that resolves to an `AIExecutionResult` with structured transcription data.
193
- * @throws Will throw an error if the operation fails or inputs are invalid.
194
- *
195
- * @example
196
- * // Basic transcript
197
- * const result = await transcribe(audioHandle, { includeTranscript: true }, context)
198
- * // Returns: { language: "en", transcript: "..." }
199
- *
200
- * @example
201
- * // Transcript with participant identification
202
- * const result = await transcribe(audioHandle, {
203
- * includeTranscript: true,
204
- * participants: ['Customer', 'Support Agent']
205
- * }, context)
206
- * // Returns: { language: "en", transcript: "Customer: Hello...\nSupport Agent: Hi...", participants: [...] }
207
- *
208
- * @example
209
- * // Summary with auto-detected participants
210
- * const result = await transcribe(videoHandle, {
211
- * summarize: true,
212
- * participants: true
213
- * }, context)
214
- * // Returns: { language: "en", summary: "...", participants: ["Participant 1", "Participant 2"] }
186
+ * @deprecated Use `transcribePages` for the pages of a PDF.
215
187
  */
216
188
  export async function transcribe(input, options, context) {
217
189
  // Validation
package/dist/graphql.d.ts CHANGED
@@ -1,4 +1,15 @@
1
1
  import type { Context } from './types';
2
+ /** JSON-shaped values, used unchanged in GraphQL variables and view presets. */
3
+ export type GraphQLJsonValue = boolean | null | number | string | GraphQLJsonValue[] | GraphQLJsonObject;
4
+ export interface GraphQLJsonObject {
5
+ [key: string]: GraphQLJsonValue;
6
+ }
7
+ /** The JSON value carried by a native SimpleDB filter field. */
8
+ export type RecordWhereValue = GraphQLJsonValue;
9
+ /** The canonical SimpleDB filter object. Its valid operators depend on the source schema. */
10
+ export interface RecordWhere {
11
+ [key: string]: RecordWhereValue;
12
+ }
2
13
  /**
3
14
  * Executes a GraphQL query with variables and returns the data directly.
4
15
  * This function communicates with the host system's database action and handles
@@ -1,6 +1,7 @@
1
1
  import type { Tenant, User } from '../types.js';
2
2
  import type { SimpleActionsClient } from './actions.js';
3
3
  import type { SimpleDocumentsClient } from './documents.js';
4
+ import type { SimpleCreateRecordClient, SimpleNewRecordClient, SimplePanelClient } from './host-ui.js';
4
5
  import type { SimpleNavigationClient, SpaceNavigationTransport } from './navigation.js';
5
6
  import type { SpaceTransport } from './protocol.js';
6
7
  import type { RecordFormCapabilities, RecordFormModelTransport, UiRuntimeDescriptor } from './record-form.js';
@@ -9,7 +10,7 @@ import type { SimpleTasksClient } from './tasks.js';
9
10
  import type { SimpleHeaderClient, SimpleTabsClient, SimpleToastClient, SpaceHeaderTransport, SpaceTabsTransport, SpaceToastTransport } from './ui.js';
10
11
  export type { ActionFailedDetails, ActionRunOptions, SimpleActionsClient, } from './actions.js';
11
12
  export type { DocumentStageInput, DocumentStageResult, SimpleDocumentsClient, StagedDocumentHandle, } from './documents.js';
12
- export type { NavigationOpenOptions, NavigationTarget, SimpleNavigationClient, SpaceNavigationTransport, } from './navigation.js';
13
+ export type { NavigationOpenOptions, NavigationOpenUrlOptions, NavigationTarget, SimpleNavigationClient, SpaceNavigationTransport, } from './navigation.js';
13
14
  export { PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError } from './protocol.js';
14
15
  export type { ProtocolErrorResponse, ProtocolRequest, ProtocolResponse, ProtocolSuccessResponse, SpaceDataErrorPayload, SpaceProtocolErrorPayload, SpaceTransport, } from './protocol.js';
15
16
  export { MANAGED_RECORD_FORM_PROTOCOL_VERSION } from './record-form.js';
@@ -53,6 +54,9 @@ export interface SimpleClient {
53
54
  records: SimpleRecordsClient;
54
55
  tasks: SimpleTasksClient;
55
56
  ui: {
57
+ createRecord: SimpleCreateRecordClient;
58
+ newRecord: SimpleNewRecordClient;
59
+ panel: SimplePanelClient;
56
60
  header: SimpleHeaderClient;
57
61
  tabs: SimpleTabsClient;
58
62
  toast: SimpleToastClient;
@@ -68,6 +72,7 @@ export interface SimpleClientOptions {
68
72
  documentTransport?: SpaceTransport;
69
73
  formModelTransport?: RecordFormModelTransport;
70
74
  hostOrigin?: string;
75
+ hostUiTransport?: SpaceTransport;
71
76
  headerTransport?: SpaceHeaderTransport;
72
77
  navigationTransport?: SpaceNavigationTransport;
73
78
  nextRequestId?: () => string;
@@ -80,5 +85,5 @@ export interface SimpleClientOptions {
80
85
  transport?: SpaceTransport;
81
86
  }
82
87
  /** Composes Space capabilities around the host transports supplied by `connect`. */
83
- export declare function createSimpleClient({ actionTransport, capabilities, context, dataTransport, documentTransport, formModelTransport, headerTransport, hostOrigin, navigationTransport, nextRequestId, recordsTransport, runtime, tabsTransport, taskTransport, toastTransport, transport, }: SimpleClientOptions): SimpleClient;
88
+ export declare function createSimpleClient({ actionTransport, capabilities, context, dataTransport, documentTransport, formModelTransport, headerTransport, hostOrigin, hostUiTransport, navigationTransport, nextRequestId, recordsTransport, runtime, tabsTransport, taskTransport, toastTransport, transport, }: SimpleClientOptions): SimpleClient;
84
89
  export declare function isSpaceContext(value: unknown): value is SpaceContext;
@@ -1,5 +1,6 @@
1
1
  import { createActionsClient } from './actions.js';
2
2
  import { createDocumentsClient } from './documents.js';
3
+ import { createHostUiClients } from './host-ui.js';
3
4
  import { createNavigationClient } from './navigation.js';
4
5
  import { deepFreeze, invalidResponse, isNonBlankString, isObjectRecord, PROTOCOL_VERSION, readResponse, SpaceDataError, SpaceProtocolError } from './protocol.js';
5
6
  import { createRecordsClient, isCurrentRecordResult, ProtocolRecordHandle } from './record.js';
@@ -11,7 +12,7 @@ export { RECORDS_PROTOCOL_VERSION } from './record.js';
11
12
  export { DEFAULT_TABS_TIMEOUT_MS, HEADER_ACTIONS_PROTOCOL_VERSION, LUCIDE_ICON_NAME, TAB_ID, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION, validateTabs } from './ui.js';
12
13
  const MANAGED_UI_SYMBOL = Symbol.for('@simpleplatform/sdk/space/managed-ui/v1');
13
14
  /** Composes Space capabilities around the host transports supplied by `connect`. */
14
- export function createSimpleClient({ actionTransport, capabilities, context = { kind: 'standalone' }, dataTransport, documentTransport, formModelTransport, headerTransport, hostOrigin, navigationTransport, nextRequestId = createRequestId, recordsTransport, runtime, tabsTransport, taskTransport, toastTransport, transport, }) {
15
+ export function createSimpleClient({ actionTransport, capabilities, context = { kind: 'standalone' }, dataTransport, documentTransport, formModelTransport, headerTransport, hostOrigin, hostUiTransport, navigationTransport, nextRequestId = createRequestId, recordsTransport, runtime, tabsTransport, taskTransport, toastTransport, transport, }) {
15
16
  const immutableContext = deepFreeze(structuredClone(context));
16
17
  const recordFormCapabilities = capabilities && toastTransport
17
18
  ? {
@@ -64,6 +65,7 @@ export function createSimpleClient({ actionTransport, capabilities, context = {
64
65
  records,
65
66
  tasks: createTasksClient(taskTransport, nextRequestId),
66
67
  ui: {
68
+ ...createHostUiClients(hostUiTransport, nextRequestId),
67
69
  header: createHeaderClient(immutableContext.kind === 'record', headerTransport),
68
70
  tabs: createTabsClient(immutableContext.kind === 'record', tabsTransport, nextRequestId),
69
71
  toast: createToastClient(toastTransport),
@@ -0,0 +1,37 @@
1
+ import type { SpaceTransport } from './protocol.js';
2
+ import type { RecordReference } from './record.js';
3
+ import type { JsonObject } from './tasks.js';
4
+ export declare const HOST_UI_PROTOCOL_VERSION: 1;
5
+ export interface CreateRecordOptions {
6
+ appId: string;
7
+ tableName: string;
8
+ defaults?: JsonObject;
9
+ }
10
+ export type NewRecordOptions = CreateRecordOptions;
11
+ export type PanelContent = ({
12
+ kind: 'record';
13
+ } & RecordReference) | {
14
+ kind: 'space';
15
+ spaceId: string;
16
+ };
17
+ export interface SimpleCreateRecordClient {
18
+ /** Opens the platform form without navigating. Null means the user cancelled. */
19
+ open: (options: CreateRecordOptions) => Promise<RecordReference | null>;
20
+ }
21
+ export type SimpleNewRecordClient = SimpleCreateRecordClient;
22
+ export interface SimplePanelClient {
23
+ /** The host owns the panel chrome; arbitrary workflows use a Space of this app. Awaits until the panel closes. */
24
+ open: (content: PanelContent) => Promise<{
25
+ closed: true;
26
+ id: string;
27
+ }>;
28
+ close: (id?: string) => Promise<boolean>;
29
+ }
30
+ export declare function validateCreateRecordOptions(value: unknown): CreateRecordOptions;
31
+ export declare const validateNewRecordOptions: typeof validateCreateRecordOptions;
32
+ export declare function validatePanelContent(value: unknown): PanelContent;
33
+ export declare function createHostUiClients(transport: SpaceTransport | undefined, nextRequestId: () => string): {
34
+ createRecord: SimpleCreateRecordClient;
35
+ newRecord: SimpleNewRecordClient;
36
+ panel: SimplePanelClient;
37
+ };
@@ -0,0 +1,57 @@
1
+ import { invalidRequest, invalidResponse, isObjectRecord, PROTOCOL_VERSION, readResponse, SpaceProtocolError } from './protocol.js';
2
+ import { isJsonValue } from './tasks.js';
3
+ export const HOST_UI_PROTOCOL_VERSION = 1;
4
+ const identifier = (value) => typeof value === 'string' && /^[\w.-]{1,200}$/.test(value);
5
+ export function validateCreateRecordOptions(value) {
6
+ if (!isObjectRecord(value) || !identifier(value.appId) || !identifier(value.tableName)
7
+ || (value.defaults !== undefined && (!isObjectRecord(value.defaults) || !isJsonValue(value.defaults) || JSON.stringify(value.defaults).length > 65536))) {
8
+ throw invalidRequest('A new record requires appId, tableName, and optional JSON defaults (up to 64 KB).');
9
+ }
10
+ return { appId: value.appId, tableName: value.tableName, ...(value.defaults === undefined ? {} : { defaults: value.defaults }) };
11
+ }
12
+ export const validateNewRecordOptions = validateCreateRecordOptions;
13
+ export function validatePanelContent(value) {
14
+ if (!isObjectRecord(value))
15
+ throw invalidRequest('Panel content must name a record or an app-owned Space.');
16
+ if (value.kind === 'record' && identifier(value.appId) && identifier(value.tableName) && identifier(value.recordId))
17
+ return { appId: value.appId, kind: 'record', recordId: value.recordId, tableName: value.tableName };
18
+ if (value.kind === 'space' && identifier(value.spaceId))
19
+ return { kind: 'space', spaceId: value.spaceId };
20
+ throw invalidRequest('Panel content must name a record or an app-owned Space.');
21
+ }
22
+ export function createHostUiClients(transport, nextRequestId) {
23
+ const request = async (operation, payload) => {
24
+ if (!transport)
25
+ throw new SpaceProtocolError({ code: 'unavailable', message: 'Host dialogs and panels are unavailable in this host.' });
26
+ const envelope = { operation, payload, protocol: PROTOCOL_VERSION, requestId: nextRequestId() };
27
+ return readResponse(await transport.request(envelope), envelope);
28
+ };
29
+ const createRecordClient = {
30
+ open: async (options) => {
31
+ const result = await request('ui.createRecord.open', validateCreateRecordOptions(options));
32
+ if (result !== null && (!isObjectRecord(result) || !identifier(result.appId) || !identifier(result.tableName) || !identifier(result.recordId)))
33
+ throw invalidResponse('The create-record result is malformed.');
34
+ return result;
35
+ },
36
+ };
37
+ return {
38
+ createRecord: createRecordClient,
39
+ newRecord: createRecordClient,
40
+ panel: {
41
+ close: async (id) => {
42
+ if (id !== undefined && !identifier(id))
43
+ throw invalidRequest('Panel id must be a non-empty identifier.');
44
+ const result = await request('ui.panel.close', id ? { id } : {});
45
+ if (typeof result !== 'boolean')
46
+ throw invalidResponse('The panel close result is malformed.');
47
+ return result;
48
+ },
49
+ open: async (content) => {
50
+ const result = await request('ui.panel.open', validatePanelContent(content));
51
+ if (!isObjectRecord(result) || result.closed !== true || !identifier(result.id))
52
+ throw invalidResponse('The panel result is malformed.');
53
+ return result;
54
+ },
55
+ },
56
+ };
57
+ }
@@ -1,7 +1,9 @@
1
1
  import type { SimpleClient } from './core.js';
2
2
  import { HEADER_ACTIONS_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION } from './core.js';
3
+ export type { ActionFailedDetails, ActionRunOptions, DocumentStageInput, DocumentStageResult, GraphQLVariables, HeaderAction, HeaderActionType, JsonObject, JsonValue, NavigationOpenOptions, NavigationOpenUrlOptions, NavigationTarget, OpenRecordOptions, RecordErrorSnapshot, RecordFieldSnapshot, RecordFormError, RecordHandle, RecordOpenRequest, RecordOpenResult, RecordReference, RecordSnapshot, RecordSubmitResult, RecordUpdateResult, SetTabsOptions, SimpleActionsClient, SimpleClient, SimpleDataClient, SimpleDocumentsClient, SimpleHeaderActionsClient, SimpleHeaderClient, SimpleNavigationClient, SimpleRecordsClient, SimpleTabsClient, SimpleTasksClient, SimpleToastClient, SpaceContext, SpaceDataErrorPayload, SpaceNavigationTransport, SpaceProtocolErrorPayload, SpaceTab, SpaceTabsSelectionEvent, SpaceTabsTransport, SpaceToastOptions, SpaceToastVariant, StagedDocumentHandle, TaskCreateInput, TaskCreateResult, TaskReplyInput, TaskReplyResult, TaskStatus, } from './core.js';
4
+ export { HOST_UI_PROTOCOL_VERSION } from './host-ui.js';
3
5
  export { HEADER_ACTIONS_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION };
4
- export type { ActionFailedDetails, ActionRunOptions, DocumentStageInput, DocumentStageResult, GraphQLVariables, HeaderAction, HeaderActionType, JsonObject, JsonValue, NavigationOpenOptions, NavigationTarget, OpenRecordOptions, RecordErrorSnapshot, RecordFieldSnapshot, RecordFormError, RecordHandle, RecordOpenRequest, RecordOpenResult, RecordReference, RecordSnapshot, RecordSubmitResult, RecordUpdateResult, SetTabsOptions, SimpleActionsClient, SimpleClient, SimpleDataClient, SimpleDocumentsClient, SimpleHeaderActionsClient, SimpleHeaderClient, SimpleNavigationClient, SimpleRecordsClient, SimpleTabsClient, SimpleTasksClient, SimpleToastClient, SpaceContext, SpaceDataErrorPayload, SpaceNavigationTransport, SpaceProtocolErrorPayload, SpaceTab, SpaceTabsSelectionEvent, SpaceTabsTransport, SpaceToastOptions, SpaceToastVariant, StagedDocumentHandle, TaskCreateInput, TaskCreateResult, TaskReplyInput, TaskReplyResult, TaskStatus, } from './core.js';
6
+ export type { CreateRecordOptions, NewRecordOptions, PanelContent, SimpleCreateRecordClient, SimpleNewRecordClient, SimplePanelClient } from './host-ui.js';
5
7
  export interface ConnectOptions {
6
8
  targetOrigin: string;
7
9
  }
@@ -1,7 +1,9 @@
1
1
  import { createMessagePortTransport } from './browser-transport.js';
2
2
  import { createSimpleClient, HEADER_ACTIONS_PROTOCOL_VERSION, isSpaceContext, MANAGED_RECORD_FORM_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION, } from './core.js';
3
+ import { HOST_UI_PROTOCOL_VERSION } from './host-ui.js';
3
4
  import { isObjectRecord } from './protocol.js';
4
5
  import { applyThemeSnapshot, parseThemeSnapshot, THEME_PROTOCOL_VERSION } from './theme.js';
6
+ export { HOST_UI_PROTOCOL_VERSION } from './host-ui.js';
5
7
  export { HEADER_ACTIONS_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION };
6
8
  const connections = new WeakMap();
7
9
  /** Connects this Space to its host using the explicitly supplied host origin. */
@@ -78,6 +80,7 @@ export function connect({ targetOrigin }) {
78
80
  formModelTransport: protocols?.form === MANAGED_RECORD_FORM_PROTOCOL_VERSION || protocols?.form === 2 ? transport : undefined,
79
81
  headerTransport: hasRecord && protocols?.header === HEADER_ACTIONS_PROTOCOL_VERSION ? transport : undefined,
80
82
  hostOrigin: targetOrigin,
83
+ hostUiTransport: protocols?.hostUi === HOST_UI_PROTOCOL_VERSION ? transport : undefined,
81
84
  navigationTransport: transport,
82
85
  recordsTransport: hasRecords ? transport : undefined,
83
86
  runtime: event.data.runtime,
@@ -94,6 +97,7 @@ export function connect({ targetOrigin }) {
94
97
  document: [PROTOCOL_VERSION],
95
98
  form: [MANAGED_RECORD_FORM_PROTOCOL_VERSION, 2],
96
99
  header: [HEADER_ACTIONS_PROTOCOL_VERSION],
100
+ hostUi: [HOST_UI_PROTOCOL_VERSION],
97
101
  record: [PROTOCOL_VERSION],
98
102
  records: [RECORDS_PROTOCOL_VERSION],
99
103
  tabs: [TABS_PROTOCOL_VERSION],
@@ -15,9 +15,20 @@ export type NavigationTarget = 'same-tab' | 'new-tab';
15
15
  export interface NavigationOpenOptions {
16
16
  path: string;
17
17
  target?: NavigationTarget;
18
+ url?: never;
19
+ }
20
+ /**
21
+ * Opens an absolute HTTPS `url` outside the platform. It opens only in a new
22
+ * tab, so `target` must be `new-tab`, and it may not carry a username or a
23
+ * password. Options hold a `path` or a `url`, never both.
24
+ */
25
+ export interface NavigationOpenUrlOptions {
26
+ url: string;
27
+ target: 'new-tab';
28
+ path?: never;
18
29
  }
19
30
  export interface SimpleNavigationClient {
20
- open: (options: NavigationOpenOptions) => void;
31
+ open: (options: NavigationOpenOptions | NavigationOpenUrlOptions) => void;
21
32
  }
22
33
  export interface SpaceNavigationTransport {
23
34
  navigate: (url: string, target: NavigationTarget) => void;
@@ -4,12 +4,16 @@ export function createNavigationClient(hostOrigin, transport) {
4
4
  open(options) {
5
5
  if (!isObjectRecord(options))
6
6
  throw invalidRequest('Navigation options must be an object.');
7
- const { path, target } = options;
8
- if (typeof path !== 'string' || path.length === 0 || !path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
7
+ const { path, target, url: address } = options;
8
+ if ((path === undefined) === (address === undefined))
9
+ throw invalidRequest('Navigation options must hold either a path or a url, not both.');
10
+ if (address === undefined && (typeof path !== 'string' || path.length === 0 || !path.startsWith('/') || path.startsWith('//') || path.includes('\\')))
9
11
  throw invalidRequest('Navigation path must be a host-relative path starting with one slash, with no backslash.');
10
12
  const resolvedTarget = target === undefined ? 'same-tab' : target;
11
13
  if (resolvedTarget !== 'same-tab' && resolvedTarget !== 'new-tab')
12
14
  throw invalidRequest('Navigation target must be "same-tab" or "new-tab".');
15
+ if (address !== undefined && resolvedTarget !== 'new-tab')
16
+ throw invalidRequest('A navigation url opens only in a new tab: set target to "new-tab".');
13
17
  if (!hostOrigin || new URL(hostOrigin).protocol !== 'https:') {
14
18
  throw new SpaceProtocolError({
15
19
  code: 'unavailable',
@@ -22,6 +26,10 @@ export function createNavigationClient(hostOrigin, transport) {
22
26
  message: 'The platform-navigation bridge is unavailable for this Space.',
23
27
  });
24
28
  }
29
+ if (address !== undefined) {
30
+ transport.navigate(outsideAddress(address), resolvedTarget);
31
+ return;
32
+ }
25
33
  // URL parsing drops a tab or a newline, which can turn a path into another host's address.
26
34
  const url = new URL(path, hostOrigin);
27
35
  if (url.origin !== new URL(hostOrigin).origin)
@@ -30,3 +38,22 @@ export function createNavigationClient(hostOrigin, transport) {
30
38
  },
31
39
  };
32
40
  }
41
+ /**
42
+ * Checks an address outside the platform and returns it as the browser parses
43
+ * it, so the address sent is the one checked. The platform opens such an
44
+ * address only over HTTPS and never with a username or a password in it.
45
+ */
46
+ function outsideAddress(address) {
47
+ let url;
48
+ try {
49
+ url = typeof address === 'string' ? new URL(address) : undefined;
50
+ }
51
+ catch {
52
+ url = undefined;
53
+ }
54
+ if (url?.protocol !== 'https:')
55
+ throw invalidRequest('Navigation url must be an absolute HTTPS address.');
56
+ if (url.username !== '' || url.password !== '')
57
+ throw invalidRequest('Navigation url must not carry a username or a password.');
58
+ return url.href;
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpleplatform/sdk",
3
- "version": "4.0.1",
3
+ "version": "4.2.0",
4
4
  "description": "Simple Platform Typescript SDK",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://docs.simple.dev",
@@ -82,6 +82,6 @@
82
82
  "scripts": {
83
83
  "build": "rm -rf dist && tsc && cp src/worker-override.js dist/ && cp cli/build.js dist/ && cp src/space/package.json dist/space/",
84
84
  "test": "pnpm run build && node --test test/*.test.mjs",
85
- "typecheck": "tsc --noEmit"
85
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.types.json"
86
86
  }
87
87
  }