@vaadin/hilla-frontend 24.8.0-beta1 → 24.8.0-beta3
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 +15 -19
- package/Connect.js.map +1 -1
- package/CsrfInfoSource.js +3 -4
- package/CsrfInfoSource.js.map +1 -1
- package/FluxConnection.js +69 -71
- package/FluxConnection.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +7 -2
- package/utils.d.ts +1 -0
- package/utils.js +2 -0
- package/utils.js.map +1 -0
package/Connect.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import csrfInfoSource from "./CsrfInfoSource.js";
|
|
2
2
|
import { EndpointError, EndpointResponseError, EndpointValidationError, ForbiddenResponseError, UnauthorizedResponseError } from "./EndpointErrors.js";
|
|
3
3
|
import { FluxConnection } from "./FluxConnection.js";
|
|
4
|
-
|
|
4
|
+
import { VAADIN_BROWSER_ENVIRONMENT } from "./utils.js";
|
|
5
|
+
const commonFrontendModulePromise = VAADIN_BROWSER_ENVIRONMENT ? import("@vaadin/common-frontend") : undefined;
|
|
5
6
|
const $wnd = globalThis;
|
|
6
7
|
$wnd.Vaadin ??= {};
|
|
7
8
|
$wnd.Vaadin.registrations ??= [];
|
|
@@ -119,24 +120,19 @@ export class ConnectClient {
|
|
|
119
120
|
if (options.atmosphereOptions) {
|
|
120
121
|
this.atmosphereOptions = options.atmosphereOptions;
|
|
121
122
|
}
|
|
122
|
-
this.#ready = commonFrontendModulePromise.then((commonFrontendModule) => {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
$wnd.Vaadin.connectionState.state = commonFrontendModule.ConnectionState.CONNECTION_LOST;
|
|
136
|
-
}
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
});
|
|
123
|
+
this.#ready = commonFrontendModulePromise ? commonFrontendModulePromise.then((commonFrontendModule) => {
|
|
124
|
+
commonFrontendModule.ConnectionIndicator.create();
|
|
125
|
+
addEventListener("online", () => {
|
|
126
|
+
if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {
|
|
127
|
+
$wnd.Vaadin.connectionState.state = commonFrontendModule.ConnectionState.CONNECTED;
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
addEventListener("offline", () => {
|
|
131
|
+
if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {
|
|
132
|
+
$wnd.Vaadin.connectionState.state = commonFrontendModule.ConnectionState.CONNECTION_LOST;
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
}) : Promise.resolve();
|
|
140
136
|
}
|
|
141
137
|
/**
|
|
142
138
|
* Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint
|
package/Connect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAEA,OAAO,yCAA0C;AACjD,SACE,eACA,uBACA,yBACA,wBACA,sDAE2B;AAC7B,SAEE,2CAE2B;AAI7B,MAAMA,8BAAgF,WAAW,WAC7F,OAAO,6BACP,QAAQ,QAAQ,UAAU;AAE9B,MAAM,OAAO;AAEb,KAAK,WAAW,CAAE;AAClB,KAAK,OAAO,kBAAkB,CAAE;AAChC,KAAK,OAAO,cAAc,KAAK,EAC7B,IAAI,WACL,EAAC;AAEF,OAAO,MAAM,iBAAiB;;;;;AAgD9B,MAAM,qBAAqB,OAAOC,aAAsC;AACtE,MAAK,SAAS,IAAI;EAChB,MAAM,YAAY,MAAM,SAAS,MAAM;EACvC,IAAIC;AACJ,MAAI;AACF,eAAY,KAAK,MAAM,UAAU;EAClC,QAAO;AAEN,eAAY;EACb;EAED,MAAM,UACJ,WAAW,YACV,UAAU,SAAS,IAChB,aACC,sCAAsC,SAAS,OAAO,GAAG,SAAS,WAAW;EACpF,MAAM,OAA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;;CAaD,UAAUP,UAAkBC,QAAgBS,QAAiC;AAC3E,SAAO,KAAK,eAAe,UAAU,UAAU,QAAQ,SAAS,OAAO,OAAO,OAAO,GAAG,CAAE,EAAC;CAC5F;;;;CAKD,IAAI,QAAuB;AACzB,SAAO,KAAKd;CACb;AACF","names":["commonFrontendModulePromise: Promise<typeof CommonFrontendModule | undefined>","response: Response","errorJson: ConnectExceptionData | null","obj: Record<string, unknown>","prop: unknown","path: string","#ready","options: ConnectClientOptions","commonFrontendModule?: typeof CommonFrontendModule","#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 type * as CommonFrontendModule from '@vaadin/common-frontend';\nimport csrfInfoSource from './CsrfInfoSource.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\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nconst commonFrontendModulePromise: Promise<typeof CommonFrontendModule | undefined> = globalThis.document\n ? import('@vaadin/common-frontend')\n : Promise.resolve(undefined);\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 readonly #ready: Promise<void>;\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 this.#ready = commonFrontendModulePromise.then((commonFrontendModule?: typeof CommonFrontendModule) => {\n if (!commonFrontendModule) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (globalThis.document) {\n // add connection indicator to DOM\n commonFrontendModule.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 = commonFrontendModule.ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = commonFrontendModule.ConnectionState.CONNECTION_LOST;\n }\n });\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 const csrfInfo = await csrfInfoSource.get();\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...Object.fromEntries(csrfInfo.headerEntries),\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 /**\n * Promise that resolves when the instance is initialized.\n */\n get ready(): Promise<void> {\n return this.#ready;\n }\n}\n"],"version":3}
|
|
1
|
+
{"mappings":"AACA,OAAO,yCAA0C;AACjD,SACE,eACA,uBACA,yBACA,wBACA,sDAE2B;AAC7B,SAEE,2CAE2B;AAE7B,SAAS,8CAA+C;AAGxD,MAAM,8BAA8B,6BAA6B,OAAO,6BAA6B;AAErG,MAAM,OAAO;AAEb,KAAK,WAAW,CAAE;AAClB,KAAK,OAAO,kBAAkB,CAAE;AAChC,KAAK,OAAO,cAAc,KAAK,EAC7B,IAAI,WACL,EAAC;AAEF,OAAO,MAAM,iBAAiB;;;;;AAgD9B,MAAM,qBAAqB,OAAOA,aAAsC;AACtE,MAAK,SAAS,IAAI;EAChB,MAAM,YAAY,MAAM,SAAS,MAAM;EACvC,IAAIC;AACJ,MAAI;AACF,eAAY,KAAK,MAAM,UAAU;EAClC,QAAO;AAEN,eAAY;EACb;EAED,MAAM,UACJ,WAAW,YACV,UAAU,SAAS,IAChB,aACC,sCAAsC,SAAS,OAAO,GAAG,SAAS,WAAW;EACpF,MAAM,OAAO,WAAW;AAExB,MAAI,WAAW,qBAAqB;AAClC,SAAM,IAAI,wBAAwB,SAAS,UAAU,qBAAqB;EAC3E;AAED,MAAI,MAAM;AACR,SAAM,IAAI,cAAc,SAAS,MAAM,WAAW;EACnD;AAED,UAAQ,SAAS,QAAjB;GACE,KAAK,IACH,OAAM,IAAI,0BAA0B,SAAS;GAC/C,KAAK,IACH,OAAM,IAAI,uBAAuB,SAAS;GAC5C,QACE,OAAM,IAAI,sBAAsB,SAAS;EAC5C;CACF;AACF;AA8ED,SAAS,eAAwB;AAC/B,QAAO,KAAK,QAA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4BC,MAAyC;GAC5G,MAAM,WAAW,MAAM,KAAK,QAAQ;AACpC,SAAM,mBAAmB,SAAS;GAClC,MAAM,OAAO,MAAM,SAAS,MAAM;AAClC,UAAO,KAAK,MAAM,MAAM,CAAC,GAAGC,UAAgB,UAAU,OAAO,YAAY,MAAO;EACjF;EAKD,eAAe,UAAUF,SAA4B;GAEnD,MAAM,kBAAkB,MAAM,OAAO,YAAY,KAAK,QAAQ;AAC9D,oBAAiB,gBAAgB;AACjC,OAAI;IACF,MAAM,WAAW,MAAM,MAAM,QAAQ,SAAS,EAAE,QAAQ,MAAM,OAAQ,EAAC;AACvE,qBAAiB,iBAAiB;AAClC,WAAO;GACR,SAAQG,OAAgB;AAEvB,QAAI,iBAAiB,SAAS,MAAM,SAAS,cAAc;AACzD,sBAAiB,iBAAiB;IACnC,OAAM;AACL,sBAAiB,eAAe;IACjC;AACD,UAAM;GACP;EACF;EAID,MAAM,cAAc,CAAC,2BAAyC,GAAG,KAAK,WAAY;EAGlF,MAAM,QAAQ,YAAY;GACxB,CAACF,MAAsB,eAIrB,OAAO,YAAY;AACjB,eAAW,eAAe,YAAY;AACpC,YAAO,WAAW,SAAS,KAAK;IACjC;AACD,WAAO,WAAW,OAAO,SAAS,KAAK;GACxC;;GAEH;CACD;AAGD,SAAO,MAAM,eAAe;CAC7B;;;;;;;;;;;;CAaD,UAAUP,UAAkBC,QAAgBS,QAAiC;AAC3E,SAAO,KAAK,eAAe,UAAU,UAAU,QAAQ,SAAS,OAAO,OAAO,OAAO,GAAG,CAAE,EAAC;CAC5F;;;;CAKD,IAAI,QAAuB;AACzB,SAAO,KAAKb;CACb;AACF","names":["response: Response","errorJson: ConnectExceptionData | null","obj: Record<string, unknown>","prop: unknown","path: string","#ready","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 csrfInfoSource from './CsrfInfoSource.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';\nimport { VAADIN_BROWSER_ENVIRONMENT } from './utils.js';\n\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nconst commonFrontendModulePromise = VAADIN_BROWSER_ENVIRONMENT ? import('@vaadin/common-frontend') : undefined;\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 readonly #ready: Promise<void>;\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 this.#ready = commonFrontendModulePromise\n ? commonFrontendModulePromise.then((commonFrontendModule) => {\n // add connection indicator to DOM\n commonFrontendModule.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 = commonFrontendModule.ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = commonFrontendModule.ConnectionState.CONNECTION_LOST;\n }\n });\n })\n : Promise.resolve();\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 const csrfInfo = await csrfInfoSource.get();\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...Object.fromEntries(csrfInfo.headerEntries),\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 /**\n * Promise that resolves when the instance is initialized.\n */\n get ready(): Promise<void> {\n return this.#ready;\n }\n}\n"],"version":3}
|
package/CsrfInfoSource.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import CookieManager from "./CookieManager.js";
|
|
2
2
|
export let CsrfInfoType = function(CsrfInfoType) {
|
|
3
3
|
CsrfInfoType["SPRING"] = "Spring";
|
|
4
4
|
CsrfInfoType["VAADIN"] = "Vaadin";
|
|
@@ -51,9 +51,8 @@ export function updateCsrfInfoMeta(csrfInfo, doc) {
|
|
|
51
51
|
}
|
|
52
52
|
/** @internal */
|
|
53
53
|
export async function extractCsrfInfoFromMeta(doc) {
|
|
54
|
-
const cookieManager = (await cookieManagerPromise).default;
|
|
55
54
|
const timestamp = Date.now();
|
|
56
|
-
const springCsrf =
|
|
55
|
+
const springCsrf = await Promise.resolve().then(() => CookieManager.get(SPRING_CSRF_COOKIE_NAME)) ?? extractContentFromMetaTag(doc, "_csrf");
|
|
57
56
|
if (springCsrf) {
|
|
58
57
|
const csrfHeader = extractContentFromMetaTag(doc, "_csrf_header");
|
|
59
58
|
const csrfParameter = extractContentFromMetaTag(doc, "_csrf_parameter");
|
|
@@ -64,7 +63,7 @@ export async function extractCsrfInfoFromMeta(doc) {
|
|
|
64
63
|
type: CsrfInfoType.SPRING
|
|
65
64
|
};
|
|
66
65
|
}
|
|
67
|
-
const vaadinCsrf =
|
|
66
|
+
const vaadinCsrf = CookieManager.get(VAADIN_CSRF_COOKIE_NAME) ?? "";
|
|
68
67
|
return {
|
|
69
68
|
type: CsrfInfoType.VAADIN,
|
|
70
69
|
headerEntries: [[VAADIN_CSRF_HEADER, vaadinCsrf]],
|
package/CsrfInfoSource.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAEA,MAAM,uBAAuB,WAAW,WAAW,OAAO,wBAAwB;AAIlF,OAAO,IAAK,sCAAL;AACL;AACA;;AACD;AAUD,SAAS,WAAWA,GAA2B;AAC7C,QAAO,MAAM,eAAe,MAAM,YAAY,mBAAmB,KAAK,qBAAqB,KAAK,eAAe;AAChH;;AAGD,OAAO,MAAM,qBAAqB;;AAElC,OAAO,MAAM,0BAA0B;;AAEvC,OAAO,MAAM,0BAA0B;AAEvC,SAAS,0BAA0BC,KAAeC,SAAqC;CACrF,MAAM,UAAU,IAAI,KAAK,eAAgC,aAAa,QAAQ,IAAI;CAClF,MAAM,QAAQ,SAAS;AACvB,KAAI,SAAS,MAAM,aAAa,KAAK,aAAa;AAChD,SAAO;CACR;AAED,QAAO;AACR;AAED,SAAS,cAAcD,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OAAO;AACZ,OAAK,MAAM;AACX,OAAKG,gBAAgB,KAAK,aAAa,CAAC,KAAK,CAACR,aAAuB;AACnE,QAAKK,uBAAuB,SAAS;AACrC,UAAO;EACR,EAAC;AACF,OAAK,KAAKI,sBAAsB;AAC9B,QAAK,KAAK,CACP,KAAK,CAACT,aAAuB;AAC5B,SAAKO,cAAc,SAAS;GAC7B,EAAC,CACD,MAAM,QAAQ,MAAM;EACxB;CACF;;;;;;CAOD,MAAgB,cAAiC;AAC/C,SAAO,IAAI,QAAkB,CAAC,YAAY;AACxC,QAAKE,uBAAuB;AAC5B,QAAKP,uBAAuB,YAAY,UAAU;EACnD;CACF;CAED,cAAcF,UAAoB;AAChC,OAAKC,gBAAgB,YAAY,SAAS;CAC3C;CAED,iBAAiBD,UAAoB;AACnC,MAAI,KAAKS,sBAAsB;AAC7B,QAAKA,qBAAqB,SAAS;AACnC,QAAKA,uBAAuB;EAC7B,OAAM;AACL,QAAKD,gBAAgB,QAAQ,QAAQ,SAAS;EAC/C;CACF;AACF;;AAGD,OAAO,MAAM,8BAA8B,qBAAqB;CAC9D,cAAc;AACZ,SAAO;AACP,aAAW,iBAAiB,YAAY,KAAK,MAAM,KAAK,KAAK,CAAC;AAC9D,aAAW,iBAAiB,YAAY,KAAK,KAAK,KAAK,KAAK,CAAC;CAC9D;CAED,MAAyB,cAAiC;AACxD,SAAO,wBAAwB,WAAW,SAAS;CACpD;AACF;;AAID,IAAIE;AAEJ,IAAI,WAAW,UAAU;AACvB,kBAAiB,IAAI;AACtB,OAAM;AACL,kBAAiB,IAAI;AACtB;AACD,eAAe","names":["o: unknown","doc: Document","metaTag: string","name: string","content: string","csrfInfo: CsrfInfo","#updateChannel","#requestUpdateChannel","#getBroadcastChannelName","e: MessageEvent","#lastUpdateTimestamp","#receiveCsrfInfo","#sendCsrfInfo","#valuePromise","#resolveInitialValue","csrfInfoSource: CsrfInfoSource"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/CsrfInfoSource.ts"],"sourcesContent":["/// <reference lib=\"webworker\" />\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nconst cookieManagerPromise = globalThis.document ? import('./CookieManager.js') : undefined;\n\n/** @internal */\nexport type NameValueEntry = readonly [name: string, value: string];\nexport enum CsrfInfoType {\n SPRING = 'Spring',\n VAADIN = 'Vaadin',\n}\n\n/** @internal */\nexport type CsrfInfo = {\n readonly headerEntries: readonly NameValueEntry[];\n readonly formDataEntries: readonly NameValueEntry[];\n readonly type: CsrfInfoType;\n readonly timestamp: number;\n};\n\nfunction isCsrfInfo(o: unknown): o is CsrfInfo {\n return o !== null && typeof o === 'object' && 'headerEntries' in o && 'formDataEntries' in o && 'timestamp' in o;\n}\n\n/** @internal */\nexport const VAADIN_CSRF_HEADER = 'X-CSRF-Token';\n/** @internal */\nexport const VAADIN_CSRF_COOKIE_NAME = 'csrfToken';\n/** @internal */\nexport const SPRING_CSRF_COOKIE_NAME = 'XSRF-TOKEN';\n\nfunction extractContentFromMetaTag(doc: Document, metaTag: string): string | undefined {\n const element = doc.head.querySelector<HTMLMetaElement>(`meta[name=\"${metaTag}\"]`);\n const value = element?.content;\n if (value && value.toLowerCase() !== 'undefined') {\n return value;\n }\n\n return undefined;\n}\n\nfunction updateMetaTag(doc: Document, name: string, content: string): void {\n const meta = doc.createElement('meta');\n meta.name = name;\n meta.content = content;\n const existing = doc.head.querySelector(`meta[name=\"${name}\"]`);\n if (existing) {\n existing.replaceWith(meta);\n } else {\n doc.head.appendChild(meta);\n }\n}\n\nexport function clearCsrfInfoMeta(doc: Document): void {\n Array.from(\n doc.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"], meta[name=\"_csrf_parameter\"]'),\n ).forEach((el) => el.remove());\n}\n\nexport function updateCsrfInfoMeta(csrfInfo: CsrfInfo, doc: Document): void {\n if (csrfInfo.type !== CsrfInfoType.SPRING) {\n return;\n }\n\n if (csrfInfo.headerEntries.length > 0) {\n const [[csrfHeader, csrf]] = csrfInfo.headerEntries;\n updateMetaTag(doc, '_csrf_header', csrfHeader);\n updateMetaTag(doc, '_csrf', csrf);\n }\n\n if (csrfInfo.formDataEntries.length > 0) {\n const [[csrfParameter]] = csrfInfo.formDataEntries;\n updateMetaTag(doc, '_csrf_parameter', csrfParameter);\n }\n}\n\n/** @internal */\nexport async function extractCsrfInfoFromMeta(doc: Document): Promise<CsrfInfo> {\n const cookieManager = (await cookieManagerPromise!).default;\n const timestamp = Date.now();\n const springCsrf = cookieManager.get(SPRING_CSRF_COOKIE_NAME) ?? extractContentFromMetaTag(doc, '_csrf');\n if (springCsrf) {\n const csrfHeader = extractContentFromMetaTag(doc, '_csrf_header');\n const csrfParameter = extractContentFromMetaTag(doc, '_csrf_parameter');\n return {\n headerEntries: csrfHeader ? [[csrfHeader, springCsrf]] : [],\n formDataEntries: csrfParameter ? [[csrfParameter, springCsrf]] : [],\n timestamp,\n type: CsrfInfoType.SPRING,\n };\n }\n\n const vaadinCsrf = cookieManager.get(VAADIN_CSRF_COOKIE_NAME) ?? '';\n return {\n type: CsrfInfoType.VAADIN,\n headerEntries: [[VAADIN_CSRF_HEADER, vaadinCsrf]],\n formDataEntries: [],\n timestamp,\n };\n}\n\n/**\n * The source of CSRF related headers and parameters for endpoint requests.\n *\n * @internal may change or be removed in a future version.\n **/\nexport interface CsrfInfoSource {\n /**\n * Get an up-to-date value.\n */\n get(): Promise<CsrfInfo>;\n\n /**\n * Reset back to initial value and re-initialize.\n */\n reset(): void;\n\n /**\n * Close internal message channels. May be called to free resources up\n * whenever the value is not needed.\n */\n close(): void;\n\n /**\n * Reopen internal message channels after prior closing and request a shared\n * value from another clients.\n */\n open(): void;\n}\n\n/** @internal */\nexport class SharedCsrfInfoSource implements CsrfInfoSource {\n #updateChannel: BroadcastChannel | undefined;\n #requestUpdateChannel: BroadcastChannel | undefined;\n #valuePromise!: Promise<CsrfInfo>;\n #resolveInitialValue?: (csrfInfo: CsrfInfo) => void;\n #lastUpdateTimestamp: number = 0;\n\n constructor() {\n this.reset();\n }\n\n open(): void {\n if (this.#updateChannel || this.#requestUpdateChannel) {\n this.close();\n }\n\n this.#updateChannel = new BroadcastChannel(this.#getBroadcastChannelName('update'));\n this.#updateChannel.onmessage = (e: MessageEvent) => {\n if (!isCsrfInfo(e.data)) {\n return;\n }\n const csrfInfo: CsrfInfo = e.data;\n if (csrfInfo.timestamp > this.#lastUpdateTimestamp) {\n this.#lastUpdateTimestamp = csrfInfo.timestamp;\n this.#receiveCsrfInfo(csrfInfo);\n }\n };\n\n this.#requestUpdateChannel = new BroadcastChannel(this.#getBroadcastChannelName('requestUpdate'));\n this.#requestUpdateChannel.onmessage = () => {\n this.get().then((csrfInfo: CsrfInfo) => {\n this.#sendCsrfInfo(csrfInfo);\n }, console.error);\n };\n\n // Request an update from peer clients on reopen\n if (this.#lastUpdateTimestamp > 0) {\n this.#requestUpdateChannel.postMessage(undefined);\n }\n }\n\n close(): void {\n if (this.#requestUpdateChannel) {\n this.#requestUpdateChannel.onmessage = null;\n this.#requestUpdateChannel.close();\n this.#requestUpdateChannel = undefined;\n }\n\n if (this.#updateChannel) {\n this.#updateChannel.onmessage = null;\n this.#updateChannel.close();\n this.#updateChannel = undefined;\n }\n }\n\n #getBroadcastChannelName(name: string): string {\n return `@vaadin/hilla-frontend/SharedCsrfUtils.${name}`;\n }\n\n async get(): Promise<CsrfInfo> {\n return this.#valuePromise;\n }\n\n reset(): void {\n this.#lastUpdateTimestamp = 0;\n this.close();\n this.open();\n this.#valuePromise = this._getInitial().then((csrfInfo: CsrfInfo) => {\n this.#lastUpdateTimestamp = csrfInfo.timestamp;\n return csrfInfo;\n });\n if (!this.#resolveInitialValue) {\n this.get()\n .then((csrfInfo: CsrfInfo) => {\n this.#sendCsrfInfo(csrfInfo);\n })\n .catch(console.error);\n }\n }\n\n /**\n * Provides initial value for both constructor and `reset()`. The default\n * implementation uses messages to get a shared value from another window\n * or worker client.\n */\n protected async _getInitial(): Promise<CsrfInfo> {\n return new Promise<CsrfInfo>((resolve) => {\n this.#resolveInitialValue = resolve;\n this.#requestUpdateChannel?.postMessage(undefined);\n });\n }\n\n #sendCsrfInfo(csrfInfo: CsrfInfo) {\n this.#updateChannel?.postMessage(csrfInfo);\n }\n\n #receiveCsrfInfo(csrfInfo: CsrfInfo) {\n if (this.#resolveInitialValue) {\n this.#resolveInitialValue(csrfInfo);\n this.#resolveInitialValue = undefined;\n } else {\n this.#valuePromise = Promise.resolve(csrfInfo);\n }\n }\n}\n\n/** @internal */\nexport class BrowserCsrfInfoSource extends SharedCsrfInfoSource {\n constructor() {\n super();\n globalThis.addEventListener('pagehide', this.close.bind(this));\n globalThis.addEventListener('pageshow', this.open.bind(this));\n }\n\n protected override async _getInitial(): Promise<CsrfInfo> {\n return extractCsrfInfoFromMeta(globalThis.document);\n }\n}\n\n/** @internal */\n// eslint-disable-next-line import/no-mutable-exports\nlet csrfInfoSource: CsrfInfoSource;\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nif (globalThis.document) {\n csrfInfoSource = new BrowserCsrfInfoSource();\n} else {\n csrfInfoSource = new SharedCsrfInfoSource();\n}\nexport default csrfInfoSource;\n"],"version":3}
|
|
1
|
+
{"mappings":"AAEA,OAAO,uCAAwC;AAI/C,OAAO,IAAK,sCAAL;AACL;AACA;;AACD;AAUD,SAAS,WAAWA,GAA2B;AAC7C,QAAO,MAAM,eAAe,MAAM,YAAY,mBAAmB,KAAK,qBAAqB,KAAK,eAAe;AAChH;;AAGD,OAAO,MAAM,qBAAqB;;AAElC,OAAO,MAAM,0BAA0B;;AAEvC,OAAO,MAAM,0BAA0B;AAEvC,SAAS,0BAA0BC,KAAeC,SAAqC;CACrF,MAAM,UAAU,IAAI,KAAK,eAAgC,aAAa,QAAQ,IAAI;CAClF,MAAM,QAAQ,SAAS;AACvB,KAAI,SAAS,MAAM,aAAa,KAAK,aAAa;AAChD,SAAO;CACR;AAED,QAAO;AACR;AAED,SAAS,cAAcD,KAAeE,MAAcC,S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ACZ,OAAK,MAAM;AACX,OAAKG,gBAAgB,KAAK,aAAa,CAAC,KAAK,CAACR,aAAuB;AACnE,QAAKK,uBAAuB,SAAS;AACrC,UAAO;EACR,EAAC;AACF,OAAK,KAAKI,sBAAsB;AAC9B,QAAK,KAAK,CACP,KAAK,CAACT,aAAuB;AAC5B,SAAKO,cAAc,SAAS;GAC7B,EAAC,CACD,MAAM,QAAQ,MAAM;EACxB;CACF;;;;;;CAOD,MAAgB,cAAiC;AAC/C,SAAO,IAAI,QAAkB,CAAC,YAAY;AACxC,QAAKE,uBAAuB;AAC5B,QAAKP,uBAAuB,YAAY,UAAU;EACnD;CACF;CAED,cAAcF,UAAoB;AAChC,OAAKC,gBAAgB,YAAY,SAAS;CAC3C;CAED,iBAAiBD,UAAoB;AACnC,MAAI,KAAKS,sBAAsB;AAC7B,QAAKA,qBAAqB,SAAS;AACnC,QAAKA,uBAAuB;EAC7B,OAAM;AACL,QAAKD,gBAAgB,QAAQ,QAAQ,SAAS;EAC/C;CACF;AACF;;AAGD,OAAO,MAAM,8BAA8B,qBAAqB;CAC9D,cAAc;AACZ,SAAO;AACP,aAAW,iBAAiB,YAAY,KAAK,MAAM,KAAK,KAAK,CAAC;AAC9D,aAAW,iBAAiB,YAAY,KAAK,KAAK,KAAK,KAAK,CAAC;CAC9D;CAED,MAAyB,cAAiC;AACxD,SAAO,wBAAwB,WAAW,SAAS;CACpD;AACF;;AAID,IAAIE;AAEJ,IAAI,WAAW,UAAU;AACvB,kBAAiB,IAAI;AACtB,OAAM;AACL,kBAAiB,IAAI;AACtB;AACD,eAAe","names":["o: unknown","doc: Document","metaTag: string","name: string","content: string","csrfInfo: CsrfInfo","#updateChannel","#requestUpdateChannel","#getBroadcastChannelName","e: MessageEvent","#lastUpdateTimestamp","#receiveCsrfInfo","#sendCsrfInfo","#valuePromise","#resolveInitialValue","csrfInfoSource: CsrfInfoSource"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/CsrfInfoSource.ts"],"sourcesContent":["/// <reference lib=\"webworker\" />\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nimport CookieManager from './CookieManager.js';\n\n/** @internal */\nexport type NameValueEntry = readonly [name: string, value: string];\nexport enum CsrfInfoType {\n SPRING = 'Spring',\n VAADIN = 'Vaadin',\n}\n\n/** @internal */\nexport type CsrfInfo = {\n readonly headerEntries: readonly NameValueEntry[];\n readonly formDataEntries: readonly NameValueEntry[];\n readonly type: CsrfInfoType;\n readonly timestamp: number;\n};\n\nfunction isCsrfInfo(o: unknown): o is CsrfInfo {\n return o !== null && typeof o === 'object' && 'headerEntries' in o && 'formDataEntries' in o && 'timestamp' in o;\n}\n\n/** @internal */\nexport const VAADIN_CSRF_HEADER = 'X-CSRF-Token';\n/** @internal */\nexport const VAADIN_CSRF_COOKIE_NAME = 'csrfToken';\n/** @internal */\nexport const SPRING_CSRF_COOKIE_NAME = 'XSRF-TOKEN';\n\nfunction extractContentFromMetaTag(doc: Document, metaTag: string): string | undefined {\n const element = doc.head.querySelector<HTMLMetaElement>(`meta[name=\"${metaTag}\"]`);\n const value = element?.content;\n if (value && value.toLowerCase() !== 'undefined') {\n return value;\n }\n\n return undefined;\n}\n\nfunction updateMetaTag(doc: Document, name: string, content: string): void {\n const meta = doc.createElement('meta');\n meta.name = name;\n meta.content = content;\n const existing = doc.head.querySelector(`meta[name=\"${name}\"]`);\n if (existing) {\n existing.replaceWith(meta);\n } else {\n doc.head.appendChild(meta);\n }\n}\n\nexport function clearCsrfInfoMeta(doc: Document): void {\n Array.from(\n doc.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"], meta[name=\"_csrf_parameter\"]'),\n ).forEach((el) => el.remove());\n}\n\nexport function updateCsrfInfoMeta(csrfInfo: CsrfInfo, doc: Document): void {\n if (csrfInfo.type !== CsrfInfoType.SPRING) {\n return;\n }\n\n if (csrfInfo.headerEntries.length > 0) {\n const [[csrfHeader, csrf]] = csrfInfo.headerEntries;\n updateMetaTag(doc, '_csrf_header', csrfHeader);\n updateMetaTag(doc, '_csrf', csrf);\n }\n\n if (csrfInfo.formDataEntries.length > 0) {\n const [[csrfParameter]] = csrfInfo.formDataEntries;\n updateMetaTag(doc, '_csrf_parameter', csrfParameter);\n }\n}\n\n/** @internal */\nexport async function extractCsrfInfoFromMeta(doc: Document): Promise<CsrfInfo> {\n const timestamp = Date.now();\n // TODO: Replace CookieManager with CookieStore API once it is available.\n // As CookieStore is async, it will require this function to be async also.\n const springCsrf =\n (await Promise.resolve().then(() => CookieManager.get(SPRING_CSRF_COOKIE_NAME))) ??\n extractContentFromMetaTag(doc, '_csrf');\n if (springCsrf) {\n const csrfHeader = extractContentFromMetaTag(doc, '_csrf_header');\n const csrfParameter = extractContentFromMetaTag(doc, '_csrf_parameter');\n return {\n headerEntries: csrfHeader ? [[csrfHeader, springCsrf]] : [],\n formDataEntries: csrfParameter ? [[csrfParameter, springCsrf]] : [],\n timestamp,\n type: CsrfInfoType.SPRING,\n };\n }\n\n const vaadinCsrf = CookieManager.get(VAADIN_CSRF_COOKIE_NAME) ?? '';\n return {\n type: CsrfInfoType.VAADIN,\n headerEntries: [[VAADIN_CSRF_HEADER, vaadinCsrf]],\n formDataEntries: [],\n timestamp,\n };\n}\n\n/**\n * The source of CSRF related headers and parameters for endpoint requests.\n *\n * @internal may change or be removed in a future version.\n **/\nexport interface CsrfInfoSource {\n /**\n * Get an up-to-date value.\n */\n get(): Promise<CsrfInfo>;\n\n /**\n * Reset back to initial value and re-initialize.\n */\n reset(): void;\n\n /**\n * Close internal message channels. May be called to free resources up\n * whenever the value is not needed.\n */\n close(): void;\n\n /**\n * Reopen internal message channels after prior closing and request a shared\n * value from another clients.\n */\n open(): void;\n}\n\n/** @internal */\nexport class SharedCsrfInfoSource implements CsrfInfoSource {\n #updateChannel: BroadcastChannel | undefined;\n #requestUpdateChannel: BroadcastChannel | undefined;\n #valuePromise!: Promise<CsrfInfo>;\n #resolveInitialValue?: (csrfInfo: CsrfInfo) => void;\n #lastUpdateTimestamp: number = 0;\n\n constructor() {\n this.reset();\n }\n\n open(): void {\n if (this.#updateChannel || this.#requestUpdateChannel) {\n this.close();\n }\n\n this.#updateChannel = new BroadcastChannel(this.#getBroadcastChannelName('update'));\n this.#updateChannel.onmessage = (e: MessageEvent) => {\n if (!isCsrfInfo(e.data)) {\n return;\n }\n const csrfInfo: CsrfInfo = e.data;\n if (csrfInfo.timestamp > this.#lastUpdateTimestamp) {\n this.#lastUpdateTimestamp = csrfInfo.timestamp;\n this.#receiveCsrfInfo(csrfInfo);\n }\n };\n\n this.#requestUpdateChannel = new BroadcastChannel(this.#getBroadcastChannelName('requestUpdate'));\n this.#requestUpdateChannel.onmessage = () => {\n this.get().then((csrfInfo: CsrfInfo) => {\n this.#sendCsrfInfo(csrfInfo);\n }, console.error);\n };\n\n // Request an update from peer clients on reopen\n if (this.#lastUpdateTimestamp > 0) {\n this.#requestUpdateChannel.postMessage(undefined);\n }\n }\n\n close(): void {\n if (this.#requestUpdateChannel) {\n this.#requestUpdateChannel.onmessage = null;\n this.#requestUpdateChannel.close();\n this.#requestUpdateChannel = undefined;\n }\n\n if (this.#updateChannel) {\n this.#updateChannel.onmessage = null;\n this.#updateChannel.close();\n this.#updateChannel = undefined;\n }\n }\n\n #getBroadcastChannelName(name: string): string {\n return `@vaadin/hilla-frontend/SharedCsrfUtils.${name}`;\n }\n\n async get(): Promise<CsrfInfo> {\n return this.#valuePromise;\n }\n\n reset(): void {\n this.#lastUpdateTimestamp = 0;\n this.close();\n this.open();\n this.#valuePromise = this._getInitial().then((csrfInfo: CsrfInfo) => {\n this.#lastUpdateTimestamp = csrfInfo.timestamp;\n return csrfInfo;\n });\n if (!this.#resolveInitialValue) {\n this.get()\n .then((csrfInfo: CsrfInfo) => {\n this.#sendCsrfInfo(csrfInfo);\n })\n .catch(console.error);\n }\n }\n\n /**\n * Provides initial value for both constructor and `reset()`. The default\n * implementation uses messages to get a shared value from another window\n * or worker client.\n */\n protected async _getInitial(): Promise<CsrfInfo> {\n return new Promise<CsrfInfo>((resolve) => {\n this.#resolveInitialValue = resolve;\n this.#requestUpdateChannel?.postMessage(undefined);\n });\n }\n\n #sendCsrfInfo(csrfInfo: CsrfInfo) {\n this.#updateChannel?.postMessage(csrfInfo);\n }\n\n #receiveCsrfInfo(csrfInfo: CsrfInfo) {\n if (this.#resolveInitialValue) {\n this.#resolveInitialValue(csrfInfo);\n this.#resolveInitialValue = undefined;\n } else {\n this.#valuePromise = Promise.resolve(csrfInfo);\n }\n }\n}\n\n/** @internal */\nexport class BrowserCsrfInfoSource extends SharedCsrfInfoSource {\n constructor() {\n super();\n globalThis.addEventListener('pagehide', this.close.bind(this));\n globalThis.addEventListener('pageshow', this.open.bind(this));\n }\n\n protected override async _getInitial(): Promise<CsrfInfo> {\n return extractCsrfInfoFromMeta(globalThis.document);\n }\n}\n\n/** @internal */\n// eslint-disable-next-line import/no-mutable-exports\nlet csrfInfoSource: CsrfInfoSource;\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nif (globalThis.document) {\n csrfInfoSource = new BrowserCsrfInfoSource();\n} else {\n csrfInfoSource = new SharedCsrfInfoSource();\n}\nexport default csrfInfoSource;\n"],"version":3}
|
package/FluxConnection.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import csrfInfoSource from "./CsrfInfoSource.js";
|
|
2
2
|
import { isClientMessage } from "./FluxMessages.js";
|
|
3
|
+
import { VAADIN_BROWSER_ENVIRONMENT } from "./utils.js";
|
|
3
4
|
export let State = function(State) {
|
|
4
5
|
State["ACTIVE"] = "active";
|
|
5
6
|
State["INACTIVE"] = "inactive";
|
|
@@ -38,7 +39,7 @@ export let FluxSubscriptionState = function(FluxSubscriptionState) {
|
|
|
38
39
|
FluxSubscriptionState["CLOSED"] = "closed";
|
|
39
40
|
return FluxSubscriptionState;
|
|
40
41
|
}({});
|
|
41
|
-
const atmospherePromise =
|
|
42
|
+
const atmospherePromise = VAADIN_BROWSER_ENVIRONMENT ? import("atmosphere.js") : undefined;
|
|
42
43
|
/**
|
|
43
44
|
* A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods.
|
|
44
45
|
*/
|
|
@@ -159,79 +160,76 @@ export class FluxConnection extends EventTarget {
|
|
|
159
160
|
return hillaSubscription;
|
|
160
161
|
}
|
|
161
162
|
async #connectWebsocket(prefix, atmosphereOptions) {
|
|
163
|
+
if (!atmospherePromise) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
162
166
|
const extraHeaders = Object.fromEntries((await csrfInfoSource.get()).headerEntries);
|
|
163
167
|
const pushUrl = "HILLA/push";
|
|
164
168
|
const url = prefix.length === 0 ? pushUrl : (prefix.endsWith("/") ? prefix : `${prefix}/`) + pushUrl;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
this.#endpointInfos.forEach((_, id) => this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED));
|
|
230
|
-
}
|
|
231
|
-
},
|
|
232
|
-
...atmosphereOptions
|
|
233
|
-
});
|
|
234
|
-
}
|
|
169
|
+
const atmosphere = (await atmospherePromise).default;
|
|
170
|
+
this.#socket = atmosphere.subscribe?.({
|
|
171
|
+
contentType: "application/json; charset=UTF-8",
|
|
172
|
+
enableProtocol: true,
|
|
173
|
+
transport: "websocket",
|
|
174
|
+
fallbackTransport: "websocket",
|
|
175
|
+
headers: extraHeaders,
|
|
176
|
+
maxReconnectOnClose: 1e7,
|
|
177
|
+
reconnectInterval: 5e3,
|
|
178
|
+
timeout: -1,
|
|
179
|
+
trackMessageLength: true,
|
|
180
|
+
url,
|
|
181
|
+
onClose: () => {
|
|
182
|
+
this.wasClosed = true;
|
|
183
|
+
if (this.state !== State.INACTIVE) {
|
|
184
|
+
this.state = State.INACTIVE;
|
|
185
|
+
this.dispatchEvent(new CustomEvent("state-changed", { detail: { active: false } }));
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
onError: (response) => {
|
|
189
|
+
console.error("error in push communication", response);
|
|
190
|
+
},
|
|
191
|
+
onMessage: (response) => {
|
|
192
|
+
if (response.responseBody) {
|
|
193
|
+
this.#handleMessage(JSON.parse(response.responseBody));
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
onMessagePublished: (response) => {
|
|
197
|
+
if (response?.responseBody) {
|
|
198
|
+
this.#handleMessage(JSON.parse(response.responseBody));
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
onOpen: () => {
|
|
202
|
+
if (this.state !== State.ACTIVE) {
|
|
203
|
+
this.#resubscribeIfWasClosed();
|
|
204
|
+
this.state = State.ACTIVE;
|
|
205
|
+
this.dispatchEvent(new CustomEvent("state-changed", { detail: { active: true } }));
|
|
206
|
+
this.#sendPendingMessages();
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
onReopen: () => {
|
|
210
|
+
if (this.state !== State.ACTIVE) {
|
|
211
|
+
this.#resubscribeIfWasClosed();
|
|
212
|
+
this.state = State.ACTIVE;
|
|
213
|
+
this.dispatchEvent(new CustomEvent("state-changed", { detail: { active: true } }));
|
|
214
|
+
this.#sendPendingMessages();
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
onReconnect: () => {
|
|
218
|
+
if (this.state !== State.RECONNECTING) {
|
|
219
|
+
this.state = State.RECONNECTING;
|
|
220
|
+
this.#endpointInfos.forEach((_, id) => {
|
|
221
|
+
this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
onFailureToReconnect: () => {
|
|
226
|
+
if (this.state !== State.INACTIVE) {
|
|
227
|
+
this.state = State.INACTIVE;
|
|
228
|
+
this.dispatchEvent(new CustomEvent("state-changed", { detail: { active: false } }));
|
|
229
|
+
this.#endpointInfos.forEach((_, id) => this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED));
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
...atmosphereOptions
|
|
235
233
|
});
|
|
236
234
|
}
|
|
237
235
|
#setSubscriptionConnState(id, state) {
|
package/FluxConnection.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAEA,OAAO,yCAA0C;AACjD,SACE,0CAIyB;AAE3B,OAAO,IAAK,wBAAL;AACL;AACA;AACA;;AACD;;;;AAiBD,OAAO,IAAK,8DAAL;;;;AAIL;;;;AAIA;;AACD;;;;AAKD,OAAO,IAAK,wDAAL;;;;AAIL;;;;AAIA;;;;AAIA;;AACD;AAeD,MAAMA,oBAAgE,WAAW,WAC7E,OAAO,mBACP,QAAQ,QAAQ,UAAU;;;;AAK9B,OAAO,MAAM,uBAAuB,YAAY;CAC9C,QAAe,MAAM;CACrB,YAAY;CACZ,AAASC,iBAAiB,IAAI;CAC9B,UAAU;CACV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AoB,GAAG;AAC5B,SAAK,UAAU;AACb,WAAM,IAAI,MACR,gBACK,WAAW,aAAa,aAAa,GAAG,aAAa,WAAW,GAAG,KAAK,UAAU,aAAa,OAAO,CAAC,KAAK,QAAQ,QAAQ,KAC5H,iCAAiC,QAAQ,QAAQ;IAEzD;GACF;EACF,OAAM;AACL,SAAM,IAAI,OAAO,+BAA+B,OAAO,QAAQ,CAAC;EACjE;CACF;CAED,oBAAoBI,IAAY;AAC9B,OAAKN,0BAA0B,IAAI,sBAAsB,OAAO;AAChE,OAAKN,uBAAuB,OAAO,GAAG;AACtC,OAAKD,wBAAwB,OAAO,GAAG;AACvC,OAAKD,iBAAiB,OAAO,GAAG;AAChC,OAAKF,qBAAqB,OAAO,GAAG;AACpC,OAAKC,kBAAkB,OAAO,GAAG;AACjC,OAAKF,eAAe,OAAO,GAAG;CAC/B;CAED,MAAMqC,SAAwB;AAC5B,MAAI,KAAK,UAAU,MAAM,aAAa,KAAKN,SAAS;AAClD,QAAKO,iBAAiB,KAAK,QAAQ;EACpC,OAAM;AACL,QAAKP,QAAQ,OAAO,KAAK,UAAU,QAAQ,CAAC;EAC7C;CACF;CAED,uBAAuB;AACrB,OAAKO,iBAAiB,QAAQ,CAAC,QAAQ,KAAK1B,MAAM,IAAI,CAAC;AACvD,OAAK0B,mBAAmB,CAAE;CAC3B;AACF","names":["atmospherePromise: Promise<Atmosphere.Atmosphere | undefined>","#endpointInfos","#onCompleteCallbacks","#onErrorCallbacks","#onNextCallbacks","#onStateChangeCallbacks","#statusOfSubscriptions","#ready","connectPrefix: string","atmosphereOptions?: Partial<Atmosphere.Request>","#connectWebsocket","toBeRemoved: string[]","#setSubscriptionConnState","#send","#removeSubscription","endpointName: string","methodName: string","parameters?: unknown[]","id: string","#nextId","msg: ServerConnectMessage","hillaSubscription: Subscription<any>","closeMessage: ServerCloseMessage","context: ReactiveControllerHost","callback: () => void","callback: (message: string) => void","callback: (value: any) => void","callback: () => ActionOnLostSubscription | void","callback: (event: FluxSubscriptionStateChangeEvent) => void","prefix: string","atmosphereOptions: Partial<Atmosphere.Request>","atmosphere: Atmosphere.Atmosphere | undefined","#socket","#handleMessage","#resubscribeIfWasClosed","#sendPendingMessages","state: FluxSubscriptionState","message: unknown","message: ServerMessage","#pendingMessages"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/FluxConnection.ts"],"sourcesContent":["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport type { Subscription } from './Connect.js';\nimport csrfInfoSource from './CsrfInfoSource.js';\nimport {\n isClientMessage,\n type ServerCloseMessage,\n type ServerConnectMessage,\n type ServerMessage,\n} from './FluxMessages.js';\n\nexport enum State {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n RECONNECTING = 'reconnecting',\n}\n\ntype ActiveEvent = CustomEvent<{ active: boolean }>;\ninterface EventMap {\n 'state-changed': ActiveEvent;\n}\n\ntype ListenerType<T extends keyof EventMap> =\n | ((this: FluxConnection, ev: EventMap[T]) => any)\n | {\n handleEvent(ev: EventMap[T]): void;\n }\n | null;\n\n/**\n * Possible options for dealing with lost subscriptions after a websocket is reopened.\n */\nexport enum ActionOnLostSubscription {\n /**\n * The subscription should be resubscribed using the same server method and parameters.\n */\n RESUBSCRIBE = 'resubscribe',\n /**\n * The subscription should be removed.\n */\n REMOVE = 'remove',\n}\n\n/**\n * Possible states of a flux subscription.\n */\nexport enum FluxSubscriptionState {\n /**\n * The subscription is not connected and is trying to connect.\n */\n CONNECTING = 'connecting',\n /**\n * The subscription is connected and receiving updates.\n */\n CONNECTED = 'connected',\n /**\n * The subscription is closed and is not trying to reconnect.\n */\n CLOSED = 'closed',\n}\n\n/**\n * Event wrapper for flux subscription connection state change callback\n */\nexport type FluxSubscriptionStateChangeEvent = CustomEvent<{ state: FluxSubscriptionState }>;\n\ntype EndpointInfo = {\n endpointName: string;\n methodName: string;\n params: unknown[] | undefined;\n reconnect?(): ActionOnLostSubscription | void;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nconst atmospherePromise: Promise<Atmosphere.Atmosphere | undefined> = globalThis.document\n ? import('atmosphere.js')\n : Promise.resolve(undefined);\n\n/**\n * A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods.\n */\nexport class FluxConnection extends EventTarget {\n state: State = State.INACTIVE;\n wasClosed = false;\n readonly #endpointInfos = new Map<string, EndpointInfo>();\n #nextId = 0;\n readonly #onCompleteCallbacks = new Map<string, () => void>();\n readonly #onErrorCallbacks = new Map<string, (message: string) => void>();\n readonly #onNextCallbacks = new Map<string, (value: any) => void>();\n readonly #onStateChangeCallbacks = new Map<string, (event: FluxSubscriptionStateChangeEvent) => void>();\n readonly #statusOfSubscriptions = new Map<string, FluxSubscriptionState>();\n #pendingMessages: ServerMessage[] = [];\n #socket?: Atmosphere.Request;\n readonly #ready: Promise<void>;\n\n constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {\n super();\n this.#ready = this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});\n }\n\n #resubscribeIfWasClosed() {\n if (this.wasClosed) {\n this.wasClosed = false;\n const toBeRemoved: string[] = [];\n this.#endpointInfos.forEach((endpointInfo, id) => {\n if (endpointInfo.reconnect?.() === ActionOnLostSubscription.RESUBSCRIBE) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n this.#send({\n '@type': 'subscribe',\n endpointName: endpointInfo.endpointName,\n id,\n methodName: endpointInfo.methodName,\n params: endpointInfo.params,\n });\n } else {\n toBeRemoved.push(id);\n }\n });\n toBeRemoved.forEach((id) => this.#removeSubscription(id));\n }\n }\n\n /**\n * Promise that resolves when the instance is initialized.\n */\n get ready(): Promise<void> {\n return this.#ready;\n }\n\n /**\n * Subscribes to the flux returned by the given endpoint name + method name using the given parameters.\n *\n * @param endpointName - the endpoint to connect to\n * @param methodName - the method in the endpoint to connect to\n * @param parameters - the parameters to use\n * @returns a subscription\n */\n subscribe(endpointName: string, methodName: string, parameters?: unknown[]): Subscription<any> {\n const id: string = this.#nextId.toString();\n this.#nextId += 1;\n const params = parameters ?? [];\n\n const msg: ServerConnectMessage = { '@type': 'subscribe', endpointName, id, methodName, params };\n this.#send(msg);\n this.#endpointInfos.set(id, { endpointName, methodName, params });\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n const hillaSubscription: Subscription<any> = {\n cancel: () => {\n if (!this.#endpointInfos.has(id)) {\n // Subscription already closed or canceled\n return;\n }\n\n const closeMessage: ServerCloseMessage = { '@type': 'unsubscribe', id };\n this.#send(closeMessage);\n this.#removeSubscription(id);\n },\n context(context: ReactiveControllerHost): Subscription<any> {\n context.addController({\n hostDisconnected() {\n hillaSubscription.cancel();\n },\n });\n return hillaSubscription;\n },\n onComplete: (callback: () => void): Subscription<any> => {\n this.#onCompleteCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onError: (callback: (message: string) => void): Subscription<any> => {\n this.#onErrorCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onNext: (callback: (value: any) => void): Subscription<any> => {\n this.#onNextCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onSubscriptionLost: (callback: () => ActionOnLostSubscription | void): Subscription<any> => {\n if (this.#endpointInfos.has(id)) {\n this.#endpointInfos.get(id)!.reconnect = callback;\n } else {\n console.warn(`\"onReconnect\" value not set for subscription \"${id}\" because it was already canceled`);\n }\n return hillaSubscription;\n },\n onConnectionStateChange: (callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<any> => {\n this.#onStateChangeCallbacks.set(id, callback);\n callback(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n return hillaSubscription;\n },\n };\n return hillaSubscription;\n }\n\n async #connectWebsocket(prefix: string, atmosphereOptions: Partial<Atmosphere.Request>) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const extraHeaders = Object.fromEntries((await csrfInfoSource.get()).headerEntries);\n const pushUrl = 'HILLA/push';\n const url = prefix.length === 0 ? pushUrl : (prefix.endsWith('/') ? prefix : `${prefix}/`) + pushUrl;\n return atmospherePromise.then((atmosphere: Atmosphere.Atmosphere | undefined) => {\n if (!atmosphere) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (globalThis.document) {\n this.#socket = atmosphere.subscribe?.({\n contentType: 'application/json; charset=UTF-8',\n enableProtocol: true,\n transport: 'websocket',\n fallbackTransport: 'websocket',\n headers: extraHeaders,\n maxReconnectOnClose: 10000000,\n reconnectInterval: 5000,\n timeout: -1,\n trackMessageLength: true,\n url,\n onClose: () => {\n this.wasClosed = true;\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n }\n },\n onError: (response) => {\n // eslint-disable-next-line no-console\n console.error('error in push communication', response);\n },\n onMessage: (response) => {\n if (response.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onMessagePublished: (response) => {\n if (response?.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onOpen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReopen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReconnect: () => {\n if (this.state !== State.RECONNECTING) {\n this.state = State.RECONNECTING;\n this.#endpointInfos.forEach((_, id) => {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n });\n }\n },\n onFailureToReconnect: () => {\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n this.#endpointInfos.forEach((_, id) => this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED));\n }\n },\n ...atmosphereOptions,\n } satisfies Atmosphere.Request);\n }\n });\n }\n\n #setSubscriptionConnState(id: string, state: FluxSubscriptionState) {\n const currentState = this.#statusOfSubscriptions.get(id);\n if (!currentState) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n } else if (currentState !== state) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n }\n }\n\n #handleMessage(message: unknown) {\n if (isClientMessage(message)) {\n const { id } = message;\n const endpointInfo = this.#endpointInfos.get(id);\n\n if (message['@type'] === 'update') {\n const callback = this.#onNextCallbacks.get(id);\n if (callback) {\n callback(message.item);\n }\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTED);\n } else if (message['@type'] === 'complete') {\n this.#onCompleteCallbacks.get(id)?.();\n this.#removeSubscription(id);\n } else {\n const callback = this.#onErrorCallbacks.get(id);\n if (callback) {\n callback(message.message);\n }\n this.#removeSubscription(id);\n if (!callback) {\n throw new Error(\n endpointInfo\n ? `Error in ${endpointInfo.endpointName}.${endpointInfo.methodName}(${JSON.stringify(endpointInfo.params)}): ${message.message}`\n : `Error in unknown subscription: ${message.message}`,\n );\n }\n }\n } else {\n throw new Error(`Unknown message from server: ${String(message)}`);\n }\n }\n\n #removeSubscription(id: string) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED);\n this.#statusOfSubscriptions.delete(id);\n this.#onStateChangeCallbacks.delete(id);\n this.#onNextCallbacks.delete(id);\n this.#onCompleteCallbacks.delete(id);\n this.#onErrorCallbacks.delete(id);\n this.#endpointInfos.delete(id);\n }\n\n #send(message: ServerMessage) {\n if (this.state === State.INACTIVE || !this.#socket) {\n this.#pendingMessages.push(message);\n } else {\n this.#socket.push?.(JSON.stringify(message));\n }\n }\n\n #sendPendingMessages() {\n this.#pendingMessages.forEach((msg) => this.#send(msg));\n this.#pendingMessages = [];\n }\n}\n\nexport interface FluxConnection {\n addEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n removeEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n}\n"],"version":3}
|
|
1
|
+
{"mappings":"AAEA,OAAO,yCAA0C;AACjD,SACE,0CAIyB;AAC3B,SAAS,8CAA+C;AAExD,OAAO,IAAK,wBAAL;AACL;AACA;AACA;;AACD;;;;AAiBD,OAAO,IAAK,8DAAL;;;;AAIL;;;;AAIA;;AACD;;;;AAKD,OAAO,IAAK,wDAAL;;;;AAIL;;;;AAIA;;;;AAIA;;AACD;AAeD,MAAM,oBAAoB,6BAA6B,OAAO,mBAAmB;;;;AAKjF,OAAO,MAAM,uBAAuB,YAAY;CAC9C,QAAe,MAAM;CACrB,YAAY;CACZ,AAASA,iBAAiB,IAAI;CAC9B,UAAU;CACV,AAASC,uBAAuB,IAAI;CACpC,AAASC,oBAAoB,IAAI;CACjC,AAASC,mBAAmB,IAAI;CAChC,AAASC,0BAA0B,IAAI;CACvC,AAASC,yBAAyB,IAAI;CACtC,mBAAoC,CAAE;CACtC;CACA,AAASC;CAET,YAAYC,eAAuBC,mBAAiD;AAClF,SAAO;AACP,OAAKF,SAAS,KAAKG,kBAAkB,cAAc,QAAQ,aAAa,GAAG,EAAE,qBAAqB,CAAE,EAAC;CACtG;CAED,0BAA0B;AACxB,MAAI,KAAK,WAAW;AAClB,QAAK,YAAY;GACjB,MAAMC,cAAwB,CAAE;AAChC,QAAKV,eAAe,QAAQ,CAAC,cAAc,OAAO;AAChD,QAAI,aAAa,aAAa,KAAK,yBAAyB,aAAa;AACvE,UAAKW,0BAA0B,IAAI,sBAAsB,WAAW;AACpE,UAAKC,MAAM;eACA;MACT,cAAc,aAAa;MAC3B;MACA,YAAY,aAAa;MACzB,QAAQ,aAAa;K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;EACpC,OAAM;AACL,QAAKP,QAAQ,OAAO,KAAK,UAAU,QAAQ,CAAC;EAC7C;CACF;CAED,uBAAuB;AACrB,OAAKO,iBAAiB,QAAQ,CAAC,QAAQ,KAAKzB,MAAM,IAAI,CAAC;AACvD,OAAKyB,mBAAmB,CAAE;CAC3B;AACF","names":["#endpointInfos","#onCompleteCallbacks","#onErrorCallbacks","#onNextCallbacks","#onStateChangeCallbacks","#statusOfSubscriptions","#ready","connectPrefix: string","atmosphereOptions?: Partial<Atmosphere.Request>","#connectWebsocket","toBeRemoved: string[]","#setSubscriptionConnState","#send","#removeSubscription","endpointName: string","methodName: string","parameters?: unknown[]","id: string","#nextId","msg: ServerConnectMessage","hillaSubscription: Subscription<any>","closeMessage: ServerCloseMessage","context: ReactiveControllerHost","callback: () => void","callback: (message: string) => void","callback: (value: any) => void","callback: () => ActionOnLostSubscription | void","callback: (event: FluxSubscriptionStateChangeEvent) => void","prefix: string","atmosphereOptions: Partial<Atmosphere.Request>","#socket","#handleMessage","#resubscribeIfWasClosed","#sendPendingMessages","state: FluxSubscriptionState","message: unknown","message: ServerMessage","#pendingMessages"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/FluxConnection.ts"],"sourcesContent":["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport type { Subscription } from './Connect.js';\nimport csrfInfoSource from './CsrfInfoSource.js';\nimport {\n isClientMessage,\n type ServerCloseMessage,\n type ServerConnectMessage,\n type ServerMessage,\n} from './FluxMessages.js';\nimport { VAADIN_BROWSER_ENVIRONMENT } from './utils.js';\n\nexport enum State {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n RECONNECTING = 'reconnecting',\n}\n\ntype ActiveEvent = CustomEvent<{ active: boolean }>;\ninterface EventMap {\n 'state-changed': ActiveEvent;\n}\n\ntype ListenerType<T extends keyof EventMap> =\n | ((this: FluxConnection, ev: EventMap[T]) => any)\n | {\n handleEvent(ev: EventMap[T]): void;\n }\n | null;\n\n/**\n * Possible options for dealing with lost subscriptions after a websocket is reopened.\n */\nexport enum ActionOnLostSubscription {\n /**\n * The subscription should be resubscribed using the same server method and parameters.\n */\n RESUBSCRIBE = 'resubscribe',\n /**\n * The subscription should be removed.\n */\n REMOVE = 'remove',\n}\n\n/**\n * Possible states of a flux subscription.\n */\nexport enum FluxSubscriptionState {\n /**\n * The subscription is not connected and is trying to connect.\n */\n CONNECTING = 'connecting',\n /**\n * The subscription is connected and receiving updates.\n */\n CONNECTED = 'connected',\n /**\n * The subscription is closed and is not trying to reconnect.\n */\n CLOSED = 'closed',\n}\n\n/**\n * Event wrapper for flux subscription connection state change callback\n */\nexport type FluxSubscriptionStateChangeEvent = CustomEvent<{ state: FluxSubscriptionState }>;\n\ntype EndpointInfo = {\n endpointName: string;\n methodName: string;\n params: unknown[] | undefined;\n reconnect?(): ActionOnLostSubscription | void;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nconst atmospherePromise = VAADIN_BROWSER_ENVIRONMENT ? import('atmosphere.js') : undefined;\n\n/**\n * A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods.\n */\nexport class FluxConnection extends EventTarget {\n state: State = State.INACTIVE;\n wasClosed = false;\n readonly #endpointInfos = new Map<string, EndpointInfo>();\n #nextId = 0;\n readonly #onCompleteCallbacks = new Map<string, () => void>();\n readonly #onErrorCallbacks = new Map<string, (message: string) => void>();\n readonly #onNextCallbacks = new Map<string, (value: any) => void>();\n readonly #onStateChangeCallbacks = new Map<string, (event: FluxSubscriptionStateChangeEvent) => void>();\n readonly #statusOfSubscriptions = new Map<string, FluxSubscriptionState>();\n #pendingMessages: ServerMessage[] = [];\n #socket?: Atmosphere.Request;\n readonly #ready: Promise<void>;\n\n constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {\n super();\n this.#ready = this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});\n }\n\n #resubscribeIfWasClosed() {\n if (this.wasClosed) {\n this.wasClosed = false;\n const toBeRemoved: string[] = [];\n this.#endpointInfos.forEach((endpointInfo, id) => {\n if (endpointInfo.reconnect?.() === ActionOnLostSubscription.RESUBSCRIBE) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n this.#send({\n '@type': 'subscribe',\n endpointName: endpointInfo.endpointName,\n id,\n methodName: endpointInfo.methodName,\n params: endpointInfo.params,\n });\n } else {\n toBeRemoved.push(id);\n }\n });\n toBeRemoved.forEach((id) => this.#removeSubscription(id));\n }\n }\n\n /**\n * Promise that resolves when the instance is initialized.\n */\n get ready(): Promise<void> {\n return this.#ready;\n }\n\n /**\n * Subscribes to the flux returned by the given endpoint name + method name using the given parameters.\n *\n * @param endpointName - the endpoint to connect to\n * @param methodName - the method in the endpoint to connect to\n * @param parameters - the parameters to use\n * @returns a subscription\n */\n subscribe(endpointName: string, methodName: string, parameters?: unknown[]): Subscription<any> {\n const id: string = this.#nextId.toString();\n this.#nextId += 1;\n const params = parameters ?? [];\n\n const msg: ServerConnectMessage = { '@type': 'subscribe', endpointName, id, methodName, params };\n this.#send(msg);\n this.#endpointInfos.set(id, { endpointName, methodName, params });\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n const hillaSubscription: Subscription<any> = {\n cancel: () => {\n if (!this.#endpointInfos.has(id)) {\n // Subscription already closed or canceled\n return;\n }\n\n const closeMessage: ServerCloseMessage = { '@type': 'unsubscribe', id };\n this.#send(closeMessage);\n this.#removeSubscription(id);\n },\n context(context: ReactiveControllerHost): Subscription<any> {\n context.addController({\n hostDisconnected() {\n hillaSubscription.cancel();\n },\n });\n return hillaSubscription;\n },\n onComplete: (callback: () => void): Subscription<any> => {\n this.#onCompleteCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onError: (callback: (message: string) => void): Subscription<any> => {\n this.#onErrorCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onNext: (callback: (value: any) => void): Subscription<any> => {\n this.#onNextCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onSubscriptionLost: (callback: () => ActionOnLostSubscription | void): Subscription<any> => {\n if (this.#endpointInfos.has(id)) {\n this.#endpointInfos.get(id)!.reconnect = callback;\n } else {\n console.warn(`\"onReconnect\" value not set for subscription \"${id}\" because it was already canceled`);\n }\n return hillaSubscription;\n },\n onConnectionStateChange: (callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<any> => {\n this.#onStateChangeCallbacks.set(id, callback);\n callback(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n return hillaSubscription;\n },\n };\n return hillaSubscription;\n }\n\n async #connectWebsocket(prefix: string, atmosphereOptions: Partial<Atmosphere.Request>) {\n if (!atmospherePromise) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const extraHeaders = Object.fromEntries((await csrfInfoSource.get()).headerEntries);\n const pushUrl = 'HILLA/push';\n const url = prefix.length === 0 ? pushUrl : (prefix.endsWith('/') ? prefix : `${prefix}/`) + pushUrl;\n const atmosphere = (await atmospherePromise).default;\n this.#socket = atmosphere.subscribe?.({\n contentType: 'application/json; charset=UTF-8',\n enableProtocol: true,\n transport: 'websocket',\n fallbackTransport: 'websocket',\n headers: extraHeaders,\n maxReconnectOnClose: 10000000,\n reconnectInterval: 5000,\n timeout: -1,\n trackMessageLength: true,\n url,\n onClose: () => {\n this.wasClosed = true;\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n }\n },\n onError: (response) => {\n // eslint-disable-next-line no-console\n console.error('error in push communication', response);\n },\n onMessage: (response) => {\n if (response.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onMessagePublished: (response) => {\n if (response?.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onOpen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReopen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReconnect: () => {\n if (this.state !== State.RECONNECTING) {\n this.state = State.RECONNECTING;\n this.#endpointInfos.forEach((_, id) => {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n });\n }\n },\n onFailureToReconnect: () => {\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n this.#endpointInfos.forEach((_, id) => this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED));\n }\n },\n ...atmosphereOptions,\n } satisfies Atmosphere.Request);\n }\n\n #setSubscriptionConnState(id: string, state: FluxSubscriptionState) {\n const currentState = this.#statusOfSubscriptions.get(id);\n if (!currentState) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n } else if (currentState !== state) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n }\n }\n\n #handleMessage(message: unknown) {\n if (isClientMessage(message)) {\n const { id } = message;\n const endpointInfo = this.#endpointInfos.get(id);\n\n if (message['@type'] === 'update') {\n const callback = this.#onNextCallbacks.get(id);\n if (callback) {\n callback(message.item);\n }\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTED);\n } else if (message['@type'] === 'complete') {\n this.#onCompleteCallbacks.get(id)?.();\n this.#removeSubscription(id);\n } else {\n const callback = this.#onErrorCallbacks.get(id);\n if (callback) {\n callback(message.message);\n }\n this.#removeSubscription(id);\n if (!callback) {\n throw new Error(\n endpointInfo\n ? `Error in ${endpointInfo.endpointName}.${endpointInfo.methodName}(${JSON.stringify(endpointInfo.params)}): ${message.message}`\n : `Error in unknown subscription: ${message.message}`,\n );\n }\n }\n } else {\n throw new Error(`Unknown message from server: ${String(message)}`);\n }\n }\n\n #removeSubscription(id: string) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED);\n this.#statusOfSubscriptions.delete(id);\n this.#onStateChangeCallbacks.delete(id);\n this.#onNextCallbacks.delete(id);\n this.#onCompleteCallbacks.delete(id);\n this.#onErrorCallbacks.delete(id);\n this.#endpointInfos.delete(id);\n }\n\n #send(message: ServerMessage) {\n if (this.state === State.INACTIVE || !this.#socket) {\n this.#pendingMessages.push(message);\n } else {\n this.#socket.push?.(JSON.stringify(message));\n }\n }\n\n #sendPendingMessages() {\n this.#pendingMessages.forEach((msg) => this.#send(msg));\n this.#pendingMessages = [];\n }\n}\n\nexport interface FluxConnection {\n addEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n removeEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n}\n"],"version":3}
|
package/index.js
CHANGED
|
@@ -6,7 +6,7 @@ export { ActionOnLostSubscription, FluxConnection, State } from "./FluxConnectio
|
|
|
6
6
|
vaadinObj.registrations ??= [];
|
|
7
7
|
vaadinObj.registrations.push({
|
|
8
8
|
is: feature ? `@vaadin/hilla-frontend/${feature}` : "@vaadin/hilla-frontend",
|
|
9
|
-
version: "24.8.0-
|
|
9
|
+
version: "24.8.0-beta3"
|
|
10
10
|
});
|
|
11
11
|
})();
|
|
12
12
|
//# sourceMappingURL=./index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAAA;AACA;AACA;AACA,SAAS,0BAA0B,gBAAgB;AAInD,CAAC,CAAC,SAAS,YAAa,WAAW,WAAW,CAAE,MAAM;AACpD,WAAU,kBAAkB,CAAE;AAC9B,WAAU,cAAc,KAAK;EAC3B,IAAI,WAAW,yBAAyB,QAAQ,IAAI;EACpD,SAAS;CACV,EAAC;AACH,IAAG","names":[],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/index.ts"],"sourcesContent":["export * from './Authentication.js';\nexport * from './Connect.js';\nexport * from './EndpointErrors.js';\nexport { ActionOnLostSubscription, FluxConnection, State } from './FluxConnection.js';\n\n// @ts-expect-error: esbuild injection\n// eslint-disable-next-line @typescript-eslint/no-unsafe-call\n((feature, vaadinObj = (globalThis.Vaadin ??= {})) => {\n vaadinObj.registrations ??= [];\n vaadinObj.registrations.push({\n is: feature ? `@vaadin/hilla-frontend/${feature}` : '@vaadin/hilla-frontend',\n version: '24.8.0-
|
|
1
|
+
{"mappings":"AAAA;AACA;AACA;AACA,SAAS,0BAA0B,gBAAgB;AAInD,CAAC,CAAC,SAAS,YAAa,WAAW,WAAW,CAAE,MAAM;AACpD,WAAU,kBAAkB,CAAE;AAC9B,WAAU,cAAc,KAAK;EAC3B,IAAI,WAAW,yBAAyB,QAAQ,IAAI;EACpD,SAAS;CACV,EAAC;AACH,IAAG","names":[],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/index.ts"],"sourcesContent":["export * from './Authentication.js';\nexport * from './Connect.js';\nexport * from './EndpointErrors.js';\nexport { ActionOnLostSubscription, FluxConnection, State } from './FluxConnection.js';\n\n// @ts-expect-error: esbuild injection\n// eslint-disable-next-line @typescript-eslint/no-unsafe-call\n((feature, vaadinObj = (globalThis.Vaadin ??= {})) => {\n vaadinObj.registrations ??= [];\n vaadinObj.registrations.push({\n is: feature ? `@vaadin/hilla-frontend/${feature}` : '@vaadin/hilla-frontend',\n version: '24.8.0-beta3',\n });\n})();\n"],"version":3}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vaadin/hilla-frontend",
|
|
3
|
-
"version": "24.8.0-
|
|
3
|
+
"version": "24.8.0-beta3",
|
|
4
4
|
"description": "Hilla core frontend utils",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"module": "index.js",
|
|
@@ -68,5 +68,10 @@
|
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
70
|
"lit": "^3.0.0"
|
|
71
|
-
}
|
|
71
|
+
},
|
|
72
|
+
"sideEffects": [
|
|
73
|
+
"./index.js",
|
|
74
|
+
"./Connect.js",
|
|
75
|
+
"./CsrfInfoSource.js"
|
|
76
|
+
]
|
|
72
77
|
}
|
package/utils.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VAADIN_BROWSER_ENVIRONMENT: boolean;
|
package/utils.js
ADDED
package/utils.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"mappings":"AAGA,OAAO,MAAMA,6BAAsC,WAAW,aAAa","names":["VAADIN_BROWSER_ENVIRONMENT: boolean"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/utils.ts"],"sourcesContent":["/// <reference lib=\"webworker\" />\n\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nexport const VAADIN_BROWSER_ENVIRONMENT: boolean = globalThis.document !== undefined;\n"],"version":3}
|