@webiny/sdk-frontend 0.0.0-unstable.9f53ea597d → 0.0.0-unstable.a85ef555b2
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/ComponentsSdk.d.ts +39 -0
- package/ComponentsSdk.js +154 -0
- package/ComponentsSdk.js.map +1 -0
- package/ComponentsSdk.test.d.ts +1 -0
- package/ComponentsSdk.test.js +313 -0
- package/ComponentsSdk.test.js.map +1 -0
- package/FrontendSdk.d.ts +2 -0
- package/FrontendSdk.js +13 -1
- package/FrontendSdk.js.map +1 -1
- package/WbSdk.js +6 -2
- package/WbSdk.js.map +1 -1
- package/createCmsContentEntryLoader.d.ts +7 -0
- package/createCmsContentEntryLoader.js +9 -0
- package/createCmsContentEntryLoader.js.map +1 -0
- package/index.d.ts +7 -2
- package/index.js +5 -2
- package/package.json +7 -6
- package/resolveContentEntries.client.test.d.ts +1 -0
- package/resolveContentEntries.client.test.js +118 -0
- package/resolveContentEntries.client.test.js.map +1 -0
- package/resolveContentEntries.d.ts +20 -0
- package/resolveContentEntries.js +45 -0
- package/resolveContentEntries.js.map +1 -0
- package/resolveContentEntries.test.d.ts +1 -0
- package/resolveContentEntries.test.js +328 -0
- package/resolveContentEntries.test.js.map +1 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { WebinyConfig } from "@webiny/sdk";
|
|
2
|
+
import { Result, HttpError, ApiError, NetworkError } from "@webiny/sdk";
|
|
3
|
+
export interface RemoteComponentEntry {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
label: string;
|
|
7
|
+
bundledJs: string;
|
|
8
|
+
bundledJsSha256: string;
|
|
9
|
+
bundledCss: string;
|
|
10
|
+
bundledCssSha256: string;
|
|
11
|
+
sdkVersion: string;
|
|
12
|
+
status: string;
|
|
13
|
+
}
|
|
14
|
+
export interface LoadComponentsOptions {
|
|
15
|
+
fetchOptions?: RequestInit;
|
|
16
|
+
}
|
|
17
|
+
export interface HydrateComponentDependencies {
|
|
18
|
+
sdk: unknown;
|
|
19
|
+
React: unknown;
|
|
20
|
+
}
|
|
21
|
+
export interface HydrateComponentOptions {
|
|
22
|
+
tenantId?: string;
|
|
23
|
+
locale?: string;
|
|
24
|
+
mode?: "server" | "browser";
|
|
25
|
+
}
|
|
26
|
+
export interface HydratedComponent {
|
|
27
|
+
component: any;
|
|
28
|
+
manifest: any;
|
|
29
|
+
css: string;
|
|
30
|
+
scopeClassName: string;
|
|
31
|
+
}
|
|
32
|
+
export declare class ComponentsSdk {
|
|
33
|
+
private config;
|
|
34
|
+
private fetchFn;
|
|
35
|
+
constructor(config: WebinyConfig);
|
|
36
|
+
loadComponents(options?: LoadComponentsOptions): Promise<Result<RemoteComponentEntry[], HttpError | ApiError | NetworkError>>;
|
|
37
|
+
hydrateComponent(entry: RemoteComponentEntry, dependencies: HydrateComponentDependencies, options?: HydrateComponentOptions): HydratedComponent | null;
|
|
38
|
+
scopeCss(rawCss: string, componentName: string): string;
|
|
39
|
+
}
|
package/ComponentsSdk.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { ApiError, HttpError, NetworkError, Result } from "@webiny/sdk";
|
|
2
|
+
import * as __rspack_external_css_tree_6b21abdd from "css-tree";
|
|
3
|
+
const LIST_REMOTE_COMPONENTS = `
|
|
4
|
+
query ListRemoteComponents {
|
|
5
|
+
remoteComponents {
|
|
6
|
+
listRemoteComponents {
|
|
7
|
+
data {
|
|
8
|
+
id
|
|
9
|
+
name
|
|
10
|
+
label
|
|
11
|
+
bundledJs
|
|
12
|
+
bundledJsSha256
|
|
13
|
+
bundledCss
|
|
14
|
+
bundledCssSha256
|
|
15
|
+
sdkVersion
|
|
16
|
+
status
|
|
17
|
+
}
|
|
18
|
+
error {
|
|
19
|
+
code
|
|
20
|
+
message
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
`;
|
|
26
|
+
class ComponentsSdk {
|
|
27
|
+
constructor(config){
|
|
28
|
+
this.config = config;
|
|
29
|
+
this.fetchFn = config.fetch ?? fetch;
|
|
30
|
+
}
|
|
31
|
+
async loadComponents(options) {
|
|
32
|
+
const url = `${this.config.endpoint}/graphql`;
|
|
33
|
+
const headers = {
|
|
34
|
+
"Content-Type": "application/json",
|
|
35
|
+
"x-tenant": this.config.tenant ?? "root",
|
|
36
|
+
...this.config.headers
|
|
37
|
+
};
|
|
38
|
+
if (this.config.token && !headers.Authorization) {
|
|
39
|
+
const token = "function" == typeof this.config.token ? await this.config.token() : this.config.token;
|
|
40
|
+
headers.Authorization = `Bearer ${token}`;
|
|
41
|
+
}
|
|
42
|
+
const callerHeaders = options?.fetchOptions?.headers;
|
|
43
|
+
const fetchFn = this.fetchFn;
|
|
44
|
+
let response;
|
|
45
|
+
try {
|
|
46
|
+
const requestHeaders = callerHeaders ? mergeHeaders(callerHeaders, headers) : headers;
|
|
47
|
+
response = await fetchFn(url, {
|
|
48
|
+
...options?.fetchOptions,
|
|
49
|
+
method: "POST",
|
|
50
|
+
headers: requestHeaders,
|
|
51
|
+
body: JSON.stringify({
|
|
52
|
+
query: LIST_REMOTE_COMPONENTS
|
|
53
|
+
})
|
|
54
|
+
});
|
|
55
|
+
} catch (error) {
|
|
56
|
+
return Result.fail(new NetworkError(error instanceof Error ? error.message : "Network request failed"));
|
|
57
|
+
}
|
|
58
|
+
if (!response.ok) return Result.fail(new HttpError(response.status, `HTTP error! status: ${response.status}`));
|
|
59
|
+
let json;
|
|
60
|
+
try {
|
|
61
|
+
json = await response.json();
|
|
62
|
+
} catch {
|
|
63
|
+
return Result.fail(new NetworkError("Failed to parse response JSON"));
|
|
64
|
+
}
|
|
65
|
+
if (json.errors) {
|
|
66
|
+
const error = json.errors[0];
|
|
67
|
+
return Result.fail(new ApiError(error?.message || "GraphQL error"));
|
|
68
|
+
}
|
|
69
|
+
const envelope = json.data?.remoteComponents?.listRemoteComponents;
|
|
70
|
+
if (!envelope) return Result.fail(new ApiError("Unexpected response — is the remote-components API extension deployed?"));
|
|
71
|
+
if (envelope.error) return Result.fail(new ApiError(envelope.error.message, envelope.error.code));
|
|
72
|
+
return Result.ok(envelope.data ?? []);
|
|
73
|
+
}
|
|
74
|
+
hydrateComponent(entry, dependencies, options) {
|
|
75
|
+
const runtimeSdk = {
|
|
76
|
+
version: "1",
|
|
77
|
+
dependencies: {
|
|
78
|
+
sdk: dependencies.sdk,
|
|
79
|
+
React: dependencies.React
|
|
80
|
+
},
|
|
81
|
+
environment: {
|
|
82
|
+
tenantId: options?.tenantId ?? this.config.tenant ?? "root",
|
|
83
|
+
locale: options?.locale ?? "en-US",
|
|
84
|
+
mode: options?.mode ?? "browser"
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
try {
|
|
88
|
+
const fn = new Function(`
|
|
89
|
+
var __remoteComponent__;
|
|
90
|
+
${entry.bundledJs}
|
|
91
|
+
return __remoteComponent__;
|
|
92
|
+
`);
|
|
93
|
+
const mod = fn();
|
|
94
|
+
const component = mod.createComponent(runtimeSdk);
|
|
95
|
+
if (!component) return null;
|
|
96
|
+
const scopeClass = toScopeClassName(entry.name);
|
|
97
|
+
const R = dependencies.React;
|
|
98
|
+
const OriginalComponent = component.component;
|
|
99
|
+
const ScopedComponent = (props)=>R.createElement("div", {
|
|
100
|
+
className: scopeClass
|
|
101
|
+
}, R.createElement(OriginalComponent, props));
|
|
102
|
+
ScopedComponent.displayName = `RemoteScope(${scopeClass})`;
|
|
103
|
+
return {
|
|
104
|
+
component: ScopedComponent,
|
|
105
|
+
manifest: component.manifest,
|
|
106
|
+
css: entry.bundledCss ?? "",
|
|
107
|
+
scopeClassName: scopeClass
|
|
108
|
+
};
|
|
109
|
+
} catch (error) {
|
|
110
|
+
console.error(`[ComponentsSdk] Failed to hydrate component "${entry.name}":`, error);
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
scopeCss(rawCss, componentName) {
|
|
115
|
+
return scopeCss(rawCss, toScopeClassName(componentName));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function mergeHeaders(callerHeaders, headers) {
|
|
119
|
+
const merged = new Headers(callerHeaders);
|
|
120
|
+
for (const [name, value] of Object.entries(headers))merged.set(name, value);
|
|
121
|
+
return merged;
|
|
122
|
+
}
|
|
123
|
+
function toScopeClassName(name) {
|
|
124
|
+
return `rc-${name.replace(/\//g, "-").toLowerCase()}`;
|
|
125
|
+
}
|
|
126
|
+
function scopeCss(rawCss, scopeName) {
|
|
127
|
+
if (!rawCss) return "";
|
|
128
|
+
try {
|
|
129
|
+
const ast = __rspack_external_css_tree_6b21abdd.parse(rawCss);
|
|
130
|
+
__rspack_external_css_tree_6b21abdd.walk(ast, {
|
|
131
|
+
visit: "Rule",
|
|
132
|
+
enter (node) {
|
|
133
|
+
const selectorList = node.prelude;
|
|
134
|
+
if (!selectorList || "SelectorList" !== selectorList.type) return;
|
|
135
|
+
const newSelectors = new __rspack_external_css_tree_6b21abdd.List();
|
|
136
|
+
selectorList.children.forEach((selector)=>{
|
|
137
|
+
const raw = __rspack_external_css_tree_6b21abdd.generate(selector).trim();
|
|
138
|
+
if (raw.startsWith(":root")) return void newSelectors.appendData(selector);
|
|
139
|
+
const scoped = __rspack_external_css_tree_6b21abdd.parse(`.${scopeName} ${raw}`, {
|
|
140
|
+
context: "selector"
|
|
141
|
+
});
|
|
142
|
+
newSelectors.appendData(scoped);
|
|
143
|
+
});
|
|
144
|
+
selectorList.children = newSelectors;
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
return __rspack_external_css_tree_6b21abdd.generate(ast);
|
|
148
|
+
} catch {
|
|
149
|
+
return rawCss;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
export { ComponentsSdk };
|
|
153
|
+
|
|
154
|
+
//# sourceMappingURL=ComponentsSdk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ComponentsSdk.js","sources":["../src/ComponentsSdk.ts"],"sourcesContent":["import type { WebinyConfig } from \"@webiny/sdk\";\nimport { Result, HttpError, ApiError, NetworkError } from \"@webiny/sdk\";\n// @ts-expect-error No types available\nimport * as csstree from \"css-tree\";\n\nexport interface RemoteComponentEntry {\n id: string;\n name: string;\n label: string;\n bundledJs: string;\n bundledJsSha256: string;\n bundledCss: string;\n bundledCssSha256: string;\n sdkVersion: string;\n status: string;\n}\n\nexport interface LoadComponentsOptions {\n fetchOptions?: RequestInit;\n}\n\nexport interface HydrateComponentDependencies {\n sdk: unknown;\n React: unknown;\n}\n\nexport interface HydrateComponentOptions {\n tenantId?: string;\n locale?: string;\n mode?: \"server\" | \"browser\";\n}\n\nexport interface HydratedComponent {\n component: any;\n manifest: any;\n css: string;\n scopeClassName: string;\n}\n\nconst LIST_REMOTE_COMPONENTS = /* GraphQL */ `\n query ListRemoteComponents {\n remoteComponents {\n listRemoteComponents {\n data {\n id\n name\n label\n bundledJs\n bundledJsSha256\n bundledCss\n bundledCssSha256\n sdkVersion\n status\n }\n error {\n code\n message\n }\n }\n }\n }\n`;\n\ninterface ListRemoteComponentsResponse {\n remoteComponents: {\n listRemoteComponents: {\n data: RemoteComponentEntry[] | null;\n error: { code: string; message: string } | null;\n };\n };\n}\n\nexport class ComponentsSdk {\n private config: WebinyConfig;\n private fetchFn: typeof fetch;\n\n constructor(config: WebinyConfig) {\n this.config = config;\n this.fetchFn = config.fetch ?? fetch;\n }\n\n async loadComponents(\n options?: LoadComponentsOptions\n ): Promise<Result<RemoteComponentEntry[], HttpError | ApiError | NetworkError>> {\n const url = `${this.config.endpoint}/graphql`;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"x-tenant\": this.config.tenant ?? \"root\",\n ...this.config.headers\n };\n\n if (this.config.token && !headers.Authorization) {\n const token =\n typeof this.config.token === \"function\"\n ? await this.config.token()\n : this.config.token;\n headers.Authorization = `Bearer ${token}`;\n }\n\n const callerHeaders = options?.fetchOptions?.headers;\n\n // Call without a receiver. Browsers reject `fetch` called as a method of another object.\n const fetchFn = this.fetchFn;\n\n let response: Response;\n try {\n // Inside the `try`, so invalid caller headers fail like a rejected `fetch` does.\n const requestHeaders = callerHeaders ? mergeHeaders(callerHeaders, headers) : headers;\n // The SDK's `method`, `headers` and `body` go last, so `fetchOptions` can't replace them.\n response = await fetchFn(url, {\n ...options?.fetchOptions,\n method: \"POST\",\n headers: requestHeaders,\n body: JSON.stringify({ query: LIST_REMOTE_COMPONENTS })\n });\n } catch (error) {\n return Result.fail(\n new NetworkError(error instanceof Error ? error.message : \"Network request failed\")\n );\n }\n\n if (!response.ok) {\n return Result.fail(\n new HttpError(response.status, `HTTP error! status: ${response.status}`)\n );\n }\n\n let json: { data?: ListRemoteComponentsResponse; errors?: Array<{ message: string }> };\n try {\n json = await response.json();\n } catch {\n return Result.fail(new NetworkError(\"Failed to parse response JSON\"));\n }\n\n if (json.errors) {\n const error = json.errors[0];\n return Result.fail(new ApiError(error?.message || \"GraphQL error\"));\n }\n\n const envelope = json.data?.remoteComponents?.listRemoteComponents;\n if (!envelope) {\n return Result.fail(\n new ApiError(\n \"Unexpected response — is the remote-components API extension deployed?\"\n )\n );\n }\n\n if (envelope.error) {\n return Result.fail(new ApiError(envelope.error.message, envelope.error.code));\n }\n\n return Result.ok(envelope.data ?? []);\n }\n\n hydrateComponent(\n entry: RemoteComponentEntry,\n dependencies: HydrateComponentDependencies,\n options?: HydrateComponentOptions\n ): HydratedComponent | null {\n const runtimeSdk = {\n version: \"1\" as const,\n dependencies: {\n sdk: dependencies.sdk,\n React: dependencies.React\n },\n environment: {\n tenantId: options?.tenantId ?? this.config.tenant ?? \"root\",\n locale: options?.locale ?? \"en-US\",\n mode: options?.mode ?? \"browser\"\n }\n };\n\n try {\n const fn = new Function(`\n var __remoteComponent__;\n ${entry.bundledJs}\n return __remoteComponent__;\n `);\n const mod = fn();\n const component = mod.createComponent(runtimeSdk);\n if (!component) {\n return null;\n }\n\n const scopeClass = toScopeClassName(entry.name);\n const R = dependencies.React as typeof import(\"react\");\n const OriginalComponent = component.component;\n\n const ScopedComponent = (props: Record<string, unknown>) =>\n R.createElement(\n \"div\",\n { className: scopeClass },\n R.createElement(OriginalComponent, props)\n );\n ScopedComponent.displayName = `RemoteScope(${scopeClass})`;\n\n return {\n component: ScopedComponent,\n manifest: component.manifest,\n css: entry.bundledCss ?? \"\",\n scopeClassName: scopeClass\n };\n } catch (error) {\n console.error(`[ComponentsSdk] Failed to hydrate component \"${entry.name}\":`, error);\n return null;\n }\n }\n\n scopeCss(rawCss: string, componentName: string): string {\n return scopeCss(rawCss, toScopeClassName(componentName));\n }\n}\n\n// Applies `headers` over `callerHeaders`. `Headers` matches names case-insensitively, so a caller's\n// `authorization` can't sit next to the SDK's `Authorization`.\nfunction mergeHeaders(callerHeaders: HeadersInit, headers: Record<string, string>): Headers {\n const merged = new Headers(callerHeaders);\n for (const [name, value] of Object.entries(headers)) {\n merged.set(name, value);\n }\n return merged;\n}\n\nfunction toScopeClassName(name: string): string {\n return `rc-${name.replace(/\\//g, \"-\").toLowerCase()}`;\n}\n\nfunction scopeCss(rawCss: string, scopeName: string): string {\n if (!rawCss) {\n return \"\";\n }\n\n try {\n const ast = csstree.parse(rawCss);\n\n csstree.walk(ast, {\n visit: \"Rule\",\n enter(node: any) {\n const selectorList = node.prelude;\n if (!selectorList || selectorList.type !== \"SelectorList\") {\n return;\n }\n\n const newSelectors = new csstree.List();\n\n selectorList.children.forEach((selector: any) => {\n const raw = csstree.generate(selector).trim();\n if (raw.startsWith(\":root\")) {\n newSelectors.appendData(selector);\n return;\n }\n\n const scoped = csstree.parse(`.${scopeName} ${raw}`, {\n context: \"selector\"\n });\n newSelectors.appendData(scoped);\n });\n\n selectorList.children = newSelectors;\n }\n });\n\n return csstree.generate(ast);\n } catch {\n return rawCss;\n }\n}\n"],"names":["LIST_REMOTE_COMPONENTS","ComponentsSdk","config","fetch","options","url","headers","token","callerHeaders","fetchFn","response","requestHeaders","mergeHeaders","JSON","error","Result","NetworkError","Error","HttpError","json","ApiError","envelope","entry","dependencies","runtimeSdk","fn","Function","mod","component","scopeClass","toScopeClassName","R","OriginalComponent","ScopedComponent","props","console","rawCss","componentName","scopeCss","merged","Headers","name","value","Object","scopeName","ast","csstree","node","selectorList","newSelectors","selector","raw","scoped"],"mappings":";;AAuCA,MAAMA,yBAAuC,CAAC;;;;;;;;;;;;;;;;;;;;;;AAsB9C,CAAC;AAWM,MAAMC;IAIT,YAAYC,MAAoB,CAAE;QAC9B,IAAI,CAAC,MAAM,GAAGA;QACd,IAAI,CAAC,OAAO,GAAGA,OAAO,KAAK,IAAIC;IACnC;IAEA,MAAM,eACFC,OAA+B,EAC6C;QAC5E,MAAMC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAE7C,MAAMC,UAAkC;YACpC,gBAAgB;YAChB,YAAY,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI;YAClC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO;QAC1B;QAEA,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,IAAI,CAACA,QAAQ,aAAa,EAAE;YAC7C,MAAMC,QACF,AAA6B,cAA7B,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,GAClB,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,KACvB,IAAI,CAAC,MAAM,CAAC,KAAK;YAC3BD,QAAQ,aAAa,GAAG,CAAC,OAAO,EAAEC,OAAO;QAC7C;QAEA,MAAMC,gBAAgBJ,SAAS,cAAc;QAG7C,MAAMK,UAAU,IAAI,CAAC,OAAO;QAE5B,IAAIC;QACJ,IAAI;YAEA,MAAMC,iBAAiBH,gBAAgBI,aAAaJ,eAAeF,WAAWA;YAE9EI,WAAW,MAAMD,QAAQJ,KAAK;gBAC1B,GAAGD,SAAS,YAAY;gBACxB,QAAQ;gBACR,SAASO;gBACT,MAAME,KAAK,SAAS,CAAC;oBAAE,OAAOb;gBAAuB;YACzD;QACJ,EAAE,OAA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BA,aAAa,IAAI,EAClC;gBAGJ,MAAMC,eAAe,IAAIH,oCAAAA,IAAY;gBAErCE,aAAa,QAAQ,CAAC,OAAO,CAAC,CAACE;oBAC3B,MAAMC,MAAML,oCAAAA,QAAgB,CAACI,UAAU,IAAI;oBAC3C,IAAIC,IAAI,UAAU,CAAC,UAAU,YACzBF,aAAa,UAAU,CAACC;oBAI5B,MAAME,SAASN,oCAAAA,KAAa,CAAC,CAAC,CAAC,EAAEF,UAAU,CAAC,EAAEO,KAAK,EAAE;wBACjD,SAAS;oBACb;oBACAF,aAAa,UAAU,CAACG;gBAC5B;gBAEAJ,aAAa,QAAQ,GAAGC;YAC5B;QACJ;QAEA,OAAOH,oCAAAA,QAAgB,CAACD;IAC5B,EAAE,OAAM;QACJ,OAAOT;IACX;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { ApiError, HttpError, NetworkError } from "@webiny/sdk";
|
|
3
|
+
import { ComponentsSdk } from "./ComponentsSdk.js";
|
|
4
|
+
const endpoint = "https://api.example.com";
|
|
5
|
+
const entry = {
|
|
6
|
+
id: "c1",
|
|
7
|
+
name: "acme/hero",
|
|
8
|
+
label: "Hero",
|
|
9
|
+
bundledJs: "",
|
|
10
|
+
bundledJsSha256: "",
|
|
11
|
+
bundledCss: "",
|
|
12
|
+
bundledCssSha256: "",
|
|
13
|
+
sdkVersion: "1",
|
|
14
|
+
status: "published"
|
|
15
|
+
};
|
|
16
|
+
function jsonResponse(body, status = 200) {
|
|
17
|
+
return new Response(JSON.stringify(body), {
|
|
18
|
+
status,
|
|
19
|
+
headers: {
|
|
20
|
+
"Content-Type": "application/json"
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function listResponse(data) {
|
|
25
|
+
return jsonResponse({
|
|
26
|
+
data: {
|
|
27
|
+
remoteComponents: {
|
|
28
|
+
listRemoteComponents: {
|
|
29
|
+
data,
|
|
30
|
+
error: null
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function browserLikeFetch() {
|
|
37
|
+
if (this !== globalThis && void 0 !== this) throw new TypeError("Failed to execute 'fetch' on 'Window': Illegal invocation");
|
|
38
|
+
return Promise.resolve(listResponse([]));
|
|
39
|
+
}
|
|
40
|
+
afterEach(()=>{
|
|
41
|
+
vi.unstubAllGlobals();
|
|
42
|
+
});
|
|
43
|
+
describe("ComponentsSdk.loadComponents", ()=>{
|
|
44
|
+
describe("fetch receiver", ()=>{
|
|
45
|
+
it("calls the global fetch without the SDK instance as receiver", async ()=>{
|
|
46
|
+
vi.stubGlobal("fetch", browserLikeFetch);
|
|
47
|
+
const sdk = new ComponentsSdk({
|
|
48
|
+
endpoint: endpoint
|
|
49
|
+
});
|
|
50
|
+
const result = await sdk.loadComponents();
|
|
51
|
+
expect(result.isOk()).toBe(true);
|
|
52
|
+
expect(result.value).toEqual([]);
|
|
53
|
+
});
|
|
54
|
+
it("calls config.fetch without the SDK instance as receiver", async ()=>{
|
|
55
|
+
const sdk = new ComponentsSdk({
|
|
56
|
+
endpoint: endpoint,
|
|
57
|
+
fetch: browserLikeFetch
|
|
58
|
+
});
|
|
59
|
+
const result = await sdk.loadComponents();
|
|
60
|
+
expect(result.isOk()).toBe(true);
|
|
61
|
+
expect(result.value).toEqual([]);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
describe("request and result", ()=>{
|
|
65
|
+
it("sends the same URL and init", async ()=>{
|
|
66
|
+
const fetchFn = vi.fn(async ()=>listResponse([
|
|
67
|
+
entry
|
|
68
|
+
]));
|
|
69
|
+
const sdk = new ComponentsSdk({
|
|
70
|
+
endpoint: endpoint,
|
|
71
|
+
tenant: "acme",
|
|
72
|
+
token: "secret",
|
|
73
|
+
headers: {
|
|
74
|
+
"x-custom": "1"
|
|
75
|
+
},
|
|
76
|
+
fetch: fetchFn
|
|
77
|
+
});
|
|
78
|
+
await sdk.loadComponents({
|
|
79
|
+
fetchOptions: {
|
|
80
|
+
cache: "no-store",
|
|
81
|
+
method: "GET"
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
expect(fetchFn).toHaveBeenCalledTimes(1);
|
|
85
|
+
const [url, init] = fetchFn.mock.calls[0];
|
|
86
|
+
expect(url).toBe(`${endpoint}/graphql`);
|
|
87
|
+
expect(init).toEqual({
|
|
88
|
+
method: "POST",
|
|
89
|
+
cache: "no-store",
|
|
90
|
+
headers: {
|
|
91
|
+
"Content-Type": "application/json",
|
|
92
|
+
"x-tenant": "acme",
|
|
93
|
+
"x-custom": "1",
|
|
94
|
+
Authorization: "Bearer secret"
|
|
95
|
+
},
|
|
96
|
+
body: expect.stringContaining("listRemoteComponents")
|
|
97
|
+
});
|
|
98
|
+
expect(JSON.parse(init.body)).toEqual({
|
|
99
|
+
query: expect.any(String)
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
it("defaults the tenant and resolves a token function", async ()=>{
|
|
103
|
+
const fetchFn = vi.fn(async ()=>listResponse([]));
|
|
104
|
+
const sdk = new ComponentsSdk({
|
|
105
|
+
endpoint: endpoint,
|
|
106
|
+
token: async ()=>"from-fn",
|
|
107
|
+
fetch: fetchFn
|
|
108
|
+
});
|
|
109
|
+
await sdk.loadComponents();
|
|
110
|
+
const [, init] = fetchFn.mock.calls[0];
|
|
111
|
+
expect(init.method).toBe("POST");
|
|
112
|
+
expect(init.headers).toEqual({
|
|
113
|
+
"Content-Type": "application/json",
|
|
114
|
+
"x-tenant": "root",
|
|
115
|
+
Authorization: "Bearer from-fn"
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
it("returns the components on an OK response", async ()=>{
|
|
119
|
+
const sdk = new ComponentsSdk({
|
|
120
|
+
endpoint: endpoint,
|
|
121
|
+
fetch: vi.fn(async ()=>listResponse([
|
|
122
|
+
entry
|
|
123
|
+
]))
|
|
124
|
+
});
|
|
125
|
+
const result = await sdk.loadComponents();
|
|
126
|
+
expect(result.isOk()).toBe(true);
|
|
127
|
+
expect(result.value).toEqual([
|
|
128
|
+
entry
|
|
129
|
+
]);
|
|
130
|
+
});
|
|
131
|
+
it("returns an HttpError on a non-OK status", async ()=>{
|
|
132
|
+
const sdk = new ComponentsSdk({
|
|
133
|
+
endpoint: endpoint,
|
|
134
|
+
fetch: vi.fn(async ()=>jsonResponse({}, 503))
|
|
135
|
+
});
|
|
136
|
+
const result = await sdk.loadComponents();
|
|
137
|
+
expect(result.isFail()).toBe(true);
|
|
138
|
+
expect(result.error).toBeInstanceOf(HttpError);
|
|
139
|
+
expect(result.error.message).toBe("HTTP error! status: 503");
|
|
140
|
+
expect(result.error.data).toEqual({
|
|
141
|
+
status: 503
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
it("returns a NetworkError when fetch throws", async ()=>{
|
|
145
|
+
const sdk = new ComponentsSdk({
|
|
146
|
+
endpoint: endpoint,
|
|
147
|
+
fetch: vi.fn(async ()=>{
|
|
148
|
+
throw new Error("connection refused");
|
|
149
|
+
})
|
|
150
|
+
});
|
|
151
|
+
const result = await sdk.loadComponents();
|
|
152
|
+
expect(result.isFail()).toBe(true);
|
|
153
|
+
expect(result.error).toBeInstanceOf(NetworkError);
|
|
154
|
+
expect(result.error.message).toBe("connection refused");
|
|
155
|
+
});
|
|
156
|
+
it("returns an ApiError on a GraphQL errors response", async ()=>{
|
|
157
|
+
const sdk = new ComponentsSdk({
|
|
158
|
+
endpoint: endpoint,
|
|
159
|
+
fetch: vi.fn(async ()=>jsonResponse({
|
|
160
|
+
errors: [
|
|
161
|
+
{
|
|
162
|
+
message: "Not authorized"
|
|
163
|
+
}
|
|
164
|
+
]
|
|
165
|
+
}))
|
|
166
|
+
});
|
|
167
|
+
const result = await sdk.loadComponents();
|
|
168
|
+
expect(result.isFail()).toBe(true);
|
|
169
|
+
expect(result.error).toBeInstanceOf(ApiError);
|
|
170
|
+
expect(result.error.message).toBe("Not authorized");
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
describe("fetchOptions", ()=>{
|
|
174
|
+
const sdkHeaders = {
|
|
175
|
+
"content-type": "application/json",
|
|
176
|
+
"x-tenant": "acme",
|
|
177
|
+
"x-custom": "1",
|
|
178
|
+
authorization: "Bearer secret"
|
|
179
|
+
};
|
|
180
|
+
function createSdk() {
|
|
181
|
+
const fetchFn = vi.fn(async ()=>listResponse([]));
|
|
182
|
+
const sdk = new ComponentsSdk({
|
|
183
|
+
endpoint: endpoint,
|
|
184
|
+
tenant: "acme",
|
|
185
|
+
token: "secret",
|
|
186
|
+
headers: {
|
|
187
|
+
"x-custom": "1"
|
|
188
|
+
},
|
|
189
|
+
fetch: fetchFn
|
|
190
|
+
});
|
|
191
|
+
return {
|
|
192
|
+
sdk,
|
|
193
|
+
fetchFn
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function sentInit(fetchFn) {
|
|
197
|
+
const [, init] = fetchFn.mock.calls[0];
|
|
198
|
+
return init;
|
|
199
|
+
}
|
|
200
|
+
function sentHeaders(init) {
|
|
201
|
+
const headers = new Headers(init.headers);
|
|
202
|
+
return Object.fromEntries(headers.entries());
|
|
203
|
+
}
|
|
204
|
+
const callerHeaderForms = [
|
|
205
|
+
[
|
|
206
|
+
"a plain object",
|
|
207
|
+
{
|
|
208
|
+
"x-extra": "extra",
|
|
209
|
+
"x-tenant": "other",
|
|
210
|
+
Authorization: "Bearer caller",
|
|
211
|
+
"Content-Type": "text/plain"
|
|
212
|
+
}
|
|
213
|
+
],
|
|
214
|
+
[
|
|
215
|
+
"a Headers instance",
|
|
216
|
+
new Headers({
|
|
217
|
+
"x-extra": "extra",
|
|
218
|
+
"x-tenant": "other",
|
|
219
|
+
Authorization: "Bearer caller",
|
|
220
|
+
"Content-Type": "text/plain"
|
|
221
|
+
})
|
|
222
|
+
],
|
|
223
|
+
[
|
|
224
|
+
"an array of pairs",
|
|
225
|
+
[
|
|
226
|
+
[
|
|
227
|
+
"x-extra",
|
|
228
|
+
"extra"
|
|
229
|
+
],
|
|
230
|
+
[
|
|
231
|
+
"x-tenant",
|
|
232
|
+
"other"
|
|
233
|
+
],
|
|
234
|
+
[
|
|
235
|
+
"authorization",
|
|
236
|
+
"Bearer caller"
|
|
237
|
+
],
|
|
238
|
+
[
|
|
239
|
+
"content-type",
|
|
240
|
+
"text/plain"
|
|
241
|
+
]
|
|
242
|
+
]
|
|
243
|
+
]
|
|
244
|
+
];
|
|
245
|
+
it.each(callerHeaderForms)("merges headers given as %s under the SDK's headers", async (_, callerHeaders)=>{
|
|
246
|
+
const { sdk, fetchFn } = createSdk();
|
|
247
|
+
await sdk.loadComponents({
|
|
248
|
+
fetchOptions: {
|
|
249
|
+
headers: callerHeaders
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
const init = sentInit(fetchFn);
|
|
253
|
+
expect(sentHeaders(init)).toEqual({
|
|
254
|
+
...sdkHeaders,
|
|
255
|
+
"x-extra": "extra"
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
it("keeps the configured headers over the caller's headers", async ()=>{
|
|
259
|
+
const { sdk, fetchFn } = createSdk();
|
|
260
|
+
await sdk.loadComponents({
|
|
261
|
+
fetchOptions: {
|
|
262
|
+
headers: {
|
|
263
|
+
"X-Custom": "caller"
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
const init = sentInit(fetchFn);
|
|
268
|
+
expect(sentHeaders(init)).toEqual(sdkHeaders);
|
|
269
|
+
});
|
|
270
|
+
it("returns a NetworkError when the caller's headers are invalid", async ()=>{
|
|
271
|
+
const { sdk, fetchFn } = createSdk();
|
|
272
|
+
const result = await sdk.loadComponents({
|
|
273
|
+
fetchOptions: {
|
|
274
|
+
headers: {
|
|
275
|
+
"bad header": "1"
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
expect(result.isFail()).toBe(true);
|
|
280
|
+
expect(result.error).toBeInstanceOf(NetworkError);
|
|
281
|
+
expect(fetchFn).not.toHaveBeenCalled();
|
|
282
|
+
});
|
|
283
|
+
it("ignores method and body, and passes other fields through", async ()=>{
|
|
284
|
+
const { sdk, fetchFn } = createSdk();
|
|
285
|
+
const controller = new AbortController();
|
|
286
|
+
await sdk.loadComponents({
|
|
287
|
+
fetchOptions: {
|
|
288
|
+
method: "GET",
|
|
289
|
+
body: "caller body",
|
|
290
|
+
cache: "no-store",
|
|
291
|
+
credentials: "include",
|
|
292
|
+
signal: controller.signal,
|
|
293
|
+
next: {
|
|
294
|
+
revalidate: 60
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
const init = sentInit(fetchFn);
|
|
299
|
+
expect(init.method).toBe("POST");
|
|
300
|
+
expect(JSON.parse(init.body)).toEqual({
|
|
301
|
+
query: expect.stringContaining("listRemoteComponents")
|
|
302
|
+
});
|
|
303
|
+
expect(init.cache).toBe("no-store");
|
|
304
|
+
expect(init.credentials).toBe("include");
|
|
305
|
+
expect(init.signal).toBe(controller.signal);
|
|
306
|
+
expect(init.next).toEqual({
|
|
307
|
+
revalidate: 60
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
//# sourceMappingURL=ComponentsSdk.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ComponentsSdk.test.js","sources":["../src/ComponentsSdk.test.ts"],"sourcesContent":["import { describe, it, expect, vi, afterEach } from \"vitest\";\nimport { HttpError } from \"@webiny/sdk\";\nimport { ApiError } from \"@webiny/sdk\";\nimport { NetworkError } from \"@webiny/sdk\";\nimport { ComponentsSdk } from \"./ComponentsSdk.js\";\nimport type { RemoteComponentEntry } from \"./ComponentsSdk.js\";\n\nconst endpoint = \"https://api.example.com\";\n\nconst entry: RemoteComponentEntry = {\n id: \"c1\",\n name: \"acme/hero\",\n label: \"Hero\",\n bundledJs: \"\",\n bundledJsSha256: \"\",\n bundledCss: \"\",\n bundledCssSha256: \"\",\n sdkVersion: \"1\",\n status: \"published\"\n};\n\nfunction jsonResponse(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\" }\n });\n}\n\nfunction listResponse(data: RemoteComponentEntry[]): Response {\n return jsonResponse({\n data: { remoteComponents: { listRemoteComponents: { data, error: null } } }\n });\n}\n\n// Behaves like a browser's `fetch`: only `globalThis` or `undefined` are accepted as the receiver.\nfunction browserLikeFetch(this: unknown): Promise<Response> {\n if (this !== globalThis && this !== undefined) {\n throw new TypeError(\"Failed to execute 'fetch' on 'Window': Illegal invocation\");\n }\n return Promise.resolve(listResponse([]));\n}\n\nafterEach(() => {\n vi.unstubAllGlobals();\n});\n\ndescribe(\"ComponentsSdk.loadComponents\", () => {\n describe(\"fetch receiver\", () => {\n it(\"calls the global fetch without the SDK instance as receiver\", async () => {\n vi.stubGlobal(\"fetch\", browserLikeFetch);\n const sdk = new ComponentsSdk({ endpoint });\n\n const result = await sdk.loadComponents();\n\n expect(result.isOk()).toBe(true);\n expect(result.value).toEqual([]);\n });\n\n it(\"calls config.fetch without the SDK instance as receiver\", async () => {\n const sdk = new ComponentsSdk({ endpoint, fetch: browserLikeFetch as typeof fetch });\n\n const result = await sdk.loadComponents();\n\n expect(result.isOk()).toBe(true);\n expect(result.value).toEqual([]);\n });\n });\n\n describe(\"request and result\", () => {\n it(\"sends the same URL and init\", async () => {\n const fetchFn = vi.fn(async () => listResponse([entry]));\n const sdk = new ComponentsSdk({\n endpoint,\n tenant: \"acme\",\n token: \"secret\",\n headers: { \"x-custom\": \"1\" },\n fetch: fetchFn\n });\n\n await sdk.loadComponents({\n fetchOptions: { cache: \"no-store\", method: \"GET\" }\n });\n\n expect(fetchFn).toHaveBeenCalledTimes(1);\n const [url, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];\n expect(url).toBe(`${endpoint}/graphql`);\n expect(init).toEqual({\n // `fetchOptions` can't replace the GraphQL request's `method`.\n method: \"POST\",\n cache: \"no-store\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-tenant\": \"acme\",\n \"x-custom\": \"1\",\n Authorization: \"Bearer secret\"\n },\n body: expect.stringContaining(\"listRemoteComponents\")\n });\n expect(JSON.parse(init.body as string)).toEqual({ query: expect.any(String) });\n });\n\n it(\"defaults the tenant and resolves a token function\", async () => {\n const fetchFn = vi.fn(async () => listResponse([]));\n const sdk = new ComponentsSdk({\n endpoint,\n token: async () => \"from-fn\",\n fetch: fetchFn\n });\n\n await sdk.loadComponents();\n\n const [, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];\n expect(init.method).toBe(\"POST\");\n expect(init.headers).toEqual({\n \"Content-Type\": \"application/json\",\n \"x-tenant\": \"root\",\n Authorization: \"Bearer from-fn\"\n });\n });\n\n it(\"returns the components on an OK response\", async () => {\n const sdk = new ComponentsSdk({\n endpoint,\n fetch: vi.fn(async () => listResponse([entry]))\n });\n\n const result = await sdk.loadComponents();\n\n expect(result.isOk()).toBe(true);\n expect(result.value).toEqual([entry]);\n });\n\n it(\"returns an HttpError on a non-OK status\", async () => {\n const sdk = new ComponentsSdk({\n endpoint,\n fetch: vi.fn(async () => jsonResponse({}, 503))\n });\n\n const result = await sdk.loadComponents();\n\n expect(result.isFail()).toBe(true);\n expect(result.error).toBeInstanceOf(HttpError);\n expect(result.error.message).toBe(\"HTTP error! status: 503\");\n expect(result.error.data).toEqual({ status: 503 });\n });\n\n it(\"returns a NetworkError when fetch throws\", async () => {\n const sdk = new ComponentsSdk({\n endpoint,\n fetch: vi.fn(async () => {\n throw new Error(\"connection refused\");\n })\n });\n\n const result = await sdk.loadComponents();\n\n expect(result.isFail()).toBe(true);\n expect(result.error).toBeInstanceOf(NetworkError);\n expect(result.error.message).toBe(\"connection refused\");\n });\n\n it(\"returns an ApiError on a GraphQL errors response\", async () => {\n const sdk = new ComponentsSdk({\n endpoint,\n fetch: vi.fn(async () => jsonResponse({ errors: [{ message: \"Not authorized\" }] }))\n });\n\n const result = await sdk.loadComponents();\n\n expect(result.isFail()).toBe(true);\n expect(result.error).toBeInstanceOf(ApiError);\n expect(result.error.message).toBe(\"Not authorized\");\n });\n });\n describe(\"fetchOptions\", () => {\n const sdkHeaders = {\n \"content-type\": \"application/json\",\n \"x-tenant\": \"acme\",\n \"x-custom\": \"1\",\n authorization: \"Bearer secret\"\n };\n\n function createSdk() {\n const fetchFn = vi.fn(async () => listResponse([]));\n const sdk = new ComponentsSdk({\n endpoint,\n tenant: \"acme\",\n token: \"secret\",\n headers: { \"x-custom\": \"1\" },\n fetch: fetchFn\n });\n return { sdk, fetchFn };\n }\n\n function sentInit(fetchFn: ReturnType<typeof createSdk>[\"fetchFn\"]): RequestInit {\n const [, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];\n return init;\n }\n\n function sentHeaders(init: RequestInit): Record<string, string> {\n const headers = new Headers(init.headers);\n return Object.fromEntries(headers.entries());\n }\n\n const callerHeaderForms: Array<[string, HeadersInit]> = [\n [\n \"a plain object\",\n {\n \"x-extra\": \"extra\",\n \"x-tenant\": \"other\",\n Authorization: \"Bearer caller\",\n \"Content-Type\": \"text/plain\"\n }\n ],\n [\n \"a Headers instance\",\n new Headers({\n \"x-extra\": \"extra\",\n \"x-tenant\": \"other\",\n Authorization: \"Bearer caller\",\n \"Content-Type\": \"text/plain\"\n })\n ],\n [\n \"an array of pairs\",\n [\n [\"x-extra\", \"extra\"],\n [\"x-tenant\", \"other\"],\n [\"authorization\", \"Bearer caller\"],\n [\"content-type\", \"text/plain\"]\n ]\n ]\n ];\n\n it.each(callerHeaderForms)(\n \"merges headers given as %s under the SDK's headers\",\n async (_, callerHeaders) => {\n const { sdk, fetchFn } = createSdk();\n\n await sdk.loadComponents({ fetchOptions: { headers: callerHeaders } });\n\n const init = sentInit(fetchFn);\n expect(sentHeaders(init)).toEqual({ ...sdkHeaders, \"x-extra\": \"extra\" });\n }\n );\n\n it(\"keeps the configured headers over the caller's headers\", async () => {\n const { sdk, fetchFn } = createSdk();\n\n await sdk.loadComponents({ fetchOptions: { headers: { \"X-Custom\": \"caller\" } } });\n\n const init = sentInit(fetchFn);\n expect(sentHeaders(init)).toEqual(sdkHeaders);\n });\n\n it(\"returns a NetworkError when the caller's headers are invalid\", async () => {\n const { sdk, fetchFn } = createSdk();\n\n const result = await sdk.loadComponents({\n fetchOptions: { headers: { \"bad header\": \"1\" } }\n });\n\n expect(result.isFail()).toBe(true);\n expect(result.error).toBeInstanceOf(NetworkError);\n expect(fetchFn).not.toHaveBeenCalled();\n });\n\n it(\"ignores method and body, and passes other fields through\", async () => {\n const { sdk, fetchFn } = createSdk();\n const controller = new AbortController();\n\n await sdk.loadComponents({\n fetchOptions: {\n method: \"GET\",\n body: \"caller body\",\n cache: \"no-store\",\n credentials: \"include\",\n signal: controller.signal,\n next: { revalidate: 60 }\n } as RequestInit\n });\n\n const init = sentInit(fetchFn) as RequestInit & { next?: unknown };\n expect(init.method).toBe(\"POST\");\n expect(JSON.parse(init.body as string)).toEqual({\n query: expect.stringContaining(\"listRemoteComponents\")\n });\n expect(init.cache).toBe(\"no-store\");\n expect(init.credentials).toBe(\"include\");\n expect(init.signal).toBe(controller.signal);\n expect(init.next).toEqual({ revalidate: 60 });\n });\n });\n});\n"],"names":["endpoint","entry","jsonResponse","body","status","Response","JSON","listResponse","data","browserLikeFetch","globalThis","undefined","TypeError","Promise","afterEach","vi","describe","it","sdk","ComponentsSdk","result","expect","fetchFn","url","init","String","HttpError","Error","NetworkError","ApiError","sdkHeaders","createSdk","sentInit","sentHeaders","headers","Headers","Object","callerHeaderForms","_","callerHeaders","controller","AbortController"],"mappings":";;;AAOA,MAAMA,WAAW;AAEjB,MAAMC,QAA8B;IAChC,IAAI;IACJ,MAAM;IACN,OAAO;IACP,WAAW;IACX,iBAAiB;IACjB,YAAY;IACZ,kBAAkB;IAClB,YAAY;IACZ,QAAQ;AACZ;AAEA,SAASC,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dk, TenantManagerSdk, TasksSdk, WebhooksSdk } from "@webiny/sdk";
|
|
2
2
|
import { CmsSdk } from "./CmsSdk.js";
|
|
3
3
|
import { WbSdk } from "./WbSdk.js";
|
|
4
|
+
import { ComponentsSdk } from "./ComponentsSdk.js";
|
|
4
5
|
import type { ContentSdkConfig } from "./types.js";
|
|
5
6
|
export declare class FrontendSdk {
|
|
6
7
|
private sdk?;
|
|
@@ -12,6 +13,7 @@ export declare class FrontendSdk {
|
|
|
12
13
|
get tenantManager(): TenantManagerSdk;
|
|
13
14
|
get tasks(): TasksSdk;
|
|
14
15
|
get webhooks(): WebhooksSdk;
|
|
16
|
+
get components(): ComponentsSdk;
|
|
15
17
|
init(config: ContentSdkConfig): void;
|
|
16
18
|
isEditing(): boolean;
|
|
17
19
|
isServer(): boolean;
|
package/FrontendSdk.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { Webiny } from "@webiny/sdk";
|
|
2
2
|
import { contentSdk, environment } from "@webiny/cms-sdk";
|
|
3
3
|
import { contentSdk as website_builder_sdk_contentSdk } from "@webiny/website-builder-sdk";
|
|
4
|
+
import { ensureContentEntryLoader } from "./resolveContentEntries.js";
|
|
4
5
|
import { CmsSdk } from "./CmsSdk.js";
|
|
5
6
|
import { WbSdk } from "./WbSdk.js";
|
|
7
|
+
import { ComponentsSdk } from "./ComponentsSdk.js";
|
|
6
8
|
class FrontendSdk {
|
|
7
9
|
get initialized() {
|
|
8
10
|
if (!this.sdk) throw new Error("SDK is not initialized. Call sdk.init() first.");
|
|
@@ -29,6 +31,9 @@ class FrontendSdk {
|
|
|
29
31
|
get webhooks() {
|
|
30
32
|
return this.initialized.webiny.webhooks;
|
|
31
33
|
}
|
|
34
|
+
get components() {
|
|
35
|
+
return this.initialized.components;
|
|
36
|
+
}
|
|
32
37
|
init(config) {
|
|
33
38
|
const webiny = new Webiny({
|
|
34
39
|
endpoint: config.endpoint,
|
|
@@ -39,7 +44,13 @@ class FrontendSdk {
|
|
|
39
44
|
this.sdk = {
|
|
40
45
|
webiny,
|
|
41
46
|
cms: new CmsSdk(webiny),
|
|
42
|
-
wb: new WbSdk()
|
|
47
|
+
wb: new WbSdk(),
|
|
48
|
+
components: new ComponentsSdk({
|
|
49
|
+
endpoint: config.endpoint,
|
|
50
|
+
token: config.token,
|
|
51
|
+
tenant: config.tenant || "root",
|
|
52
|
+
fetch: config.fetch
|
|
53
|
+
})
|
|
43
54
|
};
|
|
44
55
|
contentSdk.init({
|
|
45
56
|
apiHost: config.endpoint,
|
|
@@ -57,6 +68,7 @@ class FrontendSdk {
|
|
|
57
68
|
previewParams: config.wb?.previewParams
|
|
58
69
|
});
|
|
59
70
|
if (config.wb?.componentGroups) for (const group of config.wb.componentGroups)this.sdk.wb.registerComponentGroup(group);
|
|
71
|
+
ensureContentEntryLoader();
|
|
60
72
|
}
|
|
61
73
|
isEditing() {
|
|
62
74
|
return environment.isEditing();
|