@seliseblocks/client 0.1.5 → 0.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
@@ -1,222 +1,234 @@
1
- # Blocks Client
2
-
3
- Framework-neutral TypeScript SDK for SELISE Blocks frontend and app-runtime code.
4
-
5
- `@seliseblocks/client` gives consumer apps a small, typed wrapper around the Blocks APIs they normally call at runtime: Auth/IAM, Data, Localization, and shared HTTP configuration. Detailed `what / why / how` descriptions are kept on the SDK functions themselves so editors and generated typings show the guidance where developers use the API.
6
-
7
- Admin/control-plane work belongs in `@seliseblocks/cli-os`: project setup, schema/rules deploy, release deploy, and AI/admin terminal workflows.
8
-
9
- For AI agents and automation, see [AI_USAGE_GUIDE.md](AI_USAGE_GUIDE.md).
10
-
11
- ## Install
12
-
13
- ```bash
14
- npm install @seliseblocks/client@latest
15
- ```
16
-
17
- Requires Node.js 20+ or a browser/runtime with `fetch`.
18
-
19
- ## Create A Client
20
-
21
- ```ts
22
- import { createBlocksClient } from "@seliseblocks/client";
23
-
24
- const blocks = createBlocksClient({
25
- apiUrl: "https://api.seliseblocks.com",
26
- xBlocksKey: "<blocks-key>",
27
- accessToken: () => currentUserSession?.accessToken,
28
- oidc: {
29
- url: "https://iam.seliseblocks.com",
30
- clientId: "<public-browser-client-id>",
31
- redirectUri: configuredRedirectUri ?? `${window.location.origin}/login/callback`
32
- }
33
- });
34
- ```
35
-
36
- `xBlocksKey` is always sent as the `x-blocks-key` header. Do not send `ProjectKey` or `projectKey` in request query/body payloads.
37
-
38
- The SDK does not store tokens. Your app owns login state, refresh scheduling, storage, and logout cleanup.
39
-
40
- Use a configured OIDC redirect URI when your app has one. The current-origin `/login/callback` URL is only a browser fallback.
41
-
42
- ## Auth
43
-
44
- Auth has two login flows.
45
-
46
- OIDC/hosted IAM login uses `auth.idp`. The SDK relies on Blocks IAM `IdpController`, sends the configured public `clientId`, and does not manually build `oidc/authorize` URLs. Refresh OIDC sessions with `auth.oidc.refreshToken()`, which calls `/iam/v4/oidc/token` and sends `client_id`.
47
-
48
- ```ts
49
- await blocks.auth.idp.redirectToProvider();
50
-
51
- const result = await blocks.auth.idp.callback(window.location.href);
52
-
53
- const refreshed = await blocks.auth.oidc.refreshToken({
54
- refreshToken: result.refresh_token,
55
- clientId: "<public-browser-client-id>"
56
- });
57
- ```
58
-
59
- Embedded/app-owned login UI uses AuthController methods directly on `auth`: `auth.login()`, `auth.socialInitiate(clientId, redirectUri)` (two positional strings, not an object), `auth.socialCallback(request)`, and `auth.refresh()`.
60
-
61
- ```ts
62
- const login = await blocks.auth.login({
63
- username: "user@example.com",
64
- password: "password"
65
- });
66
-
67
- const refreshed = await blocks.auth.refresh({
68
- refreshToken: login.refresh_token
69
- });
70
- ```
71
-
72
- Other auth APIs, such as user info, organization switch, logout, signup, recovery, activation, auth config, user codes, client credentials, and identity providers, can be used by either flow when the app has the required token/permission.
73
-
74
- `auth.oidc.clientCredentials()` is for trusted non-browser runtimes only because it requires a client secret.
75
-
76
- `auth.accessToken()` resolves the caller-owned bearer token configured on `createBlocksClient` (string or callback). `auth.isAuthenticated()` checks the current session against IAM through `GET /iam/v4/auth/me` and returns a boolean based on the raw response status - use it instead of `userInfo()` when you need a true/false signal, since IAM's hosted IdP flow may set the session as a cookie with no local `accessToken` to inspect.
77
-
78
- ```ts
79
- const config = await blocks.mfa.config();
80
- await blocks.mfa.totp.setup();
81
- await blocks.mfa.totp.verifySetup({ code: "123456" });
82
- await blocks.mfa.setMethod({ mfaType: 1 });
83
- const backupCodes = await blocks.mfa.backupCodes.generate();
84
- ```
85
-
86
- ## Mail And Notifications
87
-
88
- ```ts
89
- await blocks.mail.send({
90
- to: ["user@example.com"],
91
- purpose: "welcome",
92
- language: "en",
93
- subjectDataContext: { firstName: "Ada" }
94
- });
95
-
96
- await blocks.mail.sendToAny({
97
- to: ["qa@example.com"],
98
- purpose: "welcome",
99
- language: "en",
100
- isTestMail: true
101
- });
102
-
103
- await blocks.notifier.notify({
104
- userIds: ["user-id"],
105
- denormalizedPayload: JSON.stringify({ orderId: "123" }),
106
- saveDenormalizedPayloadAsAnObject: true
107
- });
108
-
109
- const inbox = await blocks.notifier.getNotifications({ isUnreadOnly: true, page: 1, pageSize: 20 });
110
- await blocks.notifier.markNotificationAsRead({ id: inbox.notifications[0].id });
111
- await blocks.notifier.markAllNotificationAsRead();
112
- ```
113
-
114
- `mail.send`/`mail.sendToAny` call `/logic/v4/Mail/Send`/`SendToAny`. `notifier.*` calls `/logic/v4/Notifier/*`
115
- for sending/reading notifications; tenant notification *channel configuration* (`/os/v4/Notification/*`)
116
- is an admin concern handled by `@seliseblocks/cli-os`'s `notification *` commands, not this SDK.
117
-
118
- ## Common Runtime Calls
119
-
120
- ```ts
121
- const me = await blocks.iam.me();
122
- const orgs = await blocks.iam.organizations.my();
123
- const features = await blocks.iam.resources.features();
124
- ```
125
-
126
- `iam.organizations.my()` returns the IAM envelope with `organizations`, not `data`.
127
-
128
- ```ts
129
- const schemas = await blocks.data.schemas.list();
130
- const schemaInfo = await blocks.data.schemas.infoByName("Student");
131
- const schemaRules = await blocks.data.validations.bySchemaId("schema-id");
132
-
133
- const students = blocks.data.collection("Students");
134
- const rows = await students.list({ pageNo: 1, pageSize: 20 });
135
- await students.create({ firstName: "Test" });
136
-
137
- const graph = await blocks.data.graphql({
138
- query: "{ students { items { itemId firstName } } }"
139
- });
140
- ```
141
-
142
- ```ts
143
- const upload = await blocks.data.files.presignedUploadUrl({
144
- name: "avatar.png",
145
- configurationName: "default",
146
- parentDirectoryId: "root",
147
- accessModifier: "Private"
148
- });
149
-
150
- await blocks.data.files.uploadToUrl({
151
- url: upload.uploadUrl,
152
- body: file,
153
- contentType: file.type
154
- });
155
-
156
- const items = await blocks.data.objects.list({
157
- parentDirectoryId: "root",
158
- limit: 20
159
- });
160
-
161
- const directory = await blocks.data.directories.create({
162
- name: "Contracts",
163
- parentDirectoryId: "root",
164
- allowedFileExtensions: ["pdf", "docx"]
165
- });
166
- ```
167
-
168
- ```ts
169
- await blocks.localization.load("en-US", ["common", "dashboard"]);
170
- const label = blocks.localization.t("dashboard.title", "Dashboard");
171
-
172
- const tenantLanguages = await blocks.localization.languagesForCurrentTenant();
173
- const selectedKeys = await blocks.localization.keysByNames({
174
- keyNames: ["dashboard.title"]
175
- });
176
- ```
177
-
178
- ## API Surface
179
-
180
- - `blocks.auth`: AuthController login, social login, refresh, org switch, logout, signup, recovery, activation, auth config, user codes, client credentials, identity providers.
181
- - `blocks.auth.idp`: hosted IdP initiate, browser redirect, callback, UI config.
182
- - `blocks.auth.oidc`: refresh-token and client-credentials token endpoint helpers.
183
- - `blocks.iam`: current user, users, roles, permissions, resources, organizations, signup settings (`blocks.iam.signupSettings`).
184
- - `blocks.data`: schema reads, validation reads, GraphQL gateway execution, file/directory/object-tree storage helpers, and runtime collection CRUD.
185
- - `blocks.localization`: tenant language/module discovery, UILM dictionary loading, selected key lookup, simple `t()` lookup.
186
- - `blocks.mfa`: tenant MFA policy read/save, TOTP enrollment, OTP generate/resend/verify, method switch, disable, and backup codes.
187
- - `blocks.mail`: `send`/`sendToAny` transactional email through the tenant's configured mail provider.
188
- - `blocks.notifier`: `notify`, `getNotifications`, `getUnreadNotificationsBySubscriptionFilter`, `markNotificationAsRead`, `markAllNotificationAsRead`.
189
-
190
- Professional class names are exported for advanced typing and adapters: `BlocksAuthenticationClient`, `BlocksIAMClient`, `BlocksDataClient`, `BlocksLocalizationClient`, `BlocksMfaClient`, `BlocksMailClient`, and `BlocksNotifierClient`. `BlocksApiError` is exported for typed error handling - every non-2xx response from `http.request`/`http.external` throws it, exposing `status`, `statusText`, and the parsed `body`:
191
-
192
- ```ts
193
- try {
194
- await blocks.iam.me();
195
- } catch (error) {
196
- if (error instanceof BlocksApiError) {
197
- console.error(error.status, error.body);
198
- }
199
- }
200
- ```
201
-
202
- ## Boundaries
203
-
204
- This package must not contain:
205
-
206
- - CLI client secrets
207
- - impersonation APIs
208
- - project create/list/use
209
- - schema/rules deploy
210
- - release deploy
211
- - token/session/PKCE storage
212
- - Node filesystem or OS credential storage
213
- - framework UI components
214
- - Localization authoring/admin endpoints
215
- - Data schema/rules mutation endpoints
216
-
217
- ## Package Checks
218
-
219
- ```bash
220
- npm test
221
- npm pack --dry-run
222
- ```
1
+ # Blocks Client
2
+
3
+ Framework-neutral TypeScript SDK for SELISE Blocks frontend and app-runtime code.
4
+
5
+ [`@seliseblocks/client`](https://www.npmjs.com/package/@seliseblocks/client) gives consumer apps a small, typed wrapper around the Blocks APIs they normally call at runtime: Auth/IAM, Data, Localization, and shared HTTP configuration. Detailed `what / why / how` descriptions are kept on the SDK functions themselves so editors and generated typings show the guidance where developers use the API.
6
+
7
+ Admin/control-plane work belongs in `@seliseblocks/cli-os`: project setup, schema/rules deploy, release deploy, and AI/admin terminal workflows.
8
+
9
+ For AI agents and automation, see [AGENT_GUIDE.md](AGENT_GUIDE.md).
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @seliseblocks/client@latest
15
+ ```
16
+
17
+ Requires Node.js 20+ or a browser/runtime with `fetch`.
18
+
19
+ ## Create A Client
20
+
21
+ ```ts
22
+ import { createBlocksClient } from "@seliseblocks/client";
23
+
24
+ const blocks = createBlocksClient({
25
+ apiUrl: "https://api.seliseblocks.com",
26
+ xBlocksKey: "<blocks-key>",
27
+ accessToken: () => currentUserSession?.accessToken,
28
+ oidc: {
29
+ url: "https://iam.seliseblocks.com",
30
+ clientId: "<public-browser-client-id>",
31
+ redirectUri: configuredRedirectUri ?? `${window.location.origin}/login/callback`
32
+ }
33
+ });
34
+ ```
35
+
36
+ `xBlocksKey` is always sent as the `x-blocks-key` header. Do not send `ProjectKey` or `projectKey` in request query/body payloads.
37
+
38
+ The SDK does not store tokens. Your app owns login state, refresh scheduling, storage, and logout cleanup.
39
+
40
+ `blocks.config` reads back the resolved settings (`apiUrl`, `xBlocksKey`,
41
+ `appDomain`, `oidc`). It deliberately excludes your `accessToken` resolver and
42
+ `onUnauthorized` hook, so the client never doubles as a place to read a live
43
+ session out of; use `await blocks.auth.accessToken()` when you need the token.
44
+
45
+ `http.request()` only ever talks to the configured `apiUrl` — it attaches your
46
+ bearer token, `x-blocks-key`, and cookies, so an absolute URL on another origin
47
+ is refused rather than handed a live session. Use `http.external(url)` for
48
+ third-party URLs such as a pre-signed storage upload; it sends no Blocks
49
+ credentials.
50
+
51
+ Use a configured OIDC redirect URI when your app has one. The current-origin `/login/callback` URL is only a browser fallback.
52
+
53
+ ## Auth
54
+
55
+ Auth has two login flows.
56
+
57
+ OIDC/hosted IAM login uses `auth.idp`. The SDK relies on Blocks IAM `IdpController`, sends the configured public `clientId`, and does not manually build `oidc/authorize` URLs. Refresh OIDC sessions with `auth.oidc.refreshToken()`, which calls `/iam/v4/oidc/token` and sends `client_id`.
58
+
59
+ ```ts
60
+ await blocks.auth.idp.redirectToProvider();
61
+
62
+ const result = await blocks.auth.idp.callback(window.location.href);
63
+
64
+ const refreshed = await blocks.auth.oidc.refreshToken({
65
+ refreshToken: result.refresh_token,
66
+ clientId: "<public-browser-client-id>"
67
+ });
68
+ ```
69
+
70
+ Embedded/app-owned login UI uses AuthController methods directly on `auth`: `auth.login()`, `auth.socialInitiate(clientId, redirectUri)` (two positional strings, not an object), `auth.socialCallback(request)`, and `auth.refresh()`.
71
+
72
+ ```ts
73
+ const login = await blocks.auth.login({
74
+ username: "user@example.com",
75
+ password: "password"
76
+ });
77
+
78
+ const refreshed = await blocks.auth.refresh({
79
+ refreshToken: login.refresh_token
80
+ });
81
+ ```
82
+
83
+ Other auth APIs, such as user info, organization switch, logout, signup, recovery, activation, auth config, user codes, client credentials, and identity providers, can be used by either flow when the app has the required token/permission.
84
+
85
+ `auth.oidc.clientCredentials()` is for trusted non-browser runtimes only because it requires a client secret.
86
+
87
+ `auth.accessToken()` resolves the caller-owned bearer token configured on `createBlocksClient` (string or callback). `auth.isAuthenticated()` checks the current session against IAM through `GET /iam/v4/auth/me` and returns a boolean based on the raw response status - use it instead of `userInfo()` when you need a true/false signal, since IAM's hosted IdP flow may set the session as a cookie with no local `accessToken` to inspect.
88
+
89
+ ## MFA
90
+
91
+ `blocks.mfa` covers the signed-in user's own multi-factor setup — TOTP
92
+ enrollment, OTP challenges, switching the active method, and backup codes —
93
+ plus `mfa.saveConfig()` for tenant-wide MFA policy, which needs an admin
94
+ token.
95
+
96
+ ```ts
97
+ const config = await blocks.mfa.config();
98
+ await blocks.mfa.totp.setup();
99
+ await blocks.mfa.totp.verifySetup({ code: "123456" });
100
+ await blocks.mfa.setMethod({ mfaType: 1 });
101
+ const backupCodes = await blocks.mfa.backupCodes.generate();
102
+ ```
103
+
104
+ ## Mail And Notifications
105
+
106
+ ```ts
107
+ await blocks.mail.send({
108
+ to: ["user@example.com"],
109
+ purpose: "welcome",
110
+ language: "en",
111
+ subjectDataContext: { firstName: "Ada" }
112
+ });
113
+
114
+ await blocks.mail.sendToAny({
115
+ to: ["qa@example.com"],
116
+ purpose: "welcome",
117
+ language: "en",
118
+ isTestMail: true
119
+ });
120
+
121
+ await blocks.notifier.notify({
122
+ userIds: ["user-id"],
123
+ denormalizedPayload: JSON.stringify({ orderId: "123" }),
124
+ saveDenormalizedPayloadAsAnObject: true
125
+ });
126
+
127
+ const inbox = await blocks.notifier.getNotifications({ isUnreadOnly: true, page: 1, pageSize: 20 });
128
+ await blocks.notifier.markNotificationAsRead({ id: inbox.notifications[0].id });
129
+ await blocks.notifier.markAllNotificationAsRead();
130
+ ```
131
+
132
+ `mail.send`/`mail.sendToAny` call `/logic/v4/Mail/Send`/`SendToAny`. `notifier.*` calls `/logic/v4/Notifier/*`
133
+ for sending/reading notifications; tenant notification *channel configuration* (`/os/v4/Notification/*`)
134
+ is an admin concern handled by `@seliseblocks/cli-os`'s `notification *` commands, not this SDK.
135
+
136
+ ## Common Runtime Calls
137
+
138
+ ```ts
139
+ const me = await blocks.iam.me();
140
+ const orgs = await blocks.iam.organizations.my();
141
+ const features = await blocks.iam.resources.features();
142
+ ```
143
+
144
+ `iam.organizations.my()` returns the IAM envelope with `organizations`, not `data`.
145
+
146
+ ```ts
147
+ const schemas = await blocks.data.schemas.list();
148
+ const schemaInfo = await blocks.data.schemas.infoByName("Student");
149
+ const schemaRules = await blocks.data.validations.bySchemaId("schema-id");
150
+
151
+ const students = blocks.data.collection("Students");
152
+ const rows = await students.list({ pageNo: 1, pageSize: 20 });
153
+ await students.create({ firstName: "Test" });
154
+
155
+ const graph = await blocks.data.graphql({
156
+ query: "{ students { items { itemId firstName } } }"
157
+ });
158
+ ```
159
+
160
+ ```ts
161
+ const upload = await blocks.data.files.presignedUploadUrl({
162
+ name: "avatar.png",
163
+ configurationName: "default",
164
+ parentDirectoryId: "root",
165
+ accessModifier: "Private"
166
+ });
167
+
168
+ await blocks.data.files.uploadToUrl({
169
+ url: upload.uploadUrl,
170
+ body: file,
171
+ contentType: file.type
172
+ });
173
+
174
+ const items = await blocks.data.objects.list({
175
+ parentDirectoryId: "root",
176
+ limit: 20
177
+ });
178
+
179
+ const directory = await blocks.data.directories.create({
180
+ name: "Contracts",
181
+ parentDirectoryId: "root",
182
+ allowedFileExtensions: ["pdf", "docx"]
183
+ });
184
+ ```
185
+
186
+ ```ts
187
+ await blocks.localization.load("en-US", ["common", "dashboard"]);
188
+ const label = blocks.localization.t("dashboard.title", "Dashboard");
189
+
190
+ const tenantLanguages = await blocks.localization.languagesForCurrentTenant();
191
+ const selectedKeys = await blocks.localization.keysByNames({
192
+ keyNames: ["dashboard.title"]
193
+ });
194
+ ```
195
+
196
+ ## API Surface
197
+
198
+ See [`AGENT_GUIDE.md`](AGENT_GUIDE.md)'s Service Map for the full method-level
199
+ list under `blocks.auth`, `blocks.iam`, `blocks.data`, `blocks.localization`,
200
+ `blocks.mfa`, `blocks.mail`, and `blocks.notifier`.
201
+
202
+ Professional class names are exported for advanced typing and adapters: `BlocksAuthenticationClient`, `BlocksIAMClient`, `BlocksDataClient`, `BlocksLocalizationClient`, `BlocksMfaClient`, `BlocksMailClient`, and `BlocksNotifierClient`. `BlocksApiError` is exported for typed error handling - every non-2xx response from `http.request`/`http.external` throws it, exposing `status`, `statusText`, and the parsed `body`. That holds even when the body is not really JSON: a proxy or WAF answering with an HTML error page under a JSON content type surfaces as a `BlocksApiError` carrying the status and the raw text, not as a `SyntaxError`.
203
+
204
+ ```ts
205
+ try {
206
+ await blocks.iam.me();
207
+ } catch (error) {
208
+ if (error instanceof BlocksApiError) {
209
+ console.error(error.status, error.body);
210
+ }
211
+ }
212
+ ```
213
+
214
+ ## Boundaries
215
+
216
+ This package must not contain:
217
+
218
+ - CLI client secrets
219
+ - impersonation APIs
220
+ - project create/list/use
221
+ - schema/rules deploy
222
+ - release deploy
223
+ - token/session/PKCE storage
224
+ - Node filesystem or OS credential storage
225
+ - framework UI components
226
+ - Localization authoring/admin endpoints
227
+ - Data schema/rules mutation endpoints
228
+
229
+ ## Package Checks
230
+
231
+ ```bash
232
+ npm test
233
+ npm pack --dry-run
234
+ ```
@@ -1,10 +1,10 @@
1
- import type { RequiredConfig } from "../client.js";
1
+ import type { BlocksResolvedConfig } from "../client.js";
2
2
  import type { BlocksAuthJsonOptions, BlocksAuthLoginRequest, BlocksAuthPassThroughResponse, BlocksAuthResponse, BlocksClientCredentialsRequest, BlocksIdpCallbackRequest, BlocksIdpInitiateRequest, BlocksIdpInitiateResponse, BlocksLoginOption, BlocksLogoutRequest, BlocksOidcRefreshRequest, BlocksOidcUserInfo, BlocksRefreshRequest, BlocksSocialLoginRequest, BlocksSwitchOrganizationRequest } from "./types.js";
3
- export type { BlocksAuthLoginRequest, BlocksAuthPassThroughResponse, BlocksAuthResponse, BlocksClientCredentialsRequest, BlocksIdpCallbackRequest, BlocksIdpInitiateRequest, BlocksIdpInitiateResponse, BlocksLoginOption, BlocksLogoutRequest, BlocksOidcRefreshRequest, BlocksOidcUserInfo, BlocksRefreshRequest, BlocksSocialLoginRequest, BlocksSwitchOrganizationRequest } from "./types.js";
3
+ export type { BlocksAuthJsonOptions, BlocksAuthLoginRequest, BlocksAuthPassThroughResponse, BlocksAuthResponse, BlocksClientCredentialsRequest, BlocksIdpCallbackRequest, BlocksIdpInitiateRequest, BlocksIdpInitiateResponse, BlocksLoginOption, BlocksLogoutRequest, BlocksOidcRefreshRequest, BlocksOidcUserInfo, BlocksRefreshRequest, BlocksSocialLoginRequest, BlocksSwitchOrganizationRequest } from "./types.js";
4
4
  export declare class BlocksAuthenticationClient {
5
5
  private readonly clientConfig;
6
6
  private readonly fetchImpl;
7
- constructor(clientConfig: RequiredConfig, fetchImpl?: typeof fetch);
7
+ constructor(clientConfig: BlocksResolvedConfig, fetchImpl?: typeof fetch);
8
8
  /**
9
9
  * What: discovers tenant login options through `GET /iam/v4/auth/login-options`.
10
10
  * Why: login screens need to know which login methods the tenant supports before rendering controls.
package/dist/client.d.ts CHANGED
@@ -42,6 +42,13 @@ export type BlocksClientConfig = {
42
42
  * Optional fetch-compatible function for tests, SSR, or custom runtimes.
43
43
  */
44
44
  fetch?: typeof fetch;
45
+ /**
46
+ * Caller-owned hook invoked at most once per request when a protected call comes back 401.
47
+ * Should resolve a fresh token (deduping concurrent callers itself, e.g. via a shared
48
+ * in-flight refresh promise) or `undefined` if the session cannot be recovered -- the SDK
49
+ * retries the request once with the returned token, or leaves the 401 to throw if none.
50
+ */
51
+ onUnauthorized?: () => Promise<string | undefined> | string | undefined;
45
52
  /**
46
53
  * Optional hosted IdP/OIDC browser-flow configuration.
47
54
  */
@@ -51,9 +58,18 @@ export type BlocksClientConfig = {
51
58
  */
52
59
  xBlocksKey: string;
53
60
  };
61
+ /**
62
+ * The resolved configuration a client exposes on `blocks.config`: the settings
63
+ * an app may want to read back (which tenant, which API, which OIDC client),
64
+ * with the caller-owned `accessToken` resolver and `onUnauthorized` hook left
65
+ * out. Those two are callables that reach live credentials, and this package's
66
+ * boundary is that it never becomes a place to read a session from -- use
67
+ * `blocks.auth.accessToken()` when you need the token itself.
68
+ */
69
+ export type BlocksPublicConfig = Omit<BlocksResolvedConfig, "accessToken" | "onUnauthorized">;
54
70
  export type BlocksClient = {
55
71
  auth: BlocksAuthenticationClient;
56
- config: Readonly<RequiredConfig>;
72
+ config: Readonly<BlocksPublicConfig>;
57
73
  data: BlocksDataClient;
58
74
  http: BlocksHttpClient;
59
75
  iam: BlocksIAMClient;
@@ -62,16 +78,24 @@ export type BlocksClient = {
62
78
  mfa: BlocksMfaClient;
63
79
  notifier: BlocksNotifierClient;
64
80
  };
65
- export type RequiredConfig = {
81
+ /**
82
+ * `BlocksClientConfig` after defaults are applied -- the shape the internal
83
+ * service clients are constructed with. Consumers normally want
84
+ * `BlocksPublicConfig` (what `blocks.config` actually exposes) instead.
85
+ */
86
+ export type BlocksResolvedConfig = {
66
87
  accessToken?: string | (() => Promise<string | undefined> | string | undefined);
67
88
  apiUrl: string;
68
89
  appDomain?: string;
90
+ onUnauthorized?: () => Promise<string | undefined> | string | undefined;
69
91
  oidc?: BlocksOidcConfig & {
70
92
  redirectUri: string;
71
93
  scope: string;
72
94
  };
73
95
  xBlocksKey: string;
74
96
  };
97
+ /** @deprecated Renamed to `BlocksResolvedConfig` for consistency with the other exported names. */
98
+ export type RequiredConfig = BlocksResolvedConfig;
75
99
  /**
76
100
  * What: creates a framework-neutral Blocks SDK instance for one tenant/app runtime.
77
101
  * Why: frontend code needs a single configured entry point for IAM, Auth, Data, and Localization APIs.
package/dist/client.js CHANGED
@@ -15,9 +15,10 @@ export function createBlocksClient(config) {
15
15
  const normalized = normalizeConfig(config);
16
16
  const auth = new BlocksAuthenticationClient(normalized, config.fetch);
17
17
  const http = new BlocksHttpClient(normalized, auth, config.fetch);
18
+ const { accessToken: _accessToken, onUnauthorized: _onUnauthorized, ...publicConfig } = normalized;
18
19
  return {
19
20
  auth,
20
- config: normalized,
21
+ config: publicConfig,
21
22
  data: new BlocksDataClient(http),
22
23
  http,
23
24
  iam: new BlocksIAMClient(http),
@@ -36,6 +37,7 @@ function normalizeConfig(config) {
36
37
  accessToken: config.accessToken,
37
38
  apiUrl: trimTrailingSlash(config.apiUrl),
38
39
  appDomain: config.appDomain,
40
+ onUnauthorized: config.onUnauthorized,
39
41
  oidc: config.oidc ? {
40
42
  ...config.oidc,
41
43
  redirectUri: config.oidc.redirectUri ?? browserRedirectUri(),
@@ -289,13 +289,13 @@ export class BlocksDataClient {
289
289
  */
290
290
  create: (payload) => this.graphql({
291
291
  operationName: createField,
292
- query: `mutation ${createField}($input: ${schemaName}InsertInput!) {
293
- ${createField}(input: $input) {
294
- acknowledged
295
- itemId
296
- message
297
- totalImpactedData
298
- }
292
+ query: `mutation ${createField}($input: ${schemaName}InsertInput!) {
293
+ ${createField}(input: $input) {
294
+ acknowledged
295
+ itemId
296
+ message
297
+ totalImpactedData
298
+ }
299
299
  }`,
300
300
  variables: { input: payload }
301
301
  }),
@@ -306,13 +306,13 @@ export class BlocksDataClient {
306
306
  */
307
307
  delete: (itemId, deleteOptions = {}) => this.graphql({
308
308
  operationName: deleteField,
309
- query: `mutation ${deleteField}($filter: String, $input: ${schemaName}DeleteInput!) {
310
- ${deleteField}(filter: $filter, input: $input) {
311
- acknowledged
312
- itemId
313
- message
314
- totalImpactedData
315
- }
309
+ query: `mutation ${deleteField}($filter: String, $input: ${schemaName}DeleteInput!) {
310
+ ${deleteField}(filter: $filter, input: $input) {
311
+ acknowledged
312
+ itemId
313
+ message
314
+ totalImpactedData
315
+ }
316
316
  }`,
317
317
  variables: {
318
318
  filter: itemIdFilter(itemId),
@@ -354,13 +354,13 @@ export class BlocksDataClient {
354
354
  */
355
355
  update: (itemId, payload) => this.graphql({
356
356
  operationName: updateField,
357
- query: `mutation ${updateField}($filter: String, $input: ${schemaName}UpdateInput!) {
358
- ${updateField}(filter: $filter, input: $input) {
359
- acknowledged
360
- itemId
361
- message
362
- totalImpactedData
363
- }
357
+ query: `mutation ${updateField}($filter: String, $input: ${schemaName}UpdateInput!) {
358
+ ${updateField}(filter: $filter, input: $input) {
359
+ acknowledged
360
+ itemId
361
+ message
362
+ totalImpactedData
363
+ }
364
364
  }`,
365
365
  variables: {
366
366
  filter: itemIdFilter(itemId),
@@ -472,18 +472,18 @@ function dynamicQueryInput(options) {
472
472
  };
473
473
  }
474
474
  function collectionListQuery(fieldName, selection) {
475
- return `query ${fieldName}($input: DynamicQueryInput) {
476
- ${fieldName}(input: $input) {
477
- items {
478
- ${indent(selection, 6)}
479
- }
480
- totalCount
481
- pageNo
482
- pageSize
483
- totalPages
484
- hasNextPage
485
- hasPreviousPage
486
- }
475
+ return `query ${fieldName}($input: DynamicQueryInput) {
476
+ ${fieldName}(input: $input) {
477
+ items {
478
+ ${indent(selection, 6)}
479
+ }
480
+ totalCount
481
+ pageNo
482
+ pageSize
483
+ totalPages
484
+ hasNextPage
485
+ hasPreviousPage
486
+ }
487
487
  }`;
488
488
  }
489
489
  function selectionFor(fields) {