@simpleplatform/sdk 3.0.3 → 3.1.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
@@ -345,11 +345,21 @@ switch (simple.context.kind) {
345
345
  }
346
346
  ```
347
347
 
348
- The two exact context forms are `{ kind: 'standalone' }` and
349
- `{ kind: 'record', applicationId, tableName, recordId }`. There is no
348
+ The two context forms are `{ kind: 'standalone', user?, tenant? }` and
349
+ `{ kind: 'record', applicationId, tableName, recordId, user?, tenant? }`. There is no
350
350
  `unknown` context variant. A missing or malformed context rejects
351
351
  `connect({ targetOrigin })` with `SpaceProtocolError` code `invalid_response`.
352
352
 
353
+ `simple.context.user` and `simple.context.tenant` name the signed-in user and
354
+ the tenant exactly as an action's context names them, with the SDK's own `User`
355
+ and `Tenant` types: `user.id`, and `tenant.id`, `tenant.name` and `tenant.host`.
356
+ They are present from the host version that adds them to initialization
357
+ context. Older hosts omit them, so a Space handles `undefined` explicitly before
358
+ using `user.id`, for example to filter the tasks assigned to the viewer. The
359
+ SDK never invents them or derives them from `recordId`. Supplied text must be
360
+ non-blank; otherwise the context is malformed. This is descriptive identity,
361
+ not an authorization grant: the host and server still enforce access.
362
+
353
363
  `connect({ targetOrigin })` works in any embedded Space, including standalone dashboards
354
364
  and tools. In a non-record Space, `simple.data` remains available and
355
365
  `simple.records.open()` succeeds whenever the records capability was negotiated,
@@ -2,6 +2,7 @@ import type { SpaceDataTransport } from './core.js';
2
2
  import type { SpaceNavigationTransport } from './navigation.js';
3
3
  import type { SpaceTransport } from './protocol.js';
4
4
  import type { RecordFormCapabilities } from './record-form.js';
5
+ import type { SpaceThemeSnapshot } from './theme.js';
5
6
  import type { SpaceHeaderStatusTransport, SpaceHeaderTransport, SpaceTabsTransport, SpaceToastTransport } from './ui.js';
6
7
  export interface MessagePortLike {
7
8
  close?: () => void;
@@ -15,4 +16,4 @@ export interface BrowserSpaceTransport extends SpaceDataTransport, SpaceHeaderSt
15
16
  capabilities: RecordFormCapabilities;
16
17
  subscribeFormModel: (listener: (form: unknown) => void) => () => void;
17
18
  }
18
- export declare function createMessagePortTransport(port: MessagePortLike, targetOrigin: string): BrowserSpaceTransport;
19
+ export declare function createMessagePortTransport(port: MessagePortLike, targetOrigin: string, onThemeChanged?: (theme: SpaceThemeSnapshot) => void): BrowserSpaceTransport;
@@ -1,6 +1,7 @@
1
1
  import { SpaceDataError, SpaceProtocolError, } from './protocol.js';
2
2
  import { createFormModelSubscriptionManager, createRecordFormCapabilities, } from './record-form.js';
3
- export function createMessagePortTransport(port, targetOrigin) {
3
+ import { parseThemeSnapshot } from './theme.js';
4
+ export function createMessagePortTransport(port, targetOrigin, onThemeChanged) {
4
5
  const headerCallbacks = new Map();
5
6
  const formModelManager = createFormModelSubscriptionManager();
6
7
  const pendingData = new Map();
@@ -22,6 +23,15 @@ export function createMessagePortTransport(port, targetOrigin) {
22
23
  formModelManager.handleUpdate(envelope.form);
23
24
  return;
24
25
  }
26
+ if (envelope.type === 'THEME_CHANGED') {
27
+ if (onThemeChanged) {
28
+ const snapshot = parseThemeSnapshot(envelope.theme);
29
+ if (snapshot) {
30
+ onThemeChanged(snapshot);
31
+ }
32
+ }
33
+ return;
34
+ }
25
35
  if (envelope.type === 'SPACE_PROTOCOL_RESPONSE' && envelope.response) {
26
36
  const requestId = envelope.response.requestId;
27
37
  const request = pending.get(requestId);
@@ -1,3 +1,4 @@
1
+ import type { Tenant, User } from '../types.js';
1
2
  import type { SimpleActionsClient } from './actions.js';
2
3
  import type { SimpleDocumentsClient } from './documents.js';
3
4
  import type { SimpleNavigationClient, SpaceNavigationTransport } from './navigation.js';
@@ -23,8 +24,16 @@ export type SpaceContext = {
23
24
  kind: 'record';
24
25
  recordId: string;
25
26
  tableName: string;
27
+ /** The tenant the Space runs in, named as an action's context names it. Absent on older hosts. */
28
+ tenant?: Tenant;
29
+ /** The signed-in user, named as an action's context names it. Absent on older hosts. */
30
+ user?: User;
26
31
  } | {
27
32
  kind: 'standalone';
33
+ /** The tenant the Space runs in, named as an action's context names it. Absent on older hosts. */
34
+ tenant?: Tenant;
35
+ /** The signed-in user, named as an action's context names it. Absent on older hosts. */
36
+ user?: User;
28
37
  };
29
38
  export type GraphQLVariables = Readonly<Record<string, unknown>>;
30
39
  export interface SpaceDataTransport {
@@ -1,7 +1,7 @@
1
1
  import { createActionsClient } from './actions.js';
2
2
  import { createDocumentsClient } from './documents.js';
3
3
  import { createNavigationClient } from './navigation.js';
4
- import { deepFreeze, invalidResponse, isObjectRecord, PROTOCOL_VERSION, readResponse, SpaceDataError, SpaceProtocolError } from './protocol.js';
4
+ import { deepFreeze, invalidResponse, isNonBlankString, isObjectRecord, PROTOCOL_VERSION, readResponse, SpaceDataError, SpaceProtocolError } from './protocol.js';
5
5
  import { createRecordsClient, isCurrentRecordResult, ProtocolRecordHandle } from './record.js';
6
6
  import { createTasksClient } from './tasks.js';
7
7
  import { createHeaderClient, createTabsClient, createToastClient, validateSpaceToastOptions } from './ui.js';
@@ -69,9 +69,24 @@ export function createSimpleClient({ actionTransport, capabilities, context = {
69
69
  },
70
70
  };
71
71
  }
72
+ /** An action's context names the user by an optional ID; a supplied ID is non-blank. */
73
+ function isContextUser(value) {
74
+ return isObjectRecord(value) && (value.id === undefined || isNonBlankString(value.id));
75
+ }
76
+ /** An action's context names the tenant, with an optional ID and host; supplied text is non-blank. */
77
+ function isContextTenant(value) {
78
+ return isObjectRecord(value)
79
+ && isNonBlankString(value.name)
80
+ && (value.id === undefined || isNonBlankString(value.id))
81
+ && (value.host === undefined || isNonBlankString(value.host));
82
+ }
72
83
  export function isSpaceContext(value) {
73
84
  if (!isObjectRecord(value))
74
85
  return false;
86
+ if (value.user !== undefined && !isContextUser(value.user))
87
+ return false;
88
+ if (value.tenant !== undefined && !isContextTenant(value.tenant))
89
+ return false;
75
90
  if (value.kind === 'standalone')
76
91
  return true;
77
92
  return value.kind === 'record'
@@ -1,6 +1,7 @@
1
1
  import { createMessagePortTransport } from './browser-transport.js';
2
2
  import { createSimpleClient, HEADER_ACTIONS_PROTOCOL_VERSION, HEADER_STATUS_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
3
  import { isObjectRecord } from './protocol.js';
4
+ import { applyThemeSnapshot, parseThemeSnapshot, THEME_PROTOCOL_VERSION } from './theme.js';
4
5
  export { HEADER_ACTIONS_PROTOCOL_VERSION, HEADER_STATUS_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION };
5
6
  const connections = new WeakMap();
6
7
  /** Connects this Space to its host using the explicitly supplied host origin. */
@@ -28,7 +29,8 @@ export function connect({ targetOrigin }) {
28
29
  }));
29
30
  }
30
31
  // The host cannot style a cross-origin frame's viewport, where edge bounce occurs.
31
- window.document.documentElement.style.overscrollBehaviorY = 'none';
32
+ if (window.document.documentElement?.style)
33
+ window.document.documentElement.style.overscrollBehaviorY = 'none';
32
34
  const promise = new Promise((resolve, reject) => {
33
35
  const onMessage = (event) => {
34
36
  if (event.origin !== targetOrigin || !isInitializationMessage(event.data))
@@ -49,7 +51,21 @@ export function connect({ targetOrigin }) {
49
51
  }));
50
52
  return;
51
53
  }
52
- const transport = createMessagePortTransport(port, targetOrigin);
54
+ const isThemeNegotiated = event.data.protocols?.theme === THEME_PROTOCOL_VERSION;
55
+ const appliedThemeTokens = new Set();
56
+ const fontState = { fontLink: null };
57
+ if (isThemeNegotiated && event.data.theme !== undefined) {
58
+ const initialTheme = parseThemeSnapshot(event.data.theme);
59
+ if (initialTheme) {
60
+ applyThemeSnapshot(window.document, appliedThemeTokens, initialTheme, fontState);
61
+ }
62
+ }
63
+ const onThemeChanged = isThemeNegotiated
64
+ ? (snapshot) => {
65
+ applyThemeSnapshot(window.document, appliedThemeTokens, snapshot, fontState);
66
+ }
67
+ : undefined;
68
+ const transport = createMessagePortTransport(port, targetOrigin, onThemeChanged);
53
69
  const protocols = event.data.protocols;
54
70
  const hasRecord = protocols?.record === PROTOCOL_VERSION;
55
71
  const hasRecords = protocols?.records === RECORDS_PROTOCOL_VERSION;
@@ -84,6 +100,7 @@ export function connect({ targetOrigin }) {
84
100
  records: [RECORDS_PROTOCOL_VERSION],
85
101
  tabs: [TABS_PROTOCOL_VERSION],
86
102
  task: [PROTOCOL_VERSION],
103
+ theme: [THEME_PROTOCOL_VERSION],
87
104
  toast: [TOAST_PROTOCOL_VERSION],
88
105
  },
89
106
  type: 'SPACE_READY',
@@ -0,0 +1,60 @@
1
+ export declare const THEME_PROTOCOL_VERSION: 1;
2
+ export interface SpaceThemeFontDescriptor {
3
+ family: string;
4
+ provider: 'google';
5
+ weights: number[];
6
+ }
7
+ export interface SpaceThemeFonts {
8
+ mono?: SpaceThemeFontDescriptor;
9
+ sans?: SpaceThemeFontDescriptor;
10
+ }
11
+ export interface SpaceThemeSnapshot {
12
+ fonts?: SpaceThemeFonts;
13
+ mode: 'light' | 'dark';
14
+ tokens: Record<string, string>;
15
+ version: 1;
16
+ }
17
+ export interface SpaceDocumentElementLike {
18
+ classList?: {
19
+ contains?: (token: string) => boolean;
20
+ toggle?: (token: string, force?: boolean) => boolean;
21
+ };
22
+ style?: {
23
+ overscrollBehaviorY?: string;
24
+ removeProperty?: (property: string) => string;
25
+ setProperty?: (property: string, value: string) => void;
26
+ } & Record<string, unknown>;
27
+ }
28
+ export interface SpaceLinkElementLike {
29
+ as?: string;
30
+ crossOrigin?: string;
31
+ getAttribute?: (name: string) => string | null;
32
+ href?: string;
33
+ id?: string;
34
+ rel?: string;
35
+ remove?: () => void;
36
+ setAttribute?: (name: string, value: string) => void;
37
+ [key: string]: unknown;
38
+ }
39
+ export interface SpaceHeadElementLike {
40
+ appendChild?: (node: SpaceLinkElementLike) => SpaceLinkElementLike | unknown;
41
+ children?: SpaceLinkElementLike[] | unknown;
42
+ querySelector?: (selector: string) => SpaceLinkElementLike | null;
43
+ removeChild?: (node: SpaceLinkElementLike) => SpaceLinkElementLike | unknown;
44
+ [key: string]: unknown;
45
+ }
46
+ export interface SpaceDocumentLike {
47
+ createElement?: (tagName: string) => SpaceLinkElementLike | unknown;
48
+ documentElement?: SpaceDocumentElementLike;
49
+ head?: SpaceHeadElementLike;
50
+ querySelector?: (selector: string) => SpaceLinkElementLike | null;
51
+ [key: string]: unknown;
52
+ }
53
+ export interface SpaceFontState {
54
+ fontLink?: SpaceLinkElementLike | null;
55
+ }
56
+ export declare function parseFontDescriptor(value: unknown): SpaceThemeFontDescriptor | null;
57
+ export declare function buildGoogleFontUrl(fonts: SpaceThemeFonts | undefined): string | null;
58
+ export declare function parseThemeSnapshot(value: unknown): SpaceThemeSnapshot | null;
59
+ export declare function syncGoogleFontLink(document: SpaceDocumentLike | undefined, fonts: SpaceThemeFonts | undefined, fontState?: SpaceFontState): void;
60
+ export declare function applyThemeSnapshot(target: SpaceDocumentLike | SpaceDocumentElementLike | undefined, appliedTokens: Set<string>, snapshot: SpaceThemeSnapshot, fontState?: SpaceFontState): void;
@@ -0,0 +1,194 @@
1
+ import { isObjectRecord } from './protocol.js';
2
+ export const THEME_PROTOCOL_VERSION = 1;
3
+ const FAMILY_NAME_PATTERN = /^[A-Z0-9]+(?:[ -][A-Z0-9]+)*$/i;
4
+ export function parseFontDescriptor(value) {
5
+ if (!isObjectRecord(value))
6
+ return null;
7
+ const keys = Object.keys(value);
8
+ if (keys.length !== 3 || !('provider' in value) || !('family' in value) || !('weights' in value))
9
+ return null;
10
+ if (value.provider !== 'google')
11
+ return null;
12
+ if (typeof value.family !== 'string' || value.family.length === 0 || value.family.length > 100)
13
+ return null;
14
+ if (!FAMILY_NAME_PATTERN.test(value.family))
15
+ return null;
16
+ if (!Array.isArray(value.weights) || value.weights.length === 0)
17
+ return null;
18
+ const weights = [];
19
+ const seenWeights = new Set();
20
+ for (const w of value.weights) {
21
+ if (typeof w !== 'number' || !Number.isInteger(w) || w < 100 || w > 900 || w % 100 !== 0)
22
+ return null;
23
+ if (seenWeights.has(w))
24
+ return null;
25
+ seenWeights.add(w);
26
+ weights.push(w);
27
+ }
28
+ return {
29
+ family: value.family,
30
+ provider: 'google',
31
+ weights,
32
+ };
33
+ }
34
+ export function buildGoogleFontUrl(fonts) {
35
+ if (!fonts)
36
+ return null;
37
+ const fontEntries = [fonts.sans, fonts.mono].filter((d) => !!d);
38
+ if (fontEntries.length === 0)
39
+ return null;
40
+ const familyMap = new Map();
41
+ for (const entry of fontEntries) {
42
+ if (entry.provider !== 'google')
43
+ continue;
44
+ let weights = familyMap.get(entry.family);
45
+ if (!weights) {
46
+ weights = new Set();
47
+ familyMap.set(entry.family, weights);
48
+ }
49
+ for (const w of entry.weights) {
50
+ weights.add(w);
51
+ }
52
+ }
53
+ if (familyMap.size === 0)
54
+ return null;
55
+ const params = [];
56
+ for (const [family, weightsSet] of familyMap.entries()) {
57
+ const sortedWeights = Array.from(weightsSet).sort((a, b) => a - b);
58
+ const formattedFamily = family.replace(/ /g, '+');
59
+ params.push(`family=${formattedFamily}:wght@${sortedWeights.join(';')}`);
60
+ }
61
+ return `https://fonts.googleapis.com/css2?${params.join('&')}&display=swap`;
62
+ }
63
+ export function parseThemeSnapshot(value) {
64
+ if (!isObjectRecord(value))
65
+ return null;
66
+ const { mode, tokens, version } = value;
67
+ if (version !== 1 || (mode !== 'light' && mode !== 'dark') || !isObjectRecord(tokens))
68
+ return null;
69
+ const acceptedTokens = {};
70
+ for (const [name, tokenValue] of Object.entries(tokens)) {
71
+ if (name.startsWith('--simple-') && typeof tokenValue === 'string') {
72
+ acceptedTokens[name] = tokenValue;
73
+ }
74
+ }
75
+ let acceptedFonts;
76
+ if (isObjectRecord(value.fonts)) {
77
+ const sans = parseFontDescriptor(value.fonts.sans);
78
+ const mono = parseFontDescriptor(value.fonts.mono);
79
+ if (sans || mono) {
80
+ acceptedFonts = {};
81
+ if (sans)
82
+ acceptedFonts.sans = sans;
83
+ if (mono)
84
+ acceptedFonts.mono = mono;
85
+ }
86
+ }
87
+ const snapshot = {
88
+ mode,
89
+ tokens: acceptedTokens,
90
+ version: 1,
91
+ };
92
+ if (acceptedFonts) {
93
+ snapshot.fonts = acceptedFonts;
94
+ }
95
+ return snapshot;
96
+ }
97
+ export function syncGoogleFontLink(document, fonts, fontState) {
98
+ if (!document || !document.head)
99
+ return;
100
+ const head = document.head;
101
+ const url = buildGoogleFontUrl(fonts);
102
+ let link = fontState?.fontLink ?? null;
103
+ if (link && Array.isArray(head.children) && !head.children.includes(link)) {
104
+ link = null;
105
+ }
106
+ if (!link) {
107
+ if (typeof head.querySelector === 'function') {
108
+ link = head.querySelector('link[data-simple-font="google"]');
109
+ }
110
+ else if (typeof document.querySelector === 'function') {
111
+ link = document.querySelector('link[data-simple-font="google"]');
112
+ }
113
+ else if (Array.isArray(head.children)) {
114
+ link = head.children.find(child => child.rel === 'stylesheet' && ((typeof child.getAttribute === 'function' && child.getAttribute('data-simple-font') === 'google')
115
+ || child['data-simple-font'] === 'google')) ?? null;
116
+ }
117
+ }
118
+ if (url) {
119
+ if (link) {
120
+ link.href = url;
121
+ }
122
+ else if (typeof document.createElement === 'function' && typeof head.appendChild === 'function') {
123
+ const newLink = document.createElement('link');
124
+ newLink.rel = 'stylesheet';
125
+ newLink.href = url;
126
+ if (typeof newLink.setAttribute === 'function') {
127
+ newLink.setAttribute('data-simple-font', 'google');
128
+ }
129
+ else {
130
+ newLink['data-simple-font'] = 'google';
131
+ }
132
+ head.appendChild(newLink);
133
+ link = newLink;
134
+ }
135
+ if (fontState) {
136
+ fontState.fontLink = link;
137
+ }
138
+ }
139
+ else {
140
+ if (link) {
141
+ if (typeof link.remove === 'function') {
142
+ link.remove();
143
+ }
144
+ else if (typeof head.removeChild === 'function') {
145
+ head.removeChild(link);
146
+ }
147
+ }
148
+ if (fontState) {
149
+ fontState.fontLink = null;
150
+ }
151
+ }
152
+ }
153
+ function isDocumentLike(value) {
154
+ return 'documentElement' in value || 'head' in value || 'createElement' in value;
155
+ }
156
+ export function applyThemeSnapshot(target, appliedTokens, snapshot, fontState) {
157
+ if (!target)
158
+ return;
159
+ const document = isDocumentLike(target)
160
+ ? target
161
+ : undefined;
162
+ const documentElement = isDocumentLike(target)
163
+ ? target.documentElement
164
+ : target;
165
+ if (documentElement) {
166
+ if (typeof documentElement.classList?.toggle === 'function') {
167
+ documentElement.classList.toggle('dark', snapshot.mode === 'dark');
168
+ }
169
+ const style = documentElement.style;
170
+ if (style) {
171
+ for (const name of appliedTokens) {
172
+ if (typeof style.removeProperty === 'function') {
173
+ style.removeProperty(name);
174
+ }
175
+ else {
176
+ delete style[name];
177
+ }
178
+ }
179
+ appliedTokens.clear();
180
+ for (const [name, value] of Object.entries(snapshot.tokens)) {
181
+ if (typeof style.setProperty === 'function') {
182
+ style.setProperty(name, value);
183
+ }
184
+ else {
185
+ style[name] = value;
186
+ }
187
+ appliedTokens.add(name);
188
+ }
189
+ }
190
+ }
191
+ if (document) {
192
+ syncGoogleFontLink(document, snapshot.fonts, fontState);
193
+ }
194
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpleplatform/sdk",
3
- "version": "3.0.3",
3
+ "version": "3.1.0",
4
4
  "description": "Simple Platform Typescript SDK",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://docs.simple.dev",