bkper 4.26.0 → 4.26.1
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-outbound.d.ts","sourceRoot":"","sources":["../../src/dev/local-outbound.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"local-outbound.d.ts","sourceRoot":"","sources":["../../src/dev/local-outbound.ts"],"names":[],"mappings":"AAWA,MAAM,MAAM,oBAAoB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAE3E,MAAM,WAAW,oBAAoB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACnD,YAAY,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC1D;AAMD,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,oBAAoB,GAAG,oBAAoB,CA8B9F"}
|
|
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
10
10
|
import { AUTHENTICATION_REQUIRED_MESSAGE } from '../auth/auth-errors.js';
|
|
11
11
|
import { getStoredOAuthToken } from '../auth/local-auth-service.js';
|
|
12
12
|
const PUBLIC_BKPER_API_HOST = 'api.bkper.app';
|
|
13
|
+
const BKPER_AI_HOSTS = new Set(['ai.bkper.app', 'ai-dev.bkper.app']);
|
|
13
14
|
const PLATFORM_SESSION_COOKIE_NAMES = new Set([
|
|
14
15
|
'bkper_session',
|
|
15
16
|
'bkper_session_dev',
|
|
@@ -20,7 +21,8 @@ export function createLocalOutboundService(options) {
|
|
|
20
21
|
const getAccessToken = (_a = options.getAccessToken) !== null && _a !== void 0 ? _a : getStoredOAuthToken;
|
|
21
22
|
const forwardFetch = (_b = options.forwardFetch) !== null && _b !== void 0 ? _b : ((request) => fetch(request));
|
|
22
23
|
return (request) => __awaiter(this, void 0, void 0, function* () {
|
|
23
|
-
|
|
24
|
+
const service = getAuthorizedBkperService(request);
|
|
25
|
+
if (!service) {
|
|
24
26
|
return forwardFetch(createForwardRequest(request, new Headers(request.headers), request.redirect));
|
|
25
27
|
}
|
|
26
28
|
const accessToken = normalizeBearerToken(yield getAccessToken());
|
|
@@ -33,6 +35,9 @@ export function createLocalOutboundService(options) {
|
|
|
33
35
|
const headers = new Headers(request.headers);
|
|
34
36
|
headers.set('Authorization', `Bearer ${accessToken}`);
|
|
35
37
|
headers.set('bkper-agent-id', options.appId);
|
|
38
|
+
if (service === 'ai') {
|
|
39
|
+
headers.set('bkper-ai-source', options.appId);
|
|
40
|
+
}
|
|
36
41
|
stripPlatformCookieHeaders(headers);
|
|
37
42
|
return forwardFetch(createForwardRequest(request, headers, 'manual'));
|
|
38
43
|
});
|
|
@@ -51,9 +56,18 @@ function createForwardRequest(request, headers, redirect) {
|
|
|
51
56
|
}
|
|
52
57
|
return new Request(request.url, init);
|
|
53
58
|
}
|
|
54
|
-
function
|
|
59
|
+
function getAuthorizedBkperService(request) {
|
|
55
60
|
const url = new URL(request.url);
|
|
56
|
-
|
|
61
|
+
if (url.protocol !== 'https:') {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
if (url.host === PUBLIC_BKPER_API_HOST) {
|
|
65
|
+
return 'api';
|
|
66
|
+
}
|
|
67
|
+
if (BKPER_AI_HOSTS.has(url.host)) {
|
|
68
|
+
return 'ai';
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
57
71
|
}
|
|
58
72
|
function normalizeBearerToken(token) {
|
|
59
73
|
const trimmed = token === null || token === void 0 ? void 0 : token.trim();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-outbound.js","sourceRoot":"","sources":["../../src/dev/local-outbound.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,+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G,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SACxB,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;SAC/B,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;SAC3C,IAAI,CAAC,IAAI,CAAC,CAAC;IAEhB,IAAI,QAAQ,EAAE,CAAC;QACX,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;SAAM,CAAC;QACJ,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC7B,CAAC;AACL,CAAC;AAED,SAAS,oBAAoB,CAAC,UAAkB;;IAC5C,MAAM,UAAU,GAAG,MAAA,UAAU,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,0CAAE,IAAI,GAAG,WAAW,EAAE,CAAC;IACrE,OAAO,6BAA6B,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AACzD,CAAC"}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
# Add Bkper AI to an App
|
|
2
|
+
|
|
3
|
+
Bkper AI is the preferred inference provider for Bkper Platform apps. It uses the authenticated user's included AI allowance, attributes usage to the app, and does not require the app to store provider credentials.
|
|
4
|
+
|
|
5
|
+
Use another provider only when Bkper AI lacks a required capability, model, compliance boundary, or customer-mandated provider. External providers require their own authentication, secrets, billing, and privacy review.
|
|
6
|
+
|
|
7
|
+
This guide covers the preferred current pattern: a non-streaming response with strict structured output. Streaming, tool calls, file inputs, and agent runtimes require additional design.
|
|
8
|
+
|
|
9
|
+
## Request flow
|
|
10
|
+
|
|
11
|
+
Keep model calls behind the app's typed `/api/*` contract:
|
|
12
|
+
|
|
13
|
+
1. The web client calls an app `/api/*` route with a Bkper bearer token. The template's `auth.authenticatedFetch()` handles this.
|
|
14
|
+
2. Bkper validates the token, mounts the user and app identity as outbound context, and removes the token before invoking the app Worker.
|
|
15
|
+
3. The Worker calls `https://ai.bkper.app/v1/*` without reading, storing, or forwarding the token.
|
|
16
|
+
4. Platform outbound injects Bkper authorization and overwrites `bkper-agent-id` and `bkper-ai-source` with the authenticated app identity.
|
|
17
|
+
|
|
18
|
+
Event handlers use the same Worker-to-Bkper-AI step. Their outbound context comes from the authenticated Bkper event. A normal page request does not establish user outbound context, so start interactive inference from an authenticated `/api/*` route rather than a page handler.
|
|
19
|
+
|
|
20
|
+
## Call the app API from the client
|
|
21
|
+
|
|
22
|
+
Use the authenticated fetch provider already configured by the app template:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
interface AnalyzeRequest {
|
|
26
|
+
first: {
|
|
27
|
+
date: string;
|
|
28
|
+
amount: string;
|
|
29
|
+
description: string;
|
|
30
|
+
fromAccount: string | null;
|
|
31
|
+
toAccount: string | null;
|
|
32
|
+
};
|
|
33
|
+
second: {
|
|
34
|
+
date: string;
|
|
35
|
+
amount: string;
|
|
36
|
+
description: string;
|
|
37
|
+
fromAccount: string | null;
|
|
38
|
+
toAccount: string | null;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function analyzePair(auth: AuthProvider, request: AnalyzeRequest): Promise {
|
|
43
|
+
return auth.authenticatedFetch('/api/v1/analyze', {
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers: { 'content-type': 'application/json' },
|
|
46
|
+
body: JSON.stringify(request),
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
In a full app, define this operation in the server's Zod/OpenAPI schemas and call it through the generated typed client. The important boundary is that the client authenticates the app API request; the Worker never handles that bearer token directly.
|
|
52
|
+
|
|
53
|
+
## Discover the current default model
|
|
54
|
+
|
|
55
|
+
The live model catalog is authoritative. It publishes the current default, model IDs, modalities, structured-output support, reasoning levels, context and output limits, and effective usage rates.
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const AI_BASE_URL = 'https://ai.bkper.app/v1';
|
|
59
|
+
type Fetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise;
|
|
60
|
+
|
|
61
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
62
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function getStructuredOutputModel(fetcher: Fetcher = fetch): Promise<string> {
|
|
66
|
+
const response = await fetcher(`${AI_BASE_URL}/models`);
|
|
67
|
+
if (!response.ok) {
|
|
68
|
+
throw new Error(`Bkper AI model discovery failed (${response.status}).`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const catalog: unknown = await response.json();
|
|
72
|
+
if (
|
|
73
|
+
!isRecord(catalog) ||
|
|
74
|
+
typeof catalog.default_model !== 'string' ||
|
|
75
|
+
!Array.isArray(catalog.data)
|
|
76
|
+
) {
|
|
77
|
+
throw new Error('Bkper AI returned an invalid model catalog.');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const defaultModel = catalog.default_model;
|
|
81
|
+
const model = catalog.data.find(item => isRecord(item) && item.id === defaultModel);
|
|
82
|
+
if (
|
|
83
|
+
!isRecord(model) ||
|
|
84
|
+
!isRecord(model.structured_output) ||
|
|
85
|
+
model.structured_output.json_schema !== true ||
|
|
86
|
+
model.structured_output.strict !== true
|
|
87
|
+
) {
|
|
88
|
+
throw new Error('The default Bkper AI model does not support strict structured output.');
|
|
89
|
+
}
|
|
90
|
+
return defaultModel;
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
This example uses `default_model` after validating the capability required by the request. If an app requires another modality, file type, reasoning level, or limit, intentionally select and validate another model from the catalog's `data` array. Apps may cache the catalog briefly rather than fetching it for every inference request.
|
|
95
|
+
|
|
96
|
+
## Request strict structured output
|
|
97
|
+
|
|
98
|
+
Keep inference in a server service and make `fetch` injectable for unit tests. This example sends only the transaction facts needed for duplicate evaluation. It omits transaction IDs, Account IDs, unrelated properties, and other Book data.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const EvaluationJsonSchema = {
|
|
102
|
+
type: 'object',
|
|
103
|
+
properties: {
|
|
104
|
+
duplicate: { type: 'boolean' },
|
|
105
|
+
strength: { type: 'string', enum: ['Strong', 'Possible'] },
|
|
106
|
+
explanation: { type: 'string', maxLength: 180 },
|
|
107
|
+
},
|
|
108
|
+
required: ['duplicate', 'strength', 'explanation'],
|
|
109
|
+
additionalProperties: false,
|
|
110
|
+
} as const;
|
|
111
|
+
|
|
112
|
+
export interface DuplicateEvaluation {
|
|
113
|
+
duplicate: boolean;
|
|
114
|
+
strength: 'Strong' | 'Possible';
|
|
115
|
+
explanation: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export class BkperAiError extends Error {
|
|
119
|
+
constructor(
|
|
120
|
+
readonly status: number,
|
|
121
|
+
readonly code: string,
|
|
122
|
+
message: string
|
|
123
|
+
) {
|
|
124
|
+
super(message);
|
|
125
|
+
this.name = 'BkperAiError';
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function evaluateDuplicate(
|
|
130
|
+
candidate: AnalyzeRequest,
|
|
131
|
+
fetcher: Fetcher = fetch
|
|
132
|
+
): Promise {
|
|
133
|
+
const model = await getStructuredOutputModel(fetcher);
|
|
134
|
+
const response = await fetcher(`${AI_BASE_URL}/responses`, {
|
|
135
|
+
method: 'POST',
|
|
136
|
+
headers: { 'content-type': 'application/json' },
|
|
137
|
+
body: JSON.stringify({
|
|
138
|
+
model,
|
|
139
|
+
instructions:
|
|
140
|
+
'Decide whether both records represent the same movement. ' +
|
|
141
|
+
'Return Strong only when the evidence is compelling.',
|
|
142
|
+
input: [
|
|
143
|
+
{
|
|
144
|
+
role: 'user',
|
|
145
|
+
content: [
|
|
146
|
+
{
|
|
147
|
+
type: 'input_text',
|
|
148
|
+
text: JSON.stringify(candidate),
|
|
149
|
+
},
|
|
150
|
+
],
|
|
151
|
+
},
|
|
152
|
+
],
|
|
153
|
+
text: {
|
|
154
|
+
format: {
|
|
155
|
+
type: 'json_schema',
|
|
156
|
+
name: 'duplicate_evaluation',
|
|
157
|
+
schema: EvaluationJsonSchema,
|
|
158
|
+
strict: true,
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
stream: false,
|
|
162
|
+
store: false,
|
|
163
|
+
}),
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
const payload: unknown = await response.json();
|
|
167
|
+
if (!response.ok) {
|
|
168
|
+
const error = readAiError(payload);
|
|
169
|
+
throw new BkperAiError(response.status, error.code, error.message);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const value: unknown = JSON.parse(getOutputText(payload));
|
|
173
|
+
if (!isDuplicateEvaluation(value)) {
|
|
174
|
+
throw new Error('Bkper AI output did not match the required schema.');
|
|
175
|
+
}
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Do not add an `Authorization`, `bkper-agent-id`, or `bkper-ai-source` header to the Worker's Bkper AI request. Platform outbound derives those values from the authenticated app request or event and overwrites them before dispatch.
|
|
181
|
+
|
|
182
|
+
## Validate the response and preserve errors
|
|
183
|
+
|
|
184
|
+
Strict structured output constrains generation, but the app must still parse and validate the returned value before using it.
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
function getOutputText(payload: unknown): string {
|
|
188
|
+
if (!isRecord(payload) || payload.status !== 'completed' || !Array.isArray(payload.output)) {
|
|
189
|
+
throw new Error('Bkper AI did not return a complete response.');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const texts: string[] = [];
|
|
193
|
+
for (const item of payload.output) {
|
|
194
|
+
if (!isRecord(item) || item.type !== 'message' || !Array.isArray(item.content)) continue;
|
|
195
|
+
for (const part of item.content) {
|
|
196
|
+
if (isRecord(part) && part.type === 'output_text' && typeof part.text === 'string') {
|
|
197
|
+
texts.push(part.text);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (texts.length === 0) throw new Error('Bkper AI returned no output text.');
|
|
202
|
+
return texts.join('');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function isDuplicateEvaluation(value: unknown): value is DuplicateEvaluation {
|
|
206
|
+
return (
|
|
207
|
+
isRecord(value) &&
|
|
208
|
+
typeof value.duplicate === 'boolean' &&
|
|
209
|
+
(value.strength === 'Strong' || value.strength === 'Possible') &&
|
|
210
|
+
typeof value.explanation === 'string' &&
|
|
211
|
+
value.explanation.length <= 180
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function readAiError(payload: unknown): { code: string; message: string } {
|
|
216
|
+
if (
|
|
217
|
+
isRecord(payload) &&
|
|
218
|
+
isRecord(payload.error) &&
|
|
219
|
+
typeof payload.error.code === 'string' &&
|
|
220
|
+
typeof payload.error.message === 'string'
|
|
221
|
+
) {
|
|
222
|
+
return { code: payload.error.code, message: payload.error.message };
|
|
223
|
+
}
|
|
224
|
+
return { code: 'bkper_ai_error', message: 'Bkper AI request failed.' };
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Preserve the upstream HTTP status, error code, and message when mapping a `BkperAiError` into the app's typed error envelope. Bkper AI centralizes actionable messages such as allowance guidance and pricing links. Bot event responses may reuse that message directly when the surface supports it. Interactive apps can use the status and code to provide a tailored experience without duplicating the upstream policy or CTA.
|
|
229
|
+
|
|
230
|
+
## Test the boundary
|
|
231
|
+
|
|
232
|
+
Use a mocked `fetch` to protect the integration contract without making live model calls:
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
expect(capturedRequest.headers.get('authorization')).toBeNull();
|
|
236
|
+
expect(requestBody.store).toBe(false);
|
|
237
|
+
expect(requestBody.stream).toBe(false);
|
|
238
|
+
expect(requestBody.text).toMatchObject({
|
|
239
|
+
format: { type: 'json_schema', strict: true },
|
|
240
|
+
});
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Also test that the service:
|
|
244
|
+
|
|
245
|
+
- validates that the catalog's `default_model` supports strict structured output;
|
|
246
|
+
- rejects malformed or schema-incompatible output;
|
|
247
|
+
- preserves Bkper AI error status, code, and message;
|
|
248
|
+
- does not send internal identifiers or unrelated Book data.
|
|
249
|
+
|
|
250
|
+
## Implementation checklist
|
|
251
|
+
|
|
252
|
+
Before considering the integration complete:
|
|
253
|
+
|
|
254
|
+
- [ ] The client calls a typed `/api/*` route through authenticated fetch.
|
|
255
|
+
- [ ] Worker code never reads, stores, or forwards the Bkper bearer token.
|
|
256
|
+
- [ ] The app discovers models from `GET /v1/models` and intentionally chooses a returned ID.
|
|
257
|
+
- [ ] Inference runs in a server service with an injectable `fetch`.
|
|
258
|
+
- [ ] The request uses strict structured output, `stream: false`, and `store: false`.
|
|
259
|
+
- [ ] Only data required for the task is sent to inference.
|
|
260
|
+
- [ ] Returned JSON is parsed and independently validated.
|
|
261
|
+
- [ ] Error status, code, and message remain available to the caller.
|
|
262
|
+
- [ ] Unit tests cover the request, response, validation, and error boundaries.
|
|
263
|
+
- [ ] The app's normal `npm run check` or `bun run check` succeeds.
|
|
264
|
+
|
|
265
|
+
## Next steps
|
|
266
|
+
|
|
267
|
+
- [Read the client-agnostic Bkper AI Provider guide](https://bkper.com/docs/ai/bkper-ai-provider.md) for privacy boundaries, the complete supported profile, and advanced features.
|
|
268
|
+
- [Inspect the live model catalog](https://ai.bkper.app/v1/models).
|
|
269
|
+
- [Browse the generated AI API reference](https://bkper.com/docs/api/ai.md) when exact request or response schema details are needed.
|
|
270
|
+
- [Review the Merge Duplicates implementation](https://github.com/bkper/bkper-apps/tree/main/merge-duplicates) for a platform-app example with deterministic candidate filtering, strict structured output, and human-confirmed merges.
|
|
@@ -16,6 +16,12 @@ The same Worker can expose app-defined `/api/*` routes. Treat those routes as th
|
|
|
16
16
|
- Scripts, external clients, and agents can call them too.
|
|
17
17
|
- The default template documents them with an app OpenAPI spec at `/openapi.json`.
|
|
18
18
|
|
|
19
|
+
### AI inference
|
|
20
|
+
|
|
21
|
+
When an app needs model inference, use Bkper AI by default. An authenticated app API route or event establishes the user and app identity, then platform outbound supplies authorization and usage attribution for the Worker's Bkper AI requests. The app does not need provider credentials.
|
|
22
|
+
|
|
23
|
+
See [Add Bkper AI to an App](https://bkper.com/docs/build/apps/ai.md) for live model discovery, strict structured output, validation, and the client-to-Worker authentication flow.
|
|
24
|
+
|
|
19
25
|
### Authentication
|
|
20
26
|
|
|
21
27
|
OAuth is pre-configured. No client IDs, no redirect URIs, no consent screens to build.
|
package/lib/docs/index.md
CHANGED
|
@@ -8,6 +8,7 @@ For Bkper data, accounting, reporting, tax, or financial-flow tasks, read `core/
|
|
|
8
8
|
- `cli/data-management.md` — CLI reference for managing financial data and files: books, accounts, groups, files, transactions, per-account balance queries, query operators (on:, after:, before:, account:, group:), output formats (table/json/csv), human-review Bkper UI links, batch operations via stdin/piping, collections.
|
|
9
9
|
- `cli/app-management.md` — CLI reference for building and deploying Bkper apps: init/git clone/credential helpers, dev/build/deploy workflow, app install/uninstall, secrets management, app logs, bkper.yaml configuration reference (identity, branding, events, menu integration, deployment).
|
|
10
10
|
- `apps/overview.md` — Platform evaluation and capability overview: use when comparing managed Bkper hosting with self-managed infrastructure or clarifying platform responsibilities; use the task-specific app references for implementation.
|
|
11
|
+
- `apps/ai.md` — Bkper AI integration for Platform apps: authenticated `/api/*` request flow, outbound authorization and app attribution, live model discovery, strict structured output, response validation, error preservation, data minimization, and unit-test boundaries.
|
|
11
12
|
- `apps/first-app.md` — First-app walkthrough: scaffold, install, run locally, trigger an event, customize the listing, establish shared source, check, and deploy.
|
|
12
13
|
- `apps/architecture.md` — App and template architecture: npm workspace structure, Lit/Vite client, Hono Worker, typed `/api/*` contracts, authentication, `/events`, static assets, and supported app shapes.
|
|
13
14
|
- `apps/configuration.md` — Complete `bkper.yaml` reference: identity, branding, ownership, access, context menus, event subscriptions, property schemas, and single-Worker deployment settings.
|