@simpleplatform/sdk 2.4.2 → 3.0.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.
@@ -1,94 +1,86 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _ProtocolRecordHandle_nextRequestId, _ProtocolRecordHandle_transport, _ProtocolRecordHandle_snapshot;
13
- export const PROTOCOL_VERSION = 1;
14
- export class SpaceProtocolError extends Error {
15
- constructor({ code, details, message }) {
16
- super(message);
17
- this.name = 'SpaceProtocolError';
18
- this.code = code;
19
- this.details = details;
20
- }
21
- }
22
- export class SpaceDataError extends Error {
23
- constructor({ code, details, message }) {
24
- super(message);
25
- this.name = 'SpaceDataError';
26
- this.code = code;
27
- this.details = details;
28
- }
29
- }
30
- /**
31
- * Creates a framework-neutral Space client around a protocol transport.
32
- *
33
- * MessagePort setup is intentionally outside this factory so the same public
34
- * contract can be exercised in a first-party direct adapter and in any UI
35
- * framework without importing browser-specific code.
36
- */
37
- export function createSimpleClient({ context = { kind: 'standalone' }, dataTransport, documentTransport, nextRequestId = createRequestId, taskTransport, transport, }) {
38
- const immutableContext = immutableSpaceContext(context);
1
+ import { createActionsClient } from './actions.js';
2
+ import { createDocumentsClient } from './documents.js';
3
+ import { createNavigationClient } from './navigation.js';
4
+ import { deepFreeze, invalidResponse, isObjectRecord, PROTOCOL_VERSION, readResponse, SpaceDataError, SpaceProtocolError } from './protocol.js';
5
+ import { createRecordsClient, isCurrentRecordResult, ProtocolRecordHandle } from './record.js';
6
+ import { createTasksClient } from './tasks.js';
7
+ import { createHeaderClient, createTabsClient, createToastClient, validateSpaceToastOptions } from './ui.js';
8
+ export { PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError } from './protocol.js';
9
+ export { MANAGED_RECORD_FORM_PROTOCOL_VERSION } from './record-form.js';
10
+ export { RECORDS_PROTOCOL_VERSION } from './record.js';
11
+ export { DEFAULT_TABS_TIMEOUT_MS, HEADER_ACTIONS_PROTOCOL_VERSION, HEADER_STATUS_PROTOCOL_VERSION, LUCIDE_ICON_NAME, TAB_ID, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION, validateHeaderStatus, validateTabs } from './ui.js';
12
+ /** Composes Space capabilities around the host transports supplied by `connect`. */
13
+ export function createSimpleClient({ actionTransport, capabilities, context = { kind: 'standalone' }, dataTransport, documentTransport, formModelTransport, headerStatusTransport, headerTransport, hostOrigin, navigationTransport, nextRequestId = createRequestId, recordsTransport, runtime, tabsTransport, taskTransport, toastTransport, transport, }) {
14
+ const immutableContext = deepFreeze(structuredClone(context));
15
+ const recordFormCapabilities = capabilities && toastTransport
16
+ ? {
17
+ ...capabilities,
18
+ showToast: (options) => toastTransport.showToast(validateSpaceToastOptions(options)),
19
+ }
20
+ : capabilities;
21
+ const record = async () => {
22
+ if (immutableContext.kind !== 'record') {
23
+ throw new SpaceProtocolError({
24
+ code: 'unavailable',
25
+ message: 'The current record is available only when this Space is configured as a record view.',
26
+ });
27
+ }
28
+ if (!transport) {
29
+ throw new SpaceProtocolError({
30
+ code: 'unavailable',
31
+ message: 'The record protocol is unavailable for this record Space.',
32
+ });
33
+ }
34
+ const request = {
35
+ operation: 'record.current',
36
+ payload: {},
37
+ protocol: PROTOCOL_VERSION,
38
+ requestId: nextRequestId(),
39
+ };
40
+ const response = await transport.request(request);
41
+ const result = readResponse(response, request);
42
+ if (!isCurrentRecordResult(result))
43
+ throw invalidResponse('The primary-record response is malformed.');
44
+ return new ProtocolRecordHandle(result, nextRequestId, transport, runtime, (document, variables) => executeData(dataTransport, document, variables), recordFormCapabilities, formModelTransport, immutableContext.applicationId);
45
+ };
46
+ const records = createRecordsClient({
47
+ capabilities: recordFormCapabilities,
48
+ currentRecord: record,
49
+ graphql: (document, variables) => executeData(dataTransport, document, variables),
50
+ nextRequestId,
51
+ recordsTransport,
52
+ runtime,
53
+ });
39
54
  return {
55
+ actions: createActionsClient(actionTransport, nextRequestId),
40
56
  context: immutableContext,
41
57
  data: {
42
58
  mutate: (document, variables) => executeData(dataTransport, document, variables),
43
59
  query: (document, variables) => executeData(dataTransport, document, variables),
44
60
  },
45
61
  documents: createDocumentsClient(documentTransport, nextRequestId),
46
- records: {
47
- async current() {
48
- if (immutableContext.kind !== 'record') {
49
- throw new SpaceProtocolError({
50
- code: 'unavailable',
51
- message: 'The current record is available only when this Space is configured as a record view.',
52
- });
53
- }
54
- if (!transport) {
55
- throw new SpaceProtocolError({
56
- code: 'unavailable',
57
- message: 'The record protocol is unavailable for this record Space.',
58
- });
59
- }
60
- const request = {
61
- operation: 'record.current',
62
- payload: {},
63
- protocol: PROTOCOL_VERSION,
64
- requestId: nextRequestId(),
65
- };
66
- const response = await transport.request(request);
67
- const result = readResponse(response, request);
68
- if (!isCurrentRecordResult(result)) {
69
- throw invalidResponse('The primary-record response is malformed.');
70
- }
71
- return new ProtocolRecordHandle(result, nextRequestId, transport);
72
- },
73
- },
62
+ navigation: createNavigationClient(hostOrigin, navigationTransport),
63
+ records,
74
64
  tasks: createTasksClient(taskTransport, nextRequestId),
65
+ ui: {
66
+ header: createHeaderClient(immutableContext.kind === 'record', headerTransport, headerStatusTransport),
67
+ tabs: createTabsClient(immutableContext.kind === 'record', tabsTransport, nextRequestId),
68
+ toast: createToastClient(toastTransport),
69
+ },
75
70
  };
76
71
  }
77
72
  export function isSpaceContext(value) {
78
- if (!value || typeof value !== 'object') {
73
+ if (!isObjectRecord(value))
79
74
  return false;
80
- }
81
- const context = value;
82
- if (context.kind === 'standalone') {
75
+ if (value.kind === 'standalone')
83
76
  return true;
84
- }
85
- return context.kind === 'record'
86
- && typeof context.applicationId === 'string'
87
- && context.applicationId.length > 0
88
- && typeof context.tableName === 'string'
89
- && context.tableName.length > 0
90
- && typeof context.recordId === 'string'
91
- && context.recordId.length > 0;
77
+ return value.kind === 'record'
78
+ && typeof value.applicationId === 'string'
79
+ && value.applicationId.length > 0
80
+ && typeof value.tableName === 'string'
81
+ && value.tableName.length > 0
82
+ && typeof value.recordId === 'string'
83
+ && value.recordId.length > 0;
92
84
  }
93
85
  function executeData(dataTransport, document, variables) {
94
86
  if (!dataTransport) {
@@ -99,338 +91,8 @@ function executeData(dataTransport, document, variables) {
99
91
  }
100
92
  return dataTransport.execute(document, variables);
101
93
  }
102
- /**
103
- * A staged document is stored without being attached to a record, so staging
104
- * is available in any Space whose host negotiated the document protocol.
105
- */
106
- function createDocumentsClient(transport, nextRequestId) {
107
- return {
108
- async stage(document) {
109
- if (!transport) {
110
- throw new SpaceProtocolError({
111
- code: 'unavailable',
112
- message: 'Documents are unavailable because the Space host did not negotiate the document protocol.',
113
- });
114
- }
115
- const { file, mimeType, name } = readDocumentStageInput(document);
116
- // A Blob cannot itself be transferred. Its bytes are read into a buffer
117
- // once, and that buffer is handed to the host rather than copied again.
118
- const bytes = await file.arrayBuffer();
119
- const request = {
120
- operation: 'document.stage',
121
- payload: { bytes, mimeType, name },
122
- protocol: PROTOCOL_VERSION,
123
- requestId: nextRequestId(),
124
- };
125
- const response = await transport.request(request, [bytes]);
126
- const result = readResponse(response, request);
127
- if (!isDocumentStageResult(result))
128
- throw invalidResponse('The document-stage response is malformed.');
129
- return { handle: { ...result.handle } };
130
- },
131
- };
132
- }
133
- /**
134
- * Tasks are not tied to a page record, so they are available in any Space
135
- * whose host negotiated the task protocol, standalone or record.
136
- */
137
- function createTasksClient(transport, nextRequestId) {
138
- const requireTransport = () => {
139
- if (!transport) {
140
- throw new SpaceProtocolError({
141
- code: 'unavailable',
142
- message: 'Tasks are unavailable because the Space host did not negotiate the task protocol.',
143
- });
144
- }
145
- return transport;
146
- };
147
- return {
148
- async create(task) {
149
- const taskTransport = requireTransport();
150
- const request = {
151
- operation: 'task.create',
152
- payload: readTaskCreatePayload(task),
153
- protocol: PROTOCOL_VERSION,
154
- requestId: nextRequestId(),
155
- };
156
- const response = await taskTransport.request(request);
157
- const result = readResponse(response, request);
158
- if (!isTaskCreateResult(result))
159
- throw invalidResponse('The task-create response is malformed.');
160
- const { id, revision, status } = result.task;
161
- return { task: { id, revision, status } };
162
- },
163
- async reply(reply) {
164
- const taskTransport = requireTransport();
165
- const request = {
166
- operation: 'task.reply',
167
- payload: readTaskReplyPayload(reply),
168
- protocol: PROTOCOL_VERSION,
169
- requestId: nextRequestId(),
170
- };
171
- const response = await taskTransport.request(request);
172
- const result = readResponse(response, request);
173
- if (!isTaskReplyResult(result))
174
- throw invalidResponse('The task-reply response is malformed.');
175
- return { messageId: result.messageId, taskRevision: result.taskRevision };
176
- },
177
- };
178
- }
179
- class ProtocolRecordHandle {
180
- constructor({ sessionId, snapshot }, nextRequestId, transport) {
181
- _ProtocolRecordHandle_nextRequestId.set(this, void 0);
182
- _ProtocolRecordHandle_transport.set(this, void 0);
183
- _ProtocolRecordHandle_snapshot.set(this, void 0);
184
- this.id = sessionId;
185
- __classPrivateFieldSet(this, _ProtocolRecordHandle_nextRequestId, nextRequestId, "f");
186
- __classPrivateFieldSet(this, _ProtocolRecordHandle_snapshot, immutableSnapshot(snapshot), "f");
187
- __classPrivateFieldSet(this, _ProtocolRecordHandle_transport, transport, "f");
188
- }
189
- snapshot() {
190
- return __classPrivateFieldGet(this, _ProtocolRecordHandle_snapshot, "f");
191
- }
192
- async update(values) {
193
- const request = {
194
- operation: 'record.update',
195
- payload: {
196
- sessionId: this.id,
197
- values,
198
- },
199
- protocol: PROTOCOL_VERSION,
200
- requestId: __classPrivateFieldGet(this, _ProtocolRecordHandle_nextRequestId, "f").call(this),
201
- };
202
- const response = await __classPrivateFieldGet(this, _ProtocolRecordHandle_transport, "f").request(request);
203
- const result = readResponse(response, request);
204
- if (!isRecordUpdateResult(result))
205
- throw invalidResponse('The record-update response is malformed.');
206
- const snapshot = immutableSnapshot(result.snapshot);
207
- __classPrivateFieldSet(this, _ProtocolRecordHandle_snapshot, snapshot, "f");
208
- return { ok: result.ok, snapshot };
209
- }
210
- async submit() {
211
- const request = {
212
- operation: 'record.submit',
213
- payload: { sessionId: this.id },
214
- protocol: PROTOCOL_VERSION,
215
- requestId: __classPrivateFieldGet(this, _ProtocolRecordHandle_nextRequestId, "f").call(this),
216
- };
217
- const response = await __classPrivateFieldGet(this, _ProtocolRecordHandle_transport, "f").request(request);
218
- const result = readResponse(response, request);
219
- if (!isRecordSubmitResult(result))
220
- throw invalidResponse('The record-submit response is malformed.');
221
- const snapshot = immutableSnapshot(result.snapshot);
222
- __classPrivateFieldSet(this, _ProtocolRecordHandle_snapshot, snapshot, "f");
223
- return { ok: result.ok, snapshot };
224
- }
225
- }
226
- _ProtocolRecordHandle_nextRequestId = new WeakMap(), _ProtocolRecordHandle_transport = new WeakMap(), _ProtocolRecordHandle_snapshot = new WeakMap();
227
94
  function createRequestId() {
228
95
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')
229
96
  return crypto.randomUUID();
230
97
  return `space-request-${Math.random().toString(36).slice(2)}`;
231
98
  }
232
- function immutableSnapshot(snapshot) {
233
- if (!isRecordSnapshot(snapshot))
234
- throw invalidResponse('The record snapshot is malformed.');
235
- return deepFreeze(structuredClone(snapshot));
236
- }
237
- function immutableSpaceContext(context) {
238
- return deepFreeze(structuredClone(context));
239
- }
240
- function deepFreeze(value) {
241
- if (!value || typeof value !== 'object' || Object.isFrozen(value))
242
- return value;
243
- for (const child of Object.values(value))
244
- deepFreeze(child);
245
- return Object.freeze(value);
246
- }
247
- function invalidResponse(message) {
248
- return new SpaceProtocolError({ code: 'invalid_response', message });
249
- }
250
- function invalidRequest(message) {
251
- return new SpaceProtocolError({ code: 'invalid_request', message });
252
- }
253
- /**
254
- * Checks a task before it is sent, so a plain-JavaScript caller learns what is
255
- * wrong without a host round trip. The payload names only the members the
256
- * operation defines; an optional member left out is not sent at all.
257
- */
258
- function readTaskCreatePayload(task) {
259
- if (!isObjectRecord(task))
260
- throw invalidRequest('A task needs a title, a task type, and its input.');
261
- if (!isNonBlankString(task.title))
262
- throw invalidRequest('A task needs a title.');
263
- if (!isNonBlankString(task.taskTypeId))
264
- throw invalidRequest('A task needs the ID of its task type.');
265
- if (!isJsonObject(task.input))
266
- throw invalidRequest('A task input must be a JSON object, and everything in it a JSON value.');
267
- if (task.assignedToId !== undefined && !isNonBlankString(task.assignedToId))
268
- throw invalidRequest('A task assignee must be a user ID.');
269
- return {
270
- ...(task.assignedToId === undefined ? {} : { assignedToId: task.assignedToId }),
271
- input: task.input,
272
- taskTypeId: task.taskTypeId,
273
- title: task.title,
274
- };
275
- }
276
- function readTaskReplyPayload(reply) {
277
- if (!isObjectRecord(reply))
278
- throw invalidRequest('A task reply needs a task ID and its content.');
279
- if (!isNonBlankString(reply.taskId))
280
- throw invalidRequest('A task reply needs the ID of its task.');
281
- if (!isNonBlankString(reply.content))
282
- throw invalidRequest('A task reply needs content.');
283
- if (reply.inReplyToMessageId !== undefined && !isNonBlankString(reply.inReplyToMessageId))
284
- throw invalidRequest('A task reply can answer only a message ID.');
285
- return {
286
- content: reply.content,
287
- ...(reply.inReplyToMessageId === undefined ? {} : { inReplyToMessageId: reply.inReplyToMessageId }),
288
- taskId: reply.taskId,
289
- };
290
- }
291
- /**
292
- * The task.create contract takes an object for input, never null, an array, or
293
- * a single value, so a caller learns that here instead of from the host.
294
- */
295
- function isJsonObject(value) {
296
- return isObjectRecord(value) && isJsonValue(value);
297
- }
298
- /**
299
- * Accepts only what JSON carries unchanged. A structured clone would pass a
300
- * 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.
302
- */
303
- function isJsonValue(value, ancestors = new Set()) {
304
- if (value === null || typeof value === 'boolean' || typeof value === 'string')
305
- return true;
306
- if (typeof value === 'number')
307
- return Number.isFinite(value);
308
- if (!value || typeof value !== 'object' || ancestors.has(value))
309
- return false;
310
- const prototype = Object.getPrototypeOf(value);
311
- if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
312
- return false;
313
- ancestors.add(value);
314
- const valid = Object.values(value).every(child => isJsonValue(child, ancestors));
315
- ancestors.delete(value);
316
- return valid;
317
- }
318
- function readDocumentStageInput(document) {
319
- if (!isObjectRecord(document) || !isBlob(document.file))
320
- throw invalidRequest('A staged document needs a File or Blob.');
321
- const name = document.name ?? readFileName(document.file);
322
- if (!isNonBlankString(name))
323
- throw invalidRequest('A staged document needs a name, and a Blob has none of its own.');
324
- if (document.mimeType !== undefined && typeof document.mimeType !== 'string')
325
- throw invalidRequest('A staged document type must be a MIME type.');
326
- return {
327
- file: document.file,
328
- mimeType: document.mimeType || document.file.type || 'application/octet-stream',
329
- name,
330
- };
331
- }
332
- /** Duck-typed so a Blob from another realm, or a test double, is accepted. */
333
- function isBlob(value) {
334
- if (!isObjectRecord(value))
335
- return false;
336
- return typeof value.arrayBuffer === 'function' && typeof value.size === 'number' && typeof value.type === 'string';
337
- }
338
- function readFileName(file) {
339
- const { name } = file;
340
- return typeof name === 'string' ? name : undefined;
341
- }
342
- function isNonBlankString(value) {
343
- return typeof value === 'string' && value.trim().length > 0;
344
- }
345
- function isNonNegativeInteger(value) {
346
- return Number.isSafeInteger(value) && value >= 0;
347
- }
348
- const DOCUMENT_SCOPES = new Set([
349
- 'ephemeral',
350
- 'record',
351
- 'staged',
352
- ]);
353
- function isDocumentStageResult(value) {
354
- if (!isObjectRecord(value) || !isObjectRecord(value.handle))
355
- return false;
356
- const handle = value.handle;
357
- return isNonBlankString(handle.file_hash)
358
- && isNonBlankString(handle.filename)
359
- && typeof handle.mime_type === 'string'
360
- && isNonNegativeInteger(handle.size)
361
- && isNonBlankString(handle.storage_path)
362
- && (handle.scope === undefined || DOCUMENT_SCOPES.has(handle.scope));
363
- }
364
- const TASK_STATUSES = new Set([
365
- 'cancelled',
366
- 'completed',
367
- 'failed',
368
- 'in_progress',
369
- 'queued',
370
- 'waiting',
371
- ]);
372
- function isTaskCreateResult(value) {
373
- if (!isObjectRecord(value) || !isObjectRecord(value.task))
374
- return false;
375
- const { id, revision, status } = value.task;
376
- return isNonBlankString(id) && isNonNegativeInteger(revision) && TASK_STATUSES.has(status);
377
- }
378
- function isTaskReplyResult(value) {
379
- return isObjectRecord(value) && isNonBlankString(value.messageId) && isNonNegativeInteger(value.taskRevision);
380
- }
381
- function isCurrentRecordResult(value) {
382
- if (!value || typeof value !== 'object')
383
- return false;
384
- const result = value;
385
- return typeof result.sessionId === 'string' && result.sessionId.length > 0 && isRecordSnapshot(result.snapshot);
386
- }
387
- function isRecordSnapshot(value) {
388
- if (!value || typeof value !== 'object')
389
- return false;
390
- const snapshot = value;
391
- return Number.isSafeInteger(snapshot.revision)
392
- && (snapshot.revision ?? -1) >= 0
393
- && isRecordErrorSnapshot(snapshot.errors)
394
- && isRecordFieldSnapshotMap(snapshot.fields)
395
- && isObjectRecord(snapshot.values);
396
- }
397
- function isRecordUpdateResult(value) {
398
- if (!value || typeof value !== 'object')
399
- return false;
400
- const result = value;
401
- return typeof result.ok === 'boolean' && isRecordSnapshot(result.snapshot);
402
- }
403
- function isRecordSubmitResult(value) {
404
- if (!value || typeof value !== 'object')
405
- return false;
406
- const result = value;
407
- return typeof result.ok === 'boolean' && isRecordSnapshot(result.snapshot);
408
- }
409
- function isObjectRecord(value) {
410
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
411
- }
412
- function isRecordErrorSnapshot(value) {
413
- if (!isObjectRecord(value) || !isObjectRecord(value.fields) || !Array.isArray(value.form))
414
- return false;
415
- return Object.values(value.fields).every(errors => Array.isArray(errors) && errors.every(error => typeof error === 'string'))
416
- && value.form.every(error => isObjectRecord(error) && typeof error.code === 'string' && typeof error.message === 'string');
417
- }
418
- function isRecordFieldSnapshotMap(value) {
419
- return isObjectRecord(value) && Object.values(value).every((field) => {
420
- if (!isObjectRecord(field))
421
- return false;
422
- return (field.error === null || typeof field.error === 'string')
423
- && (field.info === null || typeof field.info === 'string')
424
- && typeof field.readOnly === 'boolean'
425
- && typeof field.required === 'boolean'
426
- && typeof field.visible === 'boolean';
427
- });
428
- }
429
- function readResponse(response, request) {
430
- if (response.protocol !== PROTOCOL_VERSION || response.requestId !== request.requestId) {
431
- throw invalidResponse('The response does not match the request envelope.');
432
- }
433
- if (!response.ok)
434
- throw new SpaceProtocolError(response.error);
435
- return response.result;
436
- }
@@ -0,0 +1,25 @@
1
+ import type { DocumentHandle } from '../types.js';
2
+ import type { SpaceTransport } from './protocol.js';
3
+ /** A file stored but not yet attached to a record. */
4
+ export interface StagedDocumentHandle extends DocumentHandle {
5
+ scope?: 'ephemeral' | 'record' | 'staged';
6
+ }
7
+ export interface DocumentStageInput {
8
+ /** The file to stage. Its bytes are transferred to the host, not copied. */
9
+ file: Blob | File;
10
+ /** Defaults to the file's own type, then to `application/octet-stream`. */
11
+ mimeType?: string;
12
+ /** Defaults to a File's name. A plain Blob needs an explicit name. */
13
+ name?: string;
14
+ }
15
+ export interface DocumentStageResult {
16
+ handle: StagedDocumentHandle;
17
+ }
18
+ export interface SimpleDocumentsClient {
19
+ stage: (document: DocumentStageInput) => Promise<DocumentStageResult>;
20
+ }
21
+ /**
22
+ * Uploads a file to staging without attaching it to a record. The host owns
23
+ * storage and returns only the document handle needed by the Space's workflow.
24
+ */
25
+ export declare function createDocumentsClient(transport: SpaceTransport | undefined, nextRequestId: () => string): SimpleDocumentsClient;
@@ -0,0 +1,72 @@
1
+ import { invalidRequest, invalidResponse, isNonBlankString, isNonNegativeInteger, isObjectRecord, PROTOCOL_VERSION, readResponse, SpaceProtocolError, } from './protocol.js';
2
+ /**
3
+ * Uploads a file to staging without attaching it to a record. The host owns
4
+ * storage and returns only the document handle needed by the Space's workflow.
5
+ */
6
+ export function createDocumentsClient(transport, nextRequestId) {
7
+ return {
8
+ async stage(document) {
9
+ if (!transport) {
10
+ throw new SpaceProtocolError({
11
+ code: 'unavailable',
12
+ message: 'Documents are unavailable because the Space host did not negotiate the document protocol.',
13
+ });
14
+ }
15
+ const { file, mimeType, name } = readDocumentStageInput(document);
16
+ const bytes = await file.arrayBuffer();
17
+ const request = {
18
+ operation: 'document.stage',
19
+ payload: { bytes, mimeType, name },
20
+ protocol: PROTOCOL_VERSION,
21
+ requestId: nextRequestId(),
22
+ };
23
+ const response = await transport.request(request, [bytes]);
24
+ const result = readResponse(response, request);
25
+ if (!isDocumentStageResult(result))
26
+ throw invalidResponse('The document-stage response is malformed.');
27
+ // Preserve host-added handle metadata while returning a Space-owned value.
28
+ return { handle: { ...result.handle } };
29
+ },
30
+ };
31
+ }
32
+ function readDocumentStageInput(document) {
33
+ if (!isObjectRecord(document) || !isBlob(document.file))
34
+ throw invalidRequest('A staged document needs a File or Blob.');
35
+ const name = document.name ?? readFileName(document.file);
36
+ if (!isNonBlankString(name))
37
+ throw invalidRequest('A staged document needs a name, and a Blob has none of its own.');
38
+ if (document.mimeType !== undefined && typeof document.mimeType !== 'string')
39
+ throw invalidRequest('A staged document type must be a MIME type.');
40
+ return {
41
+ file: document.file,
42
+ mimeType: document.mimeType || document.file.type || 'application/octet-stream',
43
+ name,
44
+ };
45
+ }
46
+ /** Duck-typed so a Blob from another realm, or a test double, is accepted. */
47
+ function isBlob(value) {
48
+ return isObjectRecord(value)
49
+ && typeof value.arrayBuffer === 'function'
50
+ && typeof value.size === 'number'
51
+ && typeof value.type === 'string';
52
+ }
53
+ function readFileName(file) {
54
+ const { name } = file;
55
+ return typeof name === 'string' ? name : undefined;
56
+ }
57
+ const DOCUMENT_SCOPES = new Set([
58
+ 'ephemeral',
59
+ 'record',
60
+ 'staged',
61
+ ]);
62
+ function isDocumentStageResult(value) {
63
+ if (!isObjectRecord(value) || !isObjectRecord(value.handle))
64
+ return false;
65
+ const handle = value.handle;
66
+ return isNonBlankString(handle.file_hash)
67
+ && isNonBlankString(handle.filename)
68
+ && typeof handle.mime_type === 'string'
69
+ && isNonNegativeInteger(handle.size)
70
+ && isNonBlankString(handle.storage_path)
71
+ && (handle.scope === undefined || DOCUMENT_SCOPES.has(handle.scope));
72
+ }
@@ -1,34 +1,9 @@
1
1
  import type { SimpleClient } from './core.js';
2
- import { SpaceDataError, SpaceProtocolError } from './core.js';
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';
5
- interface MessagePortLike {
6
- onmessage: null | ((event: {
7
- data: unknown;
8
- }) => void);
9
- postMessage: (message: unknown, transfer?: ArrayBuffer[]) => void;
10
- start?: () => void;
11
- }
12
- export interface SpaceWindowLike {
13
- addEventListener: (type: 'message', listener: (event: SpaceMessageEvent) => void) => void;
14
- parent: {
15
- postMessage: (message: unknown, targetOrigin: string) => void;
16
- };
17
- removeEventListener: (type: 'message', listener: (event: SpaceMessageEvent) => void) => void;
18
- }
19
- export interface SpaceMessageEvent {
20
- data: unknown;
21
- origin: string;
22
- ports: MessagePortLike[];
23
- }
24
- export interface ConnectSpaceOptions {
2
+ import { HEADER_ACTIONS_PROTOCOL_VERSION, HEADER_STATUS_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION } from './core.js';
3
+ export { HEADER_ACTIONS_PROTOCOL_VERSION, HEADER_STATUS_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, SimpleHeaderStatusClient, SimpleNavigationClient, SimpleRecordsClient, SimpleTabsClient, SimpleTasksClient, SimpleToastClient, SpaceContext, SpaceDataErrorPayload, SpaceHeaderStatus, SpaceHeaderStatusTransport, SpaceNavigationTransport, SpaceProtocolErrorPayload, SpaceStatusTone, SpaceTab, SpaceTabsSelectionEvent, SpaceTabsTransport, SpaceToastOptions, SpaceToastVariant, StagedDocumentHandle, TaskCreateInput, TaskCreateResult, TaskReplyInput, TaskReplyResult, TaskStatus, } from './core.js';
5
+ export interface ConnectOptions {
25
6
  targetOrigin: string;
26
- window?: SpaceWindowLike;
27
7
  }
28
- /**
29
- * Connects any embedded Space to its parent through the dedicated MessagePort
30
- * handshake. Each protocol capability is offered in `SPACE_READY` and becomes
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.
33
- */
34
- export declare function connectSpace({ targetOrigin, window }: ConnectSpaceOptions): Promise<SimpleClient>;
8
+ /** Connects this Space to its host using the explicitly supplied host origin. */
9
+ export declare function connect({ targetOrigin }: ConnectOptions): Promise<SimpleClient>;