@vaadin/hilla-frontend 24.7.0-alpha9 → 24.7.0-beta2

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/Connect.js CHANGED
@@ -1,187 +1,238 @@
1
1
  import { ConnectionIndicator, ConnectionState } from "@vaadin/common-frontend";
2
2
  import { getCsrfTokenHeadersForEndpointRequest } from "./CsrfUtils.js";
3
- import {
4
- EndpointError,
5
- EndpointResponseError,
6
- EndpointValidationError,
7
- ForbiddenResponseError,
8
- UnauthorizedResponseError
9
- } from "./EndpointErrors.js";
10
- import {
11
- FluxConnection
12
- } from "./FluxConnection.js";
3
+ import { EndpointError, EndpointResponseError, EndpointValidationError, ForbiddenResponseError, UnauthorizedResponseError } from "./EndpointErrors.js";
4
+ import { FluxConnection } from "./FluxConnection.js";
13
5
  const $wnd = globalThis;
14
6
  $wnd.Vaadin ??= {};
15
7
  $wnd.Vaadin.registrations ??= [];
16
- $wnd.Vaadin.registrations.push({
17
- is: "endpoint"
18
- });
8
+ $wnd.Vaadin.registrations.push({ is: "endpoint" });
9
+ export const BODY_PART_NAME = "hilla_body_part";
10
+ /**
11
+ * Throws a TypeError if the response is not 200 OK.
12
+ * @param response - The response to assert.
13
+ */
19
14
  const assertResponseIsOk = async (response) => {
20
- if (!response.ok) {
21
- const errorText = await response.text();
22
- let errorJson;
23
- try {
24
- errorJson = JSON.parse(errorText);
25
- } catch (ignored) {
26
- errorJson = null;
27
- }
28
- const message = errorJson?.message ?? (errorText.length > 0 ? errorText : `expected "200 OK" response, but got ${response.status} ${response.statusText}`);
29
- const type = errorJson?.type;
30
- if (errorJson?.validationErrorData) {
31
- throw new EndpointValidationError(message, errorJson.validationErrorData, type);
32
- }
33
- if (type) {
34
- throw new EndpointError(message, type, errorJson?.detail);
35
- }
36
- switch (response.status) {
37
- case 401:
38
- throw new UnauthorizedResponseError(message, response);
39
- case 403:
40
- throw new ForbiddenResponseError(message, response);
41
- default:
42
- throw new EndpointResponseError(message, response);
43
- }
44
- }
15
+ if (!response.ok) {
16
+ const errorText = await response.text();
17
+ let errorJson;
18
+ try {
19
+ errorJson = JSON.parse(errorText);
20
+ } catch {
21
+ errorJson = null;
22
+ }
23
+ const message = errorJson?.message ?? (errorText.length > 0 ? errorText : `expected "200 OK" response, but got ${response.status} ${response.statusText}`);
24
+ const type = errorJson?.type;
25
+ if (errorJson?.validationErrorData) {
26
+ throw new EndpointValidationError(message, errorJson.validationErrorData, type);
27
+ }
28
+ if (type) {
29
+ throw new EndpointError(message, type, errorJson?.detail);
30
+ }
31
+ switch (response.status) {
32
+ case 401: throw new UnauthorizedResponseError(message, response);
33
+ case 403: throw new ForbiddenResponseError(message, response);
34
+ default: throw new EndpointResponseError(message, response);
35
+ }
36
+ }
45
37
  };
46
38
  function isFlowLoaded() {
47
- return $wnd.Vaadin?.Flow?.clients?.TypeScript !== void 0;
39
+ return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;
48
40
  }
49
- class ConnectClient {
50
- /**
51
- * The array of middlewares that are invoked during a call.
52
- */
53
- middlewares = [];
54
- /**
55
- * The Hilla endpoint prefix
56
- */
57
- prefix = "/connect";
58
- /**
59
- * The Atmosphere options for the FluxConnection.
60
- */
61
- atmosphereOptions = {};
62
- #fluxConnection;
63
- /**
64
- * @param options - Constructor options.
65
- */
66
- constructor(options = {}) {
67
- if (options.prefix) {
68
- this.prefix = options.prefix;
69
- }
70
- if (options.middlewares) {
71
- this.middlewares = options.middlewares;
72
- }
73
- if (options.atmosphereOptions) {
74
- this.atmosphereOptions = options.atmosphereOptions;
75
- }
76
- ConnectionIndicator.create();
77
- addEventListener("online", () => {
78
- if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {
79
- $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;
80
- }
81
- });
82
- addEventListener("offline", () => {
83
- if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {
84
- $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;
85
- }
86
- });
87
- }
88
- /**
89
- * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint
90
- * methods.
91
- */
92
- get fluxConnection() {
93
- if (!this.#fluxConnection) {
94
- this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);
95
- }
96
- return this.#fluxConnection;
97
- }
98
- /**
99
- * Calls the given endpoint method defined using the endpoint and method
100
- * parameters with the parameters given as params.
101
- * Asynchronously returns the parsed JSON response data.
102
- *
103
- * @param endpoint - Endpoint name.
104
- * @param method - Method name to call in the endpoint class.
105
- * @param params - Optional parameters to pass to the method.
106
- * @param init - Optional parameters for the request
107
- * @returns Decoded JSON response data.
108
- */
109
- async call(endpoint, method, params, init) {
110
- if (arguments.length < 2) {
111
- throw new TypeError(`2 arguments required, but got only ${arguments.length}`);
112
- }
113
- const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};
114
- const headers = {
115
- Accept: "application/json",
116
- "Content-Type": "application/json",
117
- ...csrfHeaders
118
- };
119
- const request = new Request(`${this.prefix}/${endpoint}/${method}`, {
120
- body: params !== void 0 ? JSON.stringify(params, (_, value) => value === void 0 ? null : value) : void 0,
121
- headers,
122
- method: "POST"
123
- });
124
- const initialContext = {
125
- endpoint,
126
- method,
127
- params,
128
- request
129
- };
130
- async function responseHandlerMiddleware(context, next) {
131
- const response = await next(context);
132
- await assertResponseIsOk(response);
133
- const text = await response.text();
134
- return JSON.parse(text, (_, value) => value === null ? void 0 : value);
135
- }
136
- async function fetchNext(context) {
137
- $wnd.Vaadin?.connectionState?.loadingStarted();
138
- try {
139
- const response = await fetch(context.request, { signal: init?.signal });
140
- $wnd.Vaadin?.connectionState?.loadingFinished();
141
- return response;
142
- } catch (error) {
143
- if (error instanceof Error && error.name === "AbortError") {
144
- $wnd.Vaadin?.connectionState?.loadingFinished();
145
- } else {
146
- $wnd.Vaadin?.connectionState?.loadingFailed();
147
- }
148
- return Promise.reject(error);
149
- }
150
- }
151
- const middlewares = [responseHandlerMiddleware, ...this.middlewares];
152
- const chain = middlewares.reduceRight(
153
- (next, middleware) => (
154
- // Compose and return the new chain step, that takes the context and
155
- // invokes the current middleware with the context and the further chain
156
- // as the next argument
157
- async (context) => {
158
- if (typeof middleware === "function") {
159
- return middleware(context, next);
160
- }
161
- return middleware.invoke(context, next);
162
- }
163
- ),
164
- // Initialize reduceRight the accumulator with `fetchNext`
165
- fetchNext
166
- );
167
- return chain(initialContext);
168
- }
169
- /**
170
- * Subscribes to the given method defined using the endpoint and method
171
- * parameters with the parameters given as params. The method must return a
172
- * compatible type such as a Flux.
173
- * Returns a subscription that is used to fetch values as they become available.
174
- *
175
- * @param endpoint - Endpoint name.
176
- * @param method - Method name to call in the endpoint class.
177
- * @param params - Optional parameters to pass to the method.
178
- * @returns A subscription used to handles values as they become available.
179
- */
180
- subscribe(endpoint, method, params) {
181
- return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);
182
- }
41
+ /**
42
+ * Extracts file objects from the object that is used to build the request body.
43
+ *
44
+ * @param obj - The object to extract files from.
45
+ * @returns A tuple with the object without files and a map of files.
46
+ */
47
+ function extractFiles(obj) {
48
+ const fileMap = new Map();
49
+ function recursiveExtract(prop, path) {
50
+ if (prop !== null && typeof prop === "object") {
51
+ if (prop instanceof File) {
52
+ fileMap.set(path, prop);
53
+ return null;
54
+ }
55
+ if (Array.isArray(prop)) {
56
+ return prop.map((item, index) => recursiveExtract(item, `${path}/${index}`));
57
+ }
58
+ return Object.entries(prop).reduce((acc, [key, value]) => {
59
+ const newPath = `${path}/${key}`;
60
+ if (value instanceof File) {
61
+ fileMap.set(newPath, value);
62
+ } else {
63
+ acc[key] = recursiveExtract(value, newPath);
64
+ }
65
+ return acc;
66
+ }, {});
67
+ }
68
+ return prop;
69
+ }
70
+ return [recursiveExtract(obj, ""), fileMap];
183
71
  }
184
- export {
185
- ConnectClient
186
- };
187
- //# sourceMappingURL=Connect.js.map
72
+ /**
73
+ * A low-level network calling utility. It stores
74
+ * a prefix and facilitates remote calls to endpoint class methods
75
+ * on the Hilla backend.
76
+ *
77
+ * Example usage:
78
+ *
79
+ * ```js
80
+ * const client = new ConnectClient();
81
+ * const responseData = await client.call('MyEndpoint', 'myMethod');
82
+ * ```
83
+ *
84
+ * ### Prefix
85
+ *
86
+ * The client supports an `prefix` constructor option:
87
+ * ```js
88
+ * const client = new ConnectClient({prefix: '/my-connect-prefix'});
89
+ * ```
90
+ *
91
+ * The default prefix is '/connect'.
92
+ *
93
+ */
94
+ export class ConnectClient {
95
+ /**
96
+ * The array of middlewares that are invoked during a call.
97
+ */
98
+ middlewares = [];
99
+ /**
100
+ * The Hilla endpoint prefix
101
+ */
102
+ prefix = "/connect";
103
+ /**
104
+ * The Atmosphere options for the FluxConnection.
105
+ */
106
+ atmosphereOptions = {};
107
+ #fluxConnection;
108
+ /**
109
+ * @param options - Constructor options.
110
+ */
111
+ constructor(options = {}) {
112
+ if (options.prefix) {
113
+ this.prefix = options.prefix;
114
+ }
115
+ if (options.middlewares) {
116
+ this.middlewares = options.middlewares;
117
+ }
118
+ if (options.atmosphereOptions) {
119
+ this.atmosphereOptions = options.atmosphereOptions;
120
+ }
121
+ ConnectionIndicator.create();
122
+ addEventListener("online", () => {
123
+ if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {
124
+ $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;
125
+ }
126
+ });
127
+ addEventListener("offline", () => {
128
+ if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {
129
+ $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;
130
+ }
131
+ });
132
+ }
133
+ /**
134
+ * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint
135
+ * methods.
136
+ */
137
+ get fluxConnection() {
138
+ if (!this.#fluxConnection) {
139
+ this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);
140
+ }
141
+ return this.#fluxConnection;
142
+ }
143
+ /**
144
+ * Calls the given endpoint method defined using the endpoint and method
145
+ * parameters with the parameters given as params.
146
+ * Asynchronously returns the parsed JSON response data.
147
+ *
148
+ * @param endpoint - Endpoint name.
149
+ * @param method - Method name to call in the endpoint class.
150
+ * @param params - Optional parameters to pass to the method.
151
+ * @param init - Optional parameters for the request
152
+ * @returns Decoded JSON response data.
153
+ */
154
+ async call(endpoint, method, params, init) {
155
+ if (arguments.length < 2) {
156
+ throw new TypeError(`2 arguments required, but got only ${arguments.length}`);
157
+ }
158
+ const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};
159
+ const headers = {
160
+ Accept: "application/json",
161
+ ...csrfHeaders
162
+ };
163
+ const [paramsWithoutFiles, files] = extractFiles(params ?? {});
164
+ let body;
165
+ if (files.size > 0) {
166
+ body = new FormData();
167
+ body.append(BODY_PART_NAME, JSON.stringify(paramsWithoutFiles, (_, value) => value === undefined ? null : value));
168
+ for (const [path, file] of files) {
169
+ body.append(path, file);
170
+ }
171
+ } else {
172
+ headers["Content-Type"] = "application/json";
173
+ if (params) {
174
+ body = JSON.stringify(params, (_, value) => value === undefined ? null : value);
175
+ }
176
+ }
177
+ const request = new Request(`${this.prefix}/${endpoint}/${method}`, {
178
+ body,
179
+ headers,
180
+ method: "POST"
181
+ });
182
+ const initialContext = {
183
+ endpoint,
184
+ method,
185
+ params,
186
+ request
187
+ };
188
+ async function responseHandlerMiddleware(context, next) {
189
+ const response = await next(context);
190
+ await assertResponseIsOk(response);
191
+ const text = await response.text();
192
+ return JSON.parse(text, (_, value) => value === null ? undefined : value);
193
+ }
194
+ async function fetchNext(context) {
195
+ const connectionState = init?.mute ? undefined : $wnd.Vaadin?.connectionState;
196
+ connectionState?.loadingStarted();
197
+ try {
198
+ const response = await fetch(context.request, { signal: init?.signal });
199
+ connectionState?.loadingFinished();
200
+ return response;
201
+ } catch (error) {
202
+ if (error instanceof Error && error.name === "AbortError") {
203
+ connectionState?.loadingFinished();
204
+ } else {
205
+ connectionState?.loadingFailed();
206
+ }
207
+ throw error;
208
+ }
209
+ }
210
+ const middlewares = [responseHandlerMiddleware, ...this.middlewares];
211
+ const chain = middlewares.reduceRight(
212
+ (next, middleware) => async (context) => {
213
+ if (typeof middleware === "function") {
214
+ return middleware(context, next);
215
+ }
216
+ return middleware.invoke(context, next);
217
+ },
218
+ // Initialize reduceRight the accumulator with `fetchNext`
219
+ fetchNext
220
+ );
221
+ return chain(initialContext);
222
+ }
223
+ /**
224
+ * Subscribes to the given method defined using the endpoint and method
225
+ * parameters with the parameters given as params. The method must return a
226
+ * compatible type such as a Flux.
227
+ * Returns a subscription that is used to fetch values as they become available.
228
+ *
229
+ * @param endpoint - Endpoint name.
230
+ * @param method - Method name to call in the endpoint class.
231
+ * @param params - Optional parameters to pass to the method.
232
+ * @returns A subscription used to handles values as they become available.
233
+ */
234
+ subscribe(endpoint, method, params) {
235
+ return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);
236
+ }
237
+ }
238
+ //# sourceMappingURL=./Connect.js.map
package/Connect.js.map CHANGED
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["src/Connect.ts"],
4
- "sourcesContent": ["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport { ConnectionIndicator, ConnectionState } from '@vaadin/common-frontend';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n EndpointError,\n EndpointResponseError,\n EndpointValidationError,\n ForbiddenResponseError,\n UnauthorizedResponseError,\n type ValidationErrorData,\n} from './EndpointErrors.js';\nimport {\n type ActionOnLostSubscription,\n FluxConnection,\n type FluxSubscriptionStateChangeEvent,\n} from './FluxConnection.js';\nimport type { VaadinGlobal } from './types.js';\n\nconst $wnd = globalThis as VaadinGlobal;\n\n$wnd.Vaadin ??= {};\n$wnd.Vaadin.registrations ??= [];\n$wnd.Vaadin.registrations.push({\n is: 'endpoint',\n});\n\nexport type MaybePromise<T> = Promise<T> | T;\n\n/**\n * Represents the connection to and endpoint returning a subscription rather than a value.\n */\nexport interface Subscription<T> {\n /** Cancels the subscription. No values are made available after calling this. */\n cancel(): void;\n\n /*\n * Binds to the given context (element) so that when the context is deactivated (element detached), the subscription is closed.\n */\n context(context: ReactiveControllerHost): Subscription<T>;\n\n /** Called when the subscription has completed. No values are made available after calling this. */\n onComplete(callback: () => void): Subscription<T>;\n\n /** Called when an exception occured in the subscription. */\n onError(callback: (message: string) => void): Subscription<T>;\n\n /** Called when a new value is available. */\n onNext(callback: (value: T) => void): Subscription<T>;\n\n /** Called when the subscription state changes. */\n onConnectionStateChange(callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<T>;\n\n /**\n * Called when the connection is restored, but there's no longer a valid subscription. If the callback returns\n * `ActionOnLostSubscription.RESUBSCRIBE`, the subscription will be re-established by connecting to the same\n * server method again. If the callback returns `ActionOnLostSubscription.REMOVE`, the subscription will be\n * forgotten. This is also the default behavior if the callback is not set or if it returns `undefined`.\n */\n onSubscriptionLost(callback: () => ActionOnLostSubscription | void): Subscription<T>;\n}\n\ninterface ConnectExceptionData {\n detail?: any;\n message: string;\n type: string;\n validationErrorData?: ValidationErrorData[];\n}\n\n/**\n * Throws a TypeError if the response is not 200 OK.\n * @param response - The response to assert.\n */\nconst assertResponseIsOk = async (response: Response): Promise<void> => {\n if (!response.ok) {\n const errorText = await response.text();\n let errorJson: ConnectExceptionData | null;\n try {\n errorJson = JSON.parse(errorText);\n } catch (ignored) {\n // not a json\n errorJson = null;\n }\n\n const message =\n errorJson?.message ??\n (errorText.length > 0\n ? errorText\n : `expected \"200 OK\" response, but got ${response.status} ${response.statusText}`);\n const type = errorJson?.type;\n\n if (errorJson?.validationErrorData) {\n throw new EndpointValidationError(message, errorJson.validationErrorData, type);\n }\n\n if (type) {\n throw new EndpointError(message, type, errorJson?.detail);\n }\n\n switch (response.status) {\n case 401:\n throw new UnauthorizedResponseError(message, response);\n case 403:\n throw new ForbiddenResponseError(message, response);\n default:\n throw new EndpointResponseError(message, response);\n }\n }\n};\n\n/**\n * The `ConnectClient` constructor options.\n */\nexport interface ConnectClientOptions {\n /**\n * The `middlewares` property value.\n */\n middlewares?: Middleware[];\n /**\n * The `prefix` property value.\n */\n prefix?: string;\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions?: Partial<Atmosphere.Request>;\n}\n\nexport interface EndpointCallMetaInfo {\n /**\n * The endpoint name.\n */\n endpoint: string;\n\n /**\n * The method name to call on in the endpoint class.\n */\n method: string;\n\n /**\n * Optional object with method call arguments.\n */\n params?: Record<string, unknown>;\n}\n\n/**\n * An object with the call arguments and the related Request instance.\n * See also {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface MiddlewareContext extends EndpointCallMetaInfo {\n /**\n * The Fetch API Request object reflecting the other properties.\n */\n request: Request;\n}\n\n/**\n * An async middleware callback that invokes the next middleware in the chain\n * or makes the actual request.\n * @param context - The information about the call and request\n */\nexport type MiddlewareNext = (context: MiddlewareContext) => MaybePromise<Response>;\n\n/**\n * An interface that allows defining a middleware as a class.\n */\nexport interface MiddlewareClass {\n /**\n * @param context - The information about the call and request\n * @param next - Invokes the next in the call chain\n */\n invoke(context: MiddlewareContext, next: MiddlewareNext): MaybePromise<Response>;\n}\n\n/**\n * An async callback function that can intercept the request and response\n * of a call.\n */\nexport type MiddlewareFunction = (context: MiddlewareContext, next: MiddlewareNext) => MaybePromise<Response>;\n\n/**\n * An async callback that can intercept the request and response\n * of a call, could be either a function or a class.\n */\nexport type Middleware = MiddlewareClass | MiddlewareFunction;\n\nfunction isFlowLoaded(): boolean {\n return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;\n}\n\n/**\n * A list of parameters supported by {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface EndpointRequestInit {\n /**\n * An AbortSignal to set request's signal.\n */\n signal?: AbortSignal | null;\n}\n\n/**\n * A low-level network calling utility. It stores\n * a prefix and facilitates remote calls to endpoint class methods\n * on the Hilla backend.\n *\n * Example usage:\n *\n * ```js\n * const client = new ConnectClient();\n * const responseData = await client.call('MyEndpoint', 'myMethod');\n * ```\n *\n * ### Prefix\n *\n * The client supports an `prefix` constructor option:\n * ```js\n * const client = new ConnectClient({prefix: '/my-connect-prefix'});\n * ```\n *\n * The default prefix is '/connect'.\n *\n */\nexport class ConnectClient {\n /**\n * The array of middlewares that are invoked during a call.\n */\n middlewares: Middleware[] = [];\n /**\n * The Hilla endpoint prefix\n */\n prefix = '/connect';\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions: Partial<Atmosphere.Request> = {};\n\n #fluxConnection?: FluxConnection;\n\n /**\n * @param options - Constructor options.\n */\n constructor(options: ConnectClientOptions = {}) {\n if (options.prefix) {\n this.prefix = options.prefix;\n }\n\n if (options.middlewares) {\n this.middlewares = options.middlewares;\n }\n\n if (options.atmosphereOptions) {\n this.atmosphereOptions = options.atmosphereOptions;\n }\n\n // add connection indicator to DOM\n ConnectionIndicator.create();\n\n // Listen to browser online/offline events and update the loading indicator accordingly.\n // Note: if Flow.ts is loaded, it instead handles the state transitions.\n addEventListener('online', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;\n }\n });\n }\n\n /**\n * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint\n * methods.\n */\n get fluxConnection(): FluxConnection {\n if (!this.#fluxConnection) {\n this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);\n }\n return this.#fluxConnection;\n }\n\n /**\n * Calls the given endpoint method defined using the endpoint and method\n * parameters with the parameters given as params.\n * Asynchronously returns the parsed JSON response data.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @param init - Optional parameters for the request\n * @returns Decoded JSON response data.\n */\n async call(\n endpoint: string,\n method: string,\n params?: Record<string, unknown>,\n init?: EndpointRequestInit,\n ): Promise<any> {\n if (arguments.length < 2) {\n throw new TypeError(`2 arguments required, but got only ${arguments.length}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n ...csrfHeaders,\n };\n\n const request = new Request(`${this.prefix}/${endpoint}/${method}`, {\n body:\n params !== undefined ? JSON.stringify(params, (_, value) => (value === undefined ? null : value)) : undefined,\n headers,\n method: 'POST',\n });\n\n // The middleware `context`, includes the call arguments and the request\n // constructed from them\n const initialContext: MiddlewareContext = {\n endpoint,\n method,\n params,\n request,\n };\n\n // The internal middleware to assert and parse the response. The internal\n // response handling should come last after the other middlewares are done\n // with processing the response. That is why this middleware is first\n // in the final middlewares array.\n async function responseHandlerMiddleware(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const response = await next(context);\n await assertResponseIsOk(response);\n const text = await response.text();\n return JSON.parse(text, (_, value: any) => (value === null ? undefined : value));\n }\n\n // The actual fetch call itself is expressed as a middleware\n // chain item for our convenience. Always having an ending of the chain\n // this way makes the folding down below more concise.\n async function fetchNext(context: MiddlewareContext) {\n $wnd.Vaadin?.connectionState?.loadingStarted();\n try {\n const response = await fetch(context.request, { signal: init?.signal });\n $wnd.Vaadin?.connectionState?.loadingFinished();\n return response;\n } catch (error: unknown) {\n // don't bother about connections aborted by purpose\n if (error instanceof Error && error.name === 'AbortError') {\n $wnd.Vaadin?.connectionState?.loadingFinished();\n } else {\n $wnd.Vaadin?.connectionState?.loadingFailed();\n }\n return Promise.reject(error);\n }\n }\n\n // Assemble the final middlewares array from internal\n // and external middlewares\n const middlewares = [responseHandlerMiddleware as Middleware, ...this.middlewares];\n\n // Fold the final middlewares array into a single function\n const chain = middlewares.reduceRight(\n (next: MiddlewareNext, middleware) =>\n // Compose and return the new chain step, that takes the context and\n // invokes the current middleware with the context and the further chain\n // as the next argument\n async (context) => {\n if (typeof middleware === 'function') {\n return middleware(context, next);\n }\n return middleware.invoke(context, next);\n },\n // Initialize reduceRight the accumulator with `fetchNext`\n fetchNext,\n );\n\n // Invoke all the folded async middlewares and return\n return chain(initialContext);\n }\n\n /**\n * Subscribes to the given method defined using the endpoint and method\n * parameters with the parameters given as params. The method must return a\n * compatible type such as a Flux.\n * Returns a subscription that is used to fetch values as they become available.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @returns A subscription used to handles values as they become available.\n */\n subscribe(endpoint: string, method: string, params?: any): Subscription<any> {\n return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);\n }\n}\n"],
5
- "mappings": "AACA,SAAS,qBAAqB,uBAAuB;AACrD,SAAS,6CAA6C;AACtD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EAEE;AAAA,OAEK;AAGP,MAAM,OAAO;AAEb,KAAK,WAAW,CAAC;AACjB,KAAK,OAAO,kBAAkB,CAAC;AAC/B,KAAK,OAAO,cAAc,KAAK;AAAA,EAC7B,IAAI;AACN,CAAC;AAgDD,MAAM,qBAAqB,OAAO,aAAsC;AACtE,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,YAAY,MAAM,SAAS,KAAK;AACtC,QAAI;AACJ,QAAI;AACF,kBAAY,KAAK,MAAM,SAAS;AAAA,IAClC,SAAS,SAAS;AAEhB,kBAAY;AAAA,IACd;AAEA,UAAM,UACJ,WAAW,YACV,UAAU,SAAS,IAChB,YACA,uCAAuC,SAAS,MAAM,IAAI,SAAS,UAAU;AACnF,UAAM,OAAO,WAAW;AAExB,QAAI,WAAW,qBAAqB;AAClC,YAAM,IAAI,wBAAwB,SAAS,UAAU,qBAAqB,IAAI;AAAA,IAChF;AAEA,QAAI,MAAM;AACR,YAAM,IAA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ceptionData | null","obj: Record<string, unknown>","prop: unknown","path: string","options: ConnectClientOptions","#fluxConnection","endpoint: string","method: string","params?: Record<string, unknown>","init?: EndpointRequestInit","headers: Record<string, string>","initialContext: MiddlewareContext","context: MiddlewareContext","next: MiddlewareNext","value: any","error: unknown","params?: any"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/Connect.ts"],"sourcesContent":["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport { ConnectionIndicator, ConnectionState } from '@vaadin/common-frontend';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n EndpointError,\n EndpointResponseError,\n EndpointValidationError,\n ForbiddenResponseError,\n UnauthorizedResponseError,\n type ValidationErrorData,\n} from './EndpointErrors.js';\nimport {\n type ActionOnLostSubscription,\n FluxConnection,\n type FluxSubscriptionStateChangeEvent,\n} from './FluxConnection.js';\nimport type { VaadinGlobal } from './types.js';\n\nconst $wnd = globalThis as VaadinGlobal;\n\n$wnd.Vaadin ??= {};\n$wnd.Vaadin.registrations ??= [];\n$wnd.Vaadin.registrations.push({\n is: 'endpoint',\n});\n\nexport const BODY_PART_NAME = 'hilla_body_part';\n\nexport type MaybePromise<T> = Promise<T> | T;\n\n/**\n * Represents the connection to and endpoint returning a subscription rather than a value.\n */\nexport interface Subscription<T> {\n /** Cancels the subscription. No values are made available after calling this. */\n cancel(): void;\n\n /*\n * Binds to the given context (element) so that when the context is deactivated (element detached), the subscription is closed.\n */\n context(context: ReactiveControllerHost): Subscription<T>;\n\n /** Called when the subscription has completed. No values are made available after calling this. */\n onComplete(callback: () => void): Subscription<T>;\n\n /** Called when an exception occured in the subscription. */\n onError(callback: (message: string) => void): Subscription<T>;\n\n /** Called when a new value is available. */\n onNext(callback: (value: T) => void): Subscription<T>;\n\n /** Called when the subscription state changes. */\n onConnectionStateChange(callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<T>;\n\n /**\n * Called when the connection is restored, but there's no longer a valid subscription. If the callback returns\n * `ActionOnLostSubscription.RESUBSCRIBE`, the subscription will be re-established by connecting to the same\n * server method again. If the callback returns `ActionOnLostSubscription.REMOVE`, the subscription will be\n * forgotten. This is also the default behavior if the callback is not set or if it returns `undefined`.\n */\n onSubscriptionLost(callback: () => ActionOnLostSubscription | void): Subscription<T>;\n}\n\ninterface ConnectExceptionData {\n detail?: any;\n message: string;\n type: string;\n validationErrorData?: ValidationErrorData[];\n}\n\n/**\n * Throws a TypeError if the response is not 200 OK.\n * @param response - The response to assert.\n */\nconst assertResponseIsOk = async (response: Response): Promise<void> => {\n if (!response.ok) {\n const errorText = await response.text();\n let errorJson: ConnectExceptionData | null;\n try {\n errorJson = JSON.parse(errorText);\n } catch {\n // not a json\n errorJson = null;\n }\n\n const message =\n errorJson?.message ??\n (errorText.length > 0\n ? errorText\n : `expected \"200 OK\" response, but got ${response.status} ${response.statusText}`);\n const type = errorJson?.type;\n\n if (errorJson?.validationErrorData) {\n throw new EndpointValidationError(message, errorJson.validationErrorData, type);\n }\n\n if (type) {\n throw new EndpointError(message, type, errorJson?.detail);\n }\n\n switch (response.status) {\n case 401:\n throw new UnauthorizedResponseError(message, response);\n case 403:\n throw new ForbiddenResponseError(message, response);\n default:\n throw new EndpointResponseError(message, response);\n }\n }\n};\n\n/**\n * The `ConnectClient` constructor options.\n */\nexport interface ConnectClientOptions {\n /**\n * The `middlewares` property value.\n */\n middlewares?: Middleware[];\n /**\n * The `prefix` property value.\n */\n prefix?: string;\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions?: Partial<Atmosphere.Request>;\n}\n\nexport interface EndpointCallMetaInfo {\n /**\n * The endpoint name.\n */\n endpoint: string;\n\n /**\n * The method name to call on in the endpoint class.\n */\n method: string;\n\n /**\n * Optional object with method call arguments.\n */\n params?: Record<string, unknown>;\n}\n\n/**\n * An object with the call arguments and the related Request instance.\n * See also {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface MiddlewareContext extends EndpointCallMetaInfo {\n /**\n * The Fetch API Request object reflecting the other properties.\n */\n request: Request;\n}\n\n/**\n * An async middleware callback that invokes the next middleware in the chain\n * or makes the actual request.\n * @param context - The information about the call and request\n */\nexport type MiddlewareNext = (context: MiddlewareContext) => MaybePromise<Response>;\n\n/**\n * An interface that allows defining a middleware as a class.\n */\nexport interface MiddlewareClass {\n /**\n * @param context - The information about the call and request\n * @param next - Invokes the next in the call chain\n */\n invoke(context: MiddlewareContext, next: MiddlewareNext): MaybePromise<Response>;\n}\n\n/**\n * An async callback function that can intercept the request and response\n * of a call.\n */\nexport type MiddlewareFunction = (context: MiddlewareContext, next: MiddlewareNext) => MaybePromise<Response>;\n\n/**\n * An async callback that can intercept the request and response\n * of a call, could be either a function or a class.\n */\nexport type Middleware = MiddlewareClass | MiddlewareFunction;\n\nfunction isFlowLoaded(): boolean {\n return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;\n}\n\n/**\n * Extracts file objects from the object that is used to build the request body.\n *\n * @param obj - The object to extract files from.\n * @returns A tuple with the object without files and a map of files.\n */\nfunction extractFiles(obj: Record<string, unknown>): [Record<string, unknown>, Map<string, File>] {\n const fileMap = new Map<string, File>();\n\n function recursiveExtract(prop: unknown, path: string): unknown {\n if (prop !== null && typeof prop === 'object') {\n if (prop instanceof File) {\n fileMap.set(path, prop);\n return null;\n }\n if (Array.isArray(prop)) {\n return prop.map((item, index) => recursiveExtract(item, `${path}/${index}`));\n }\n return Object.entries(prop).reduce<Record<string, unknown>>((acc, [key, value]) => {\n const newPath = `${path}/${key}`;\n if (value instanceof File) {\n fileMap.set(newPath, value);\n } else {\n acc[key] = recursiveExtract(value, newPath);\n }\n return acc;\n }, {});\n }\n return prop;\n }\n\n return [recursiveExtract(obj, '') as Record<string, unknown>, fileMap];\n}\n\n/**\n * A list of parameters supported by {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface EndpointRequestInit {\n /**\n * An AbortSignal to set request's signal.\n */\n signal?: AbortSignal | null;\n /**\n * If set to true, the connection state will not be updated during the request.\n */\n mute?: boolean;\n}\n\n/**\n * A low-level network calling utility. It stores\n * a prefix and facilitates remote calls to endpoint class methods\n * on the Hilla backend.\n *\n * Example usage:\n *\n * ```js\n * const client = new ConnectClient();\n * const responseData = await client.call('MyEndpoint', 'myMethod');\n * ```\n *\n * ### Prefix\n *\n * The client supports an `prefix` constructor option:\n * ```js\n * const client = new ConnectClient({prefix: '/my-connect-prefix'});\n * ```\n *\n * The default prefix is '/connect'.\n *\n */\nexport class ConnectClient {\n /**\n * The array of middlewares that are invoked during a call.\n */\n middlewares: Middleware[] = [];\n /**\n * The Hilla endpoint prefix\n */\n prefix = '/connect';\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions: Partial<Atmosphere.Request> = {};\n\n #fluxConnection?: FluxConnection;\n\n /**\n * @param options - Constructor options.\n */\n constructor(options: ConnectClientOptions = {}) {\n if (options.prefix) {\n this.prefix = options.prefix;\n }\n\n if (options.middlewares) {\n this.middlewares = options.middlewares;\n }\n\n if (options.atmosphereOptions) {\n this.atmosphereOptions = options.atmosphereOptions;\n }\n\n // add connection indicator to DOM\n ConnectionIndicator.create();\n\n // Listen to browser online/offline events and update the loading indicator accordingly.\n // Note: if Flow.ts is loaded, it instead handles the state transitions.\n addEventListener('online', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;\n }\n });\n }\n\n /**\n * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint\n * methods.\n */\n get fluxConnection(): FluxConnection {\n if (!this.#fluxConnection) {\n this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);\n }\n return this.#fluxConnection;\n }\n\n /**\n * Calls the given endpoint method defined using the endpoint and method\n * parameters with the parameters given as params.\n * Asynchronously returns the parsed JSON response data.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @param init - Optional parameters for the request\n * @returns Decoded JSON response data.\n */\n async call(\n endpoint: string,\n method: string,\n params?: Record<string, unknown>,\n init?: EndpointRequestInit,\n ): Promise<any> {\n if (arguments.length < 2) {\n throw new TypeError(`2 arguments required, but got only ${arguments.length}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...csrfHeaders,\n };\n\n const [paramsWithoutFiles, files] = extractFiles(params ?? {});\n let body;\n\n if (files.size > 0) {\n // in this case params is not undefined, otherwise there would be no files\n body = new FormData();\n body.append(\n BODY_PART_NAME,\n JSON.stringify(paramsWithoutFiles, (_, value) => (value === undefined ? null : value)),\n );\n\n for (const [path, file] of files) {\n body.append(path, file);\n }\n } else {\n headers['Content-Type'] = 'application/json';\n if (params) {\n body = JSON.stringify(params, (_, value) => (value === undefined ? null : value));\n }\n }\n\n const request = new Request(`${this.prefix}/${endpoint}/${method}`, {\n body, // automatically sets Content-Type header\n headers,\n method: 'POST',\n });\n\n // The middleware `context`, includes the call arguments and the request\n // constructed from them\n const initialContext: MiddlewareContext = {\n endpoint,\n method,\n params,\n request,\n };\n\n // The internal middleware to assert and parse the response. The internal\n // response handling should come last after the other middlewares are done\n // with processing the response. That is why this middleware is first\n // in the final middlewares array.\n async function responseHandlerMiddleware(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const response = await next(context);\n await assertResponseIsOk(response);\n const text = await response.text();\n return JSON.parse(text, (_, value: any) => (value === null ? undefined : value));\n }\n\n // The actual fetch call itself is expressed as a middleware\n // chain item for our convenience. Always having an ending of the chain\n // this way makes the folding down below more concise.\n async function fetchNext(context: MiddlewareContext) {\n // if the request is not \"muted\", notify the connection state about changes\n const connectionState = init?.mute ? undefined : $wnd.Vaadin?.connectionState;\n connectionState?.loadingStarted();\n try {\n const response = await fetch(context.request, { signal: init?.signal });\n connectionState?.loadingFinished();\n return response;\n } catch (error: unknown) {\n // don't bother about connections aborted by purpose\n if (error instanceof Error && error.name === 'AbortError') {\n connectionState?.loadingFinished();\n } else {\n connectionState?.loadingFailed();\n }\n throw error;\n }\n }\n\n // Assemble the final middlewares array from internal\n // and external middlewares\n const middlewares = [responseHandlerMiddleware as Middleware, ...this.middlewares];\n\n // Fold the final middlewares array into a single function\n const chain = middlewares.reduceRight(\n (next: MiddlewareNext, middleware) =>\n // Compose and return the new chain step, that takes the context and\n // invokes the current middleware with the context and the further chain\n // as the next argument\n async (context) => {\n if (typeof middleware === 'function') {\n return middleware(context, next);\n }\n return middleware.invoke(context, next);\n },\n // Initialize reduceRight the accumulator with `fetchNext`\n fetchNext,\n );\n\n // Invoke all the folded async middlewares and return\n return chain(initialContext);\n }\n\n /**\n * Subscribes to the given method defined using the endpoint and method\n * parameters with the parameters given as params. The method must return a\n * compatible type such as a Flux.\n * Returns a subscription that is used to fetch values as they become available.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @returns A subscription used to handles values as they become available.\n */\n subscribe(endpoint: string, method: string, params?: any): Subscription<any> {\n return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);\n }\n}\n"],"version":3}
@@ -1,4 +1,4 @@
1
+ import Cookies from "js-cookie";
1
2
  export declare function calculatePath({ pathname }: URL): string;
2
- declare const CookieManager: Cookies.CookiesStatic;
3
+ declare const CookieManager: typeof Cookies;
3
4
  export default CookieManager;
4
- //# sourceMappingURL=CookieManager.d.ts.map
package/CookieManager.js CHANGED
@@ -1,14 +1,7 @@
1
1
  import Cookies from "js-cookie";
2
- function calculatePath({ pathname }) {
3
- return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
2
+ export function calculatePath({ pathname }) {
3
+ return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
4
4
  }
5
- const CookieManager = Cookies.withAttributes({
6
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
7
- path: calculatePath(new URL(globalThis.document?.baseURI ?? "/"))
8
- });
9
- var CookieManager_default = CookieManager;
10
- export {
11
- calculatePath,
12
- CookieManager_default as default
13
- };
14
- //# sourceMappingURL=CookieManager.js.map
5
+ const CookieManager = Cookies.withAttributes({ path: calculatePath(new URL(globalThis.document?.baseURI ?? "/")) });
6
+ export default CookieManager;
7
+ //# sourceMappingURL=./CookieManager.js.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["src/CookieManager.ts"],
4
- "sourcesContent": ["import Cookies from 'js-cookie';\n\nexport function calculatePath({ pathname }: URL): string {\n return pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;\n}\n\nconst CookieManager: Cookies.CookiesStatic = Cookies.withAttributes({\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n path: calculatePath(new URL(globalThis.document?.baseURI ?? '/')),\n});\n\nexport default CookieManager;\n"],
5
- "mappings": "AAAA,OAAO,aAAa;AAEb,SAAS,cAAc,EAAE,SAAS,GAAgB;AACvD,SAAO,SAAS,SAAS,KAAK,SAAS,SAAS,GAAG,IAAI,SAAS,MAAM,GAAG,EAAE,IAAI;AACjF;AAEA,MAAM,gBAAuC,QAAQ,eAAe;AAAA;AAAA,EAElE,MAAM,cAAc,IAAI,IAAI,WAAW,UAAU,WAAW,GAAG,CAAC;AAClE,CAAC;AAED,IAAO,wBAAQ;",
6
- "names": []
7
- }
1
+ {"mappings":"AAAA,OAAO,wBAAyB;AAEhC,OAAO,SAAS,cAAc,EAAE,UAAe,EAAU;AACvD,QAAO,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GAAG,SAAS,MAAM,IAAI,EAAE,GAAG;AAChF;AAED,MAAMA,gBAAgC,QAAQ,eAAe,EAE3D,MAAM,cAAc,IAAI,IAAI,WAAW,UAAU,WAAW,KAAK,CAClE,EAAC;AAEF,eAAe","names":["CookieManager: typeof Cookies"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/CookieManager.ts"],"sourcesContent":["import Cookies from 'js-cookie';\n\nexport function calculatePath({ pathname }: URL): string {\n return pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;\n}\n\nconst CookieManager: typeof Cookies = Cookies.withAttributes({\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n path: calculatePath(new URL(globalThis.document?.baseURI ?? '/')),\n});\n\nexport default CookieManager;\n"],"version":3}
package/CsrfUtils.d.ts CHANGED
@@ -1,13 +1 @@
1
- /** @internal */
2
- export declare const VAADIN_CSRF_HEADER = "X-CSRF-Token";
3
- /** @internal */
4
- export declare const VAADIN_CSRF_COOKIE_NAME = "csrfToken";
5
- /** @internal */
6
- export declare const SPRING_CSRF_COOKIE_NAME = "XSRF-TOKEN";
7
- /** @internal */
8
- export declare function getSpringCsrfInfo(doc: Document): Record<string, string>;
9
- /** @internal */
10
- export declare function getSpringCsrfTokenHeadersForAuthRequest(doc: Document): Record<string, string>;
11
- /** @internal */
12
- export declare function getCsrfTokenHeadersForEndpointRequest(doc: Document): Record<string, string>;
13
- //# sourceMappingURL=CsrfUtils.d.ts.map
1
+ export {};