@vaadin/hilla-frontend 25.0.0-alpha1 → 25.0.0-alpha10
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/Authentication.js.map +1 -1
- package/Connect.js.map +1 -1
- package/CookieManager.js.map +1 -1
- package/CsrfInfoSource.js.map +1 -1
- package/EndpointErrors.js.map +1 -1
- package/FluxConnection.js.map +1 -1
- package/FluxMessages.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/utils.js.map +1 -1
package/Authentication.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AACA,OAAO,uCAAwC;AAC/C,OAAO,kBACL,oBACA,mBAEA,cACA,yBACA,+CAC2B;AAE7B,SAAS,cAAcA,eAA+E;CACpG,MAAM,UAAU,IAAI;AACpB,MAAK,MAAM,CAAC,MAAM,MAAM,IAAI,eAAe;AACzC,UAAQ,OAAO,MAAM,MAAM;CAC5B;AACD,QAAO;AACR;AAED,MAAM,kBAAkB;AAExB,eAAe,4BAA4BC,MAAiC;CAC1E,MAAM,MAAM,IAAI,YAAY,gBAAgB,MAAM,YAAY;AAC9D,QAAO,wBAAwB,IAAI;AACpC;AAED,eAAe,gCAAgCC,UAAmC;CAChF,MAAM,eAAe,MAAM,SAAS,MAAM;CAC1C,MAAM,WAAW,MAAM,4BAA4B,aAAa;AAChE,oBAAmB,UAAU,SAAS;AACvC;AAED,eAAe,cACbC,WACAH,eACA;CACA,MAAM,UAAU,cAAc,cAAc;CAC5C,MAAM,WAAW,MAAM,MAAM,WAAW;EAAE;EAAS,QAAQ;CAAQ,EAAC;AACpE,MAAK,SAAS,IAAI;AAChB,QAAM,IAAI,OAAO,iCAAiC,SAAS,OAAO;CACnE;AAED,OAAM,gCAAgC,SAAS;AAC/C,gBAAe,OAAO;AAEtB,QAAO;AACR;AAED,eAAe,aACbI,KACAC,iBACe;CACf,MAAM,mBAAmB,QAAQ,WAAW,M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Y,OAAO;AACrB,kBAAc,QAAQ,QAAQ,IAAI,oBAAoB,YAAY,MAAM;AACxE,WAAO,KAAK,cAAc;GAC3B;EACF;AACD,SAAO;CACR;AACF","names":["headerEntries: ReadonlyArray<readonly [name: string, value: string]>","body: string","response: Response","logoutUrl: URL | string","url: URL | string","formDataEntries: ReadonlyArray<readonly [name: string, value: string]>","doc: Document","options?: LogoutOptions","url: string","to: string","username: string","password: string","options?: LoginOptions","e: unknown","response: Response | undefined","onInvalidSessionCallback: OnInvalidSessionCallback","context: MiddlewareContext","next: MiddlewareNext"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/Authentication.ts"],"sourcesContent":["import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from './Connect.js';\nimport CookieManager from './CookieManager.js';\nimport csrfInfoSource, {\n VAADIN_CSRF_HEADER,\n clearCsrfInfoMeta,\n type CsrfInfo,\n CsrfInfoType,\n extractCsrfInfoFromMeta,\n updateCsrfInfoMeta,\n} from './CsrfInfoSource.js';\n\nfunction createHeaders(headerEntries: ReadonlyArray<readonly [name: string, value: string]>): Headers {\n const headers = new Headers();\n for (const [name, value] of headerEntries) {\n headers.append(name, value);\n }\n return headers;\n}\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nasync function getCsrfInfoFromResponseBody(body: string): Promise<CsrfInfo> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return extractCsrfInfoFromMeta(doc);\n}\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<void> {\n const responseText = await response.text();\n const csrfInfo = await getCsrfInfoFromResponseBody(responseText);\n updateCsrfInfoMeta(csrfInfo, document);\n}\n\nasync function doFetchLogout(\n logoutUrl: URL | string,\n headerEntries: ReadonlyArray<readonly [name: string, value: string]>,\n) {\n const headers = createHeaders(headerEntries);\n const response = await fetch(logoutUrl, { headers, method: 'POST' });\n if (!response.ok) {\n throw new Error(`failed to logout with response ${response.status}`);\n }\n\n await updateCsrfTokensBasedOnResponse(response);\n csrfInfoSource.reset();\n\n return response;\n}\n\nasync function doFormLogout(\n url: URL | string,\n formDataEntries: ReadonlyArray<readonly [name: string, value: string]>,\n): Promise<void> {\n const logoutUrl = typeof url === 'string' ? url : url.toString();\n\n // Create form to send POST request\n const form = document.createElement('form');\n form.setAttribute('method', 'POST');\n form.setAttribute('action', logoutUrl);\n form.style.display = 'none';\n\n // Add data to form as hidden input fields\n for (const [name, value] of formDataEntries) {\n const input = document.createElement('input');\n input.setAttribute('type', 'hidden');\n input.setAttribute('name', name);\n input.setAttribute('value', value);\n\n form.appendChild(input);\n }\n\n // Append form to page and submit it to perform logout and redirect\n document.body.appendChild(form);\n\n // No code should run after a form submission, as it will navigate away.\n // The promise will reject after a long timeout to avoid executing code after\n // (old user code has a `reload` call that could happen before the form submission).\n return new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error('Form submission did not navigate away after 10 seconds.'));\n }, 10000);\n form.submit();\n });\n}\n\nasync function doLogout(doc: Document, options?: LogoutOptions): Promise<Response> {\n // performing fetch logout only makes sense if at least one of the 'navigate'\n // or 'onSuccess' is defined, otherwise we can just do a form logout:\n const shouldSubmitFormLogout = !options?.navigate && !options?.onSuccess;\n // this assumes the default Spring Security logout configuration (handler URL)\n const logoutUrl = options?.logoutUrl ?? 'logout';\n const csrfInfo = doc === document ? await csrfInfoSource.get() : await extractCsrfInfoFromMeta(doc);\n if (shouldSubmitFormLogout) {\n const formDataEntries = csrfInfo.type === CsrfInfoType.SPRING ? csrfInfo.formDataEntries : [];\n await doFormLogout(logoutUrl, formDataEntries);\n // This should never be reached, as form submission will navigate away\n return new Response(null, {\n status: 500,\n statusText: 'Form submission did not navigate away.',\n } as ResponseInit);\n }\n const headerEntries = csrfInfo.type === CsrfInfoType.SPRING ? csrfInfo.headerEntries : [];\n return await doFetchLogout(logoutUrl, headerEntries);\n}\n\nexport interface LoginResult {\n error: boolean;\n token?: string;\n errorTitle?: string;\n errorMessage?: string;\n redirectUrl?: string;\n defaultUrl?: string;\n}\n\nexport type SuccessCallback = () => Promise<void> | void;\n\nexport type NavigateFunction = (path: string) => void;\n\nexport interface LoginOptions {\n /**\n * The URL for login request, defaults to `/login`.\n */\n loginProcessingUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful login. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nexport interface LogoutOptions {\n /**\n * The URL for logout request, defaults to `/logout`.\n */\n logoutUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful logout. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nfunction normalizePath(url: string): string {\n // URL with context path\n const effectiveBaseURL = new URL('.', document.baseURI);\n const effectiveBaseURI = effectiveBaseURL.toString();\n\n let normalized = url;\n\n // Strip context path prefix\n if (normalized.startsWith(effectiveBaseURL.pathname)) {\n return `/${normalized.slice(effectiveBaseURL.pathname.length)}`;\n }\n\n // Strip base URI\n normalized = normalized.startsWith(effectiveBaseURI) ? `/${normalized.slice(effectiveBaseURI.length)}` : normalized;\n\n return normalized;\n}\n\n/**\n * Navigates to the provided path using page reload.\n *\n * @param to - navigation target path\n */\nfunction navigateWithPageReload(to: string) {\n // Consider absolute path to be within application context\n const url = to.startsWith('/') ? new URL(`.${to}`, document.baseURI) : to;\n window.location.replace(url);\n}\n\n/**\n * A helper method for Spring Security based form login.\n * @param username - username\n * @param password - password\n * @param options - defines additional options, e.g, the loginProcessingUrl etc.\n */\nexport async function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult> {\n try {\n const data = new FormData();\n data.append('username', username);\n data.append('password', password);\n\n const loginProcessingUrl = options?.loginProcessingUrl ?? 'login';\n const csrfInfo = await csrfInfoSource.get();\n const headers = createHeaders(csrfInfo.headerEntries);\n headers.append('source', 'typescript');\n const response = await fetch(loginProcessingUrl, {\n body: data,\n headers,\n method: 'POST',\n });\n\n // This code assumes that a VaadinSavedRequestAwareAuthenticationSuccessHandler is used on the server side,\n // setting these header values based on the \"source=typescript\" header set above\n\n const result = response.headers.get('Result');\n const savedUrl = response.headers.get('Saved-url') ?? undefined;\n const defaultUrl = response.headers.get('Default-url') ?? undefined;\n const loginSuccessful = response.ok && result === 'success';\n\n if (loginSuccessful) {\n const springCsrfHeader = response.headers.get('Spring-CSRF-header') ?? undefined;\n const springCsrfToken = response.headers.get('Spring-CSRF-token') ?? undefined;\n if (springCsrfHeader && springCsrfToken) {\n updateCsrfInfoMeta(\n {\n headerEntries: [[springCsrfHeader, springCsrfToken]],\n formDataEntries: [],\n type: CsrfInfoType.SPRING,\n timestamp: Date.now(),\n },\n document,\n );\n csrfInfoSource.reset();\n }\n\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n\n const url = savedUrl ?? defaultUrl ?? document.baseURI;\n const toPath = normalizePath(url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n\n return {\n defaultUrl,\n error: false,\n redirectUrl: savedUrl,\n };\n }\n return {\n error: true,\n errorMessage: 'Check that you have entered the correct username and password and try again.',\n errorTitle: 'Incorrect username or password.',\n };\n } catch (e: unknown) {\n if (e instanceof Error) {\n return {\n error: true,\n errorMessage: e.message,\n errorTitle: e.name,\n };\n }\n\n throw e;\n }\n}\n\n/**\n * A helper method for Spring Security based form logout\n * @param options - defines additional options, e.g, the logoutUrl.\n */\nexport async function logout(options?: LogoutOptions): Promise<void> {\n let response: Response | undefined;\n try {\n response = await doLogout(document, options);\n } catch {\n try {\n const noCacheResponse = await fetch('?nocache');\n const responseText = await noCacheResponse.text();\n const doc = new DOMParser().parseFromString(responseText, 'text/html');\n response = await doLogout(doc, options);\n } catch (error) {\n // clear the token if the call fails\n clearCsrfInfoMeta(document);\n csrfInfoSource.reset();\n throw error;\n }\n } finally {\n CookieManager.remove(JWT_COOKIE_NAME);\n if (response && response.ok && response.redirected) {\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n const toPath = normalizePath(response.url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n }\n }\n}\n\n/**\n * It defines what to do when it detects a session is invalid. E.g.,\n * show a login view.\n * It takes an <code>EndpointCallContinue</code> parameter, which can be\n * used to continue the endpoint call.\n */\nexport type OnInvalidSessionCallback = () => Promise<LoginResult>;\n\n/**\n * A helper class for handling invalid sessions during an endpoint call.\n * E.g., you can use this to show user a login page when the session has\n * expired.\n */\nexport class InvalidSessionMiddleware implements MiddlewareClass {\n private readonly onInvalidSessionCallback: OnInvalidSessionCallback;\n\n constructor(onInvalidSessionCallback: OnInvalidSessionCallback) {\n this.onInvalidSessionCallback = onInvalidSessionCallback;\n }\n\n async invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const clonedContext = { ...context };\n clonedContext.request = context.request.clone();\n const response = await next(context);\n if (response.status === 401) {\n const loginResult = await this.onInvalidSessionCallback();\n if (loginResult.token) {\n clonedContext.request.headers.set(VAADIN_CSRF_HEADER, loginResult.token);\n return next(clonedContext) as Promise<Response>;\n }\n }\n return response;\n }\n}\n"],"version":3}
|
|
1
|
+
{"mappings":"AACA,OAAO,uCAAwC;AAC/C,OAAO,kBACL,oBACA,mBAEA,cACA,yBACA,+CAC2B;AAE7B,SAAS,cAAcA,eAA+E;CACpG,MAAM,UAAU,IAAI;AACpB,MAAK,MAAM,CAAC,MAAM,MAAM,IAAI,eAAe;AACzC,UAAQ,OAAO,MAAM,MAAM;CAC5B;AACD,QAAO;AACR;AAED,MAAM,kBAAkB;AAExB,eAAe,4BAA4BC,MAAiC;CAC1E,MAAM,MAAM,IAAI,YAAY,gBAAgB,MAAM,YAAY;AAC9D,QAAO,wBAAwB,IAAI;AACpC;AAED,eAAe,gCAAgCC,UAAmC;CAChF,MAAM,eAAe,MAAM,SAAS,MAAM;CAC1C,MAAM,WAAW,MAAM,4BAA4B,aAAa;AAChE,oBAAmB,UAAU,SAAS;AACvC;AAED,eAAe,cACbC,WACAH,eACA;CACA,MAAM,UAA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AEjB,YAAYC,0BAAoD;AAC9D,OAAK,2BAA2B;CACjC;CAED,MAAM,OAAOC,SAA4BC,MAAyC;EAChF,MAAM,gBAAgB,EAAE,GAAG,QAAS;AACpC,gBAAc,UAAU,QAAQ,QAAQ,OAAO;EAC/C,MAAM,WAAW,MAAM,KAAK,QAAQ;AACpC,MAAI,SAAS,WAAW,KAAK;GAC3B,MAAM,cAAc,MAAM,KAAK,0BAA0B;AACzD,OAAI,YAAY,OAAO;AACrB,kBAAc,QAAQ,QAAQ,IAAI,oBAAoB,YAAY,MAAM;AACxE,WAAO,KAAK,cAAc;GAC3B;EACF;AACD,SAAO;CACR;AACF","names":["headerEntries: ReadonlyArray<readonly [name: string, value: string]>","body: string","response: Response","logoutUrl: URL | string","url: URL | string","formDataEntries: ReadonlyArray<readonly [name: string, value: string]>","doc: Document","options?: LogoutOptions","url: string","to: string","username: string","password: string","options?: LoginOptions","e: unknown","response: Response | undefined","onInvalidSessionCallback: OnInvalidSessionCallback","context: MiddlewareContext","next: MiddlewareNext"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/Authentication.ts"],"sourcesContent":["import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from './Connect.js';\nimport CookieManager from './CookieManager.js';\nimport csrfInfoSource, {\n VAADIN_CSRF_HEADER,\n clearCsrfInfoMeta,\n type CsrfInfo,\n CsrfInfoType,\n extractCsrfInfoFromMeta,\n updateCsrfInfoMeta,\n} from './CsrfInfoSource.js';\n\nfunction createHeaders(headerEntries: ReadonlyArray<readonly [name: string, value: string]>): Headers {\n const headers = new Headers();\n for (const [name, value] of headerEntries) {\n headers.append(name, value);\n }\n return headers;\n}\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nasync function getCsrfInfoFromResponseBody(body: string): Promise<CsrfInfo> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return extractCsrfInfoFromMeta(doc);\n}\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<void> {\n const responseText = await response.text();\n const csrfInfo = await getCsrfInfoFromResponseBody(responseText);\n updateCsrfInfoMeta(csrfInfo, document);\n}\n\nasync function doFetchLogout(\n logoutUrl: URL | string,\n headerEntries: ReadonlyArray<readonly [name: string, value: string]>,\n) {\n const headers = createHeaders(headerEntries);\n const response = await fetch(logoutUrl, { headers, method: 'POST' });\n if (!response.ok) {\n throw new Error(`failed to logout with response ${response.status}`);\n }\n\n await updateCsrfTokensBasedOnResponse(response);\n csrfInfoSource.reset();\n\n return response;\n}\n\nasync function doFormLogout(\n url: URL | string,\n formDataEntries: ReadonlyArray<readonly [name: string, value: string]>,\n): Promise<void> {\n const logoutUrl = typeof url === 'string' ? url : url.toString();\n\n // Create form to send POST request\n const form = document.createElement('form');\n form.setAttribute('method', 'POST');\n form.setAttribute('action', logoutUrl);\n form.style.display = 'none';\n\n // Add data to form as hidden input fields\n for (const [name, value] of formDataEntries) {\n const input = document.createElement('input');\n input.setAttribute('type', 'hidden');\n input.setAttribute('name', name);\n input.setAttribute('value', value);\n\n form.appendChild(input);\n }\n\n // Append form to page and submit it to perform logout and redirect\n document.body.appendChild(form);\n\n // No code should run after a form submission, as it will navigate away.\n // The promise will reject after a long timeout to avoid executing code after\n // (old user code has a `reload` call that could happen before the form submission).\n return new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error('Form submission did not navigate away after 10 seconds.'));\n }, 10000);\n form.submit();\n });\n}\n\nasync function doLogout(doc: Document, options?: LogoutOptions): Promise<Response> {\n // performing fetch logout only makes sense if at least one of the 'navigate'\n // or 'onSuccess' is defined, otherwise we can just do a form logout:\n const shouldSubmitFormLogout = !options?.navigate && !options?.onSuccess;\n // this assumes the default Spring Security logout configuration (handler URL)\n const logoutUrl = options?.logoutUrl ?? 'logout';\n const csrfInfo = doc === document ? await csrfInfoSource.get() : await extractCsrfInfoFromMeta(doc);\n if (shouldSubmitFormLogout) {\n const formDataEntries = csrfInfo.type === CsrfInfoType.SPRING ? csrfInfo.formDataEntries : [];\n await doFormLogout(logoutUrl, formDataEntries);\n // This should never be reached, as form submission will navigate away\n return new Response(null, {\n status: 500,\n statusText: 'Form submission did not navigate away.',\n } as ResponseInit);\n }\n const headerEntries = csrfInfo.type === CsrfInfoType.SPRING ? csrfInfo.headerEntries : [];\n return await doFetchLogout(logoutUrl, headerEntries);\n}\n\nexport interface LoginResult {\n error: boolean;\n token?: string;\n errorTitle?: string;\n errorMessage?: string;\n redirectUrl?: string;\n defaultUrl?: string;\n}\n\nexport type SuccessCallback = () => Promise<void> | void;\n\nexport type NavigateFunction = (path: string) => void;\n\nexport interface LoginOptions {\n /**\n * The URL for login request, defaults to `/login`.\n */\n loginProcessingUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful login. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nexport interface LogoutOptions {\n /**\n * The URL for logout request, defaults to `/logout`.\n */\n logoutUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful logout. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nfunction normalizePath(url: string): string {\n // URL with context path\n const effectiveBaseURL = new URL('.', document.baseURI);\n const effectiveBaseURI = effectiveBaseURL.toString();\n\n let normalized = url;\n\n // Strip context path prefix\n if (normalized.startsWith(effectiveBaseURL.pathname)) {\n return `/${normalized.slice(effectiveBaseURL.pathname.length)}`;\n }\n\n // Strip base URI\n normalized = normalized.startsWith(effectiveBaseURI) ? `/${normalized.slice(effectiveBaseURI.length)}` : normalized;\n\n return normalized;\n}\n\n/**\n * Navigates to the provided path using page reload.\n *\n * @param to - navigation target path\n */\nfunction navigateWithPageReload(to: string) {\n // Consider absolute path to be within application context\n const url = to.startsWith('/') ? new URL(`.${to}`, document.baseURI) : to;\n window.location.replace(url);\n}\n\n/**\n * A helper method for Spring Security based form login.\n * @param username - username\n * @param password - password\n * @param options - defines additional options, e.g, the loginProcessingUrl etc.\n */\nexport async function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult> {\n try {\n const data = new FormData();\n data.append('username', username);\n data.append('password', password);\n\n const loginProcessingUrl = options?.loginProcessingUrl ?? 'login';\n const csrfInfo = await csrfInfoSource.get();\n const headers = createHeaders(csrfInfo.headerEntries);\n headers.append('source', 'typescript');\n const response = await fetch(loginProcessingUrl, {\n body: data,\n headers,\n method: 'POST',\n });\n\n // This code assumes that a VaadinSavedRequestAwareAuthenticationSuccessHandler is used on the server side,\n // setting these header values based on the \"source=typescript\" header set above\n\n const result = response.headers.get('Result');\n const savedUrl = response.headers.get('Saved-url') ?? undefined;\n const defaultUrl = response.headers.get('Default-url') ?? undefined;\n const loginSuccessful = response.ok && result === 'success';\n\n if (loginSuccessful) {\n const springCsrfHeader = response.headers.get('Spring-CSRF-header') ?? undefined;\n const springCsrfToken = response.headers.get('Spring-CSRF-token') ?? undefined;\n if (springCsrfHeader && springCsrfToken) {\n updateCsrfInfoMeta(\n {\n headerEntries: [[springCsrfHeader, springCsrfToken]],\n formDataEntries: [],\n type: CsrfInfoType.SPRING,\n timestamp: Date.now(),\n },\n document,\n );\n csrfInfoSource.reset();\n }\n\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n\n const url = savedUrl ?? defaultUrl ?? document.baseURI;\n const toPath = normalizePath(url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n\n return {\n defaultUrl,\n error: false,\n redirectUrl: savedUrl,\n };\n }\n return {\n error: true,\n errorMessage: 'Check that you have entered the correct username and password and try again.',\n errorTitle: 'Incorrect username or password.',\n };\n } catch (e: unknown) {\n if (e instanceof Error) {\n return {\n error: true,\n errorMessage: e.message,\n errorTitle: e.name,\n };\n }\n\n throw e;\n }\n}\n\n/**\n * A helper method for Spring Security based form logout\n * @param options - defines additional options, e.g, the logoutUrl.\n */\nexport async function logout(options?: LogoutOptions): Promise<void> {\n let response: Response | undefined;\n try {\n response = await doLogout(document, options);\n } catch {\n try {\n const noCacheResponse = await fetch('?nocache');\n const responseText = await noCacheResponse.text();\n const doc = new DOMParser().parseFromString(responseText, 'text/html');\n response = await doLogout(doc, options);\n } catch (error) {\n // clear the token if the call fails\n clearCsrfInfoMeta(document);\n csrfInfoSource.reset();\n throw error;\n }\n } finally {\n CookieManager.remove(JWT_COOKIE_NAME);\n if (response && response.ok && response.redirected) {\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n const toPath = normalizePath(response.url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n }\n }\n}\n\n/**\n * It defines what to do when it detects a session is invalid. E.g.,\n * show a login view.\n * It takes an <code>EndpointCallContinue</code> parameter, which can be\n * used to continue the endpoint call.\n */\nexport type OnInvalidSessionCallback = () => Promise<LoginResult>;\n\n/**\n * A helper class for handling invalid sessions during an endpoint call.\n * E.g., you can use this to show user a login page when the session has\n * expired.\n */\nexport class InvalidSessionMiddleware implements MiddlewareClass {\n private readonly onInvalidSessionCallback: OnInvalidSessionCallback;\n\n constructor(onInvalidSessionCallback: OnInvalidSessionCallback) {\n this.onInvalidSessionCallback = onInvalidSessionCallback;\n }\n\n async invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const clonedContext = { ...context };\n clonedContext.request = context.request.clone();\n const response = await next(context);\n if (response.status === 401) {\n const loginResult = await this.onInvalidSessionCallback();\n if (loginResult.token) {\n clonedContext.request.headers.set(VAADIN_CSRF_HEADER, loginResult.token);\n return next(clonedContext) as Promise<Response>;\n }\n }\n return response;\n }\n}\n"],"version":3}
|
package/Connect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AACA,OAAO,yCAA0C;AACjD,SACE,eACA,uBACA,yBACA,wBACA,sDAE2B;AAC7B,SAEE,2CAE2B;AAG7B,MAAM,OAAO;AAEb,KAAK,WAAW,CAAE;AAClB,KAAK,OAAO,kBAAkB,CAAE;AAChC,KAAK,OAAO,cAAc,KAAK,EAC7B,IAAI,WACL,EAAC;AAE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AAO,MAAO;GAClF;EACF;EAED,MAAM,UAAU,IAAI,SAAS,EAAE,KAAK,OAAO,GAAG,SAAS,GAAG,OAAO,GAAG;GAClE;GACA;GACA,QAAQ;EACT;EAID,MAAMC,iBAAoC;GACxC;GACA;GACA;GACA;EACD;EAMD,eAAe,0BAA0BC,SAA4BC,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;AACF","names":["response: Response","errorJson: ConnectExceptionData | 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 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\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\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\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"],"version":3}
|
|
1
|
+
{"mappings":"AACA,OAAO,yCAA0C;AACjD,SACE,eACA,uBACA,yBACA,wBACA,sDAE2B;AAC7B,SAEE,2CAE2B;AAG7B,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;;;;;;;AAoFD,SAAS,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iB,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;AACF","names":["response: Response","errorJson: ConnectExceptionData | 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/649c11185a3798db/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';\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\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\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"],"version":3}
|
package/CookieManager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,EAC3D,MAAM;;CAEJ,WAAW,WAAW,IAAI,IAAI,WAAW,SAAS,WAAW,IAAI,IAAI,KAAK,WAAW,SAAS;CAC/F,CACF,EAAC;AAEF,eAAe","names":["CookieManager: typeof Cookies"],"sources":["/opt/agent/work/
|
|
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,EAC3D,MAAM;;CAEJ,WAAW,WAAW,IAAI,IAAI,WAAW,SAAS,WAAW,IAAI,IAAI,KAAK,WAAW,SAAS;CAC/F,CACF,EAAC;AAEF,eAAe","names":["CookieManager: typeof Cookies"],"sources":["/opt/agent/work/649c11185a3798db/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 path: calculatePath(\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n globalThis.document ? new URL(globalThis.document.baseURI) : new URL('.', globalThis.location.href),\n ),\n});\n\nexport default CookieManager;\n"],"version":3}
|
package/CsrfInfoSource.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;A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AAK;CACvD;CAED,MAAM,MAAyB;AAC7B,SAAO,KAAKU;CACb;CAED,QAAc;AACZ,OAAKH,uBAAuB;AAC5B,OAAK,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\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}
|
|
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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C7C,UAAQ,yCAAyC,KAAK;CACvD;CAED,MAAM,MAAyB;AAC7B,SAAO,KAAKU;CACb;CAED,QAAc;AACZ,OAAKH,uBAAuB;AAC5B,OAAK,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/649c11185a3798db/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/EndpointErrors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":";;;;AAIA,OAAO,MAAM,sBAAsB,MAAM;;;;;CAKvC;;;;CAIA;;;;;;CAOA,YAAYA,SAAiBC,MAAeC,QAAkB;AAC5D,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;CACf;AACF;;;;;;AAOD,OAAO,MAAM,gCAAgC,cAAc;;;;CAIzD;;;;CAIA;;;;;;CAOA,YAAYF,SAAiBG,qBAA4CF,MAAe;AACtF,QAAM,SAAS,MAAM,oBAAoB;AACzC,OAAK,yBAAyB;AAC9B,OAAK,SAAS;AACd,OAAK,sBAAsB;CAC5B;AACF;;;;AAKD,OAAO,MAAM,8BAA8B,cAAc;;;;CAIvD;;;;;CAMA,YAAYD,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,yBAAyB,SAAS;AACjD,OAAK,WAAW;CACjB;;;;CAKD,IAAI,SAAiB;AACnB,SAAO,KAAK,SAAS;CACtB;AACF;AAED,OAAO,MAAM,kCAAkC,sBAAsB;CACnE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;AAED,OAAO,MAAM,+BAA+B,sBAAsB;CAChE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;;;;AAKD,OAAO,MAAM,oBAAoB;;;;CAI/B;;;;CAKA;;;;CAKA;;;;;;CAOA,YAAYJ,SAAiBK,eAAwBC,kBAA2B;AAC9E,OAAK,UAAU;AACf,OAAK,gBAAgB;AACrB,OAAK,mBAAmB;CACzB;AACF","names":["message: string","type?: string","detail?: unknown","validationErrorData: ValidationErrorData[]","response: Response","parameterName?: string","validatorMessage?: string"],"sources":["/opt/agent/work/
|
|
1
|
+
{"mappings":";;;;AAIA,OAAO,MAAM,sBAAsB,MAAM;;;;;CAKvC;;;;CAIA;;;;;;CAOA,YAAYA,SAAiBC,MAAeC,QAAkB;AAC5D,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;CACf;AACF;;;;;;AAOD,OAAO,MAAM,gCAAgC,cAAc;;;;CAIzD;;;;CAIA;;;;;;CAOA,YAAYF,SAAiBG,qBAA4CF,MAAe;AACtF,QAAM,SAAS,MAAM,oBAAoB;AACzC,OAAK,yBAAyB;AAC9B,OAAK,SAAS;AACd,OAAK,sBAAsB;CAC5B;AACF;;;;AAKD,OAAO,MAAM,8BAA8B,cAAc;;;;CAIvD;;;;;CAMA,YAAYD,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,yBAAyB,SAAS;AACjD,OAAK,WAAW;CACjB;;;;CAKD,IAAI,SAAiB;AACnB,SAAO,KAAK,SAAS;CACtB;AACF;AAED,OAAO,MAAM,kCAAkC,sBAAsB;CACnE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;AAED,OAAO,MAAM,+BAA+B,sBAAsB;CAChE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;;;;AAKD,OAAO,MAAM,oBAAoB;;;;CAI/B;;;;CAKA;;;;CAKA;;;;;;CAOA,YAAYJ,SAAiBK,eAAwBC,kBAA2B;AAC9E,OAAK,UAAU;AACf,OAAK,gBAAgB;AACrB,OAAK,mBAAmB;CACzB;AACF","names":["message: string","type?: string","detail?: unknown","validationErrorData: ValidationErrorData[]","response: Response","parameterName?: string","validatorMessage?: string"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/EndpointErrors.ts"],"sourcesContent":["/**\n * An exception that gets thrown when the Vaadin backend responds\n * with not ok status.\n */\nexport class EndpointError extends Error {\n /**\n * The optional detail object, containing additional information sent\n * from the backend\n */\n detail?: unknown;\n /**\n * The optional name of the exception that was thrown on a backend\n */\n type?: string;\n\n /**\n * @param message - the `message` property value\n * @param type - the `type` property value\n * @param detail - the `detail` property value\n */\n constructor(message: string, type?: string, detail?: unknown) {\n super(message);\n this.type = type;\n this.detail = detail;\n }\n}\n\n/**\n * An exception that gets thrown if Vaadin endpoint responds\n * with non-ok status and provides additional info\n * on the validation errors occurred.\n */\nexport class EndpointValidationError extends EndpointError {\n /**\n * An array of the validation errors.\n */\n validationErrorData: ValidationErrorData[];\n /**\n * An original validation error message.\n */\n validationErrorMessage: string;\n\n /**\n * @param message - the `message` property value\n * @param validationErrorData - the `validationErrorData` property value\n * @param type - the `type` property value\n */\n constructor(message: string, validationErrorData: ValidationErrorData[], type?: string) {\n super(message, type, validationErrorData);\n this.validationErrorMessage = message;\n this.detail = null;\n this.validationErrorData = validationErrorData;\n }\n}\n\n/**\n * An exception that gets thrown for unexpected HTTP response.\n */\nexport class EndpointResponseError extends EndpointError {\n /**\n * The optional response object, containing the HTTP response error\n */\n response: Response;\n\n /**\n * @param message - the `message` property value\n * @param response - the `response` property value\n */\n constructor(message: string, response: Response) {\n super(message, 'EndpointResponseError', response);\n this.response = response;\n }\n\n /**\n * Convenience property to get the HTTP code status directly\n */\n get status(): number {\n return this.response.status;\n }\n}\n\nexport class UnauthorizedResponseError extends EndpointResponseError {\n constructor(message: string, response: Response) {\n super(message, response);\n this.type = 'UnauthorizedResponseError';\n }\n}\n\nexport class ForbiddenResponseError extends EndpointResponseError {\n constructor(message: string, response: Response) {\n super(message, response);\n this.type = 'ForbiddenResponseError';\n }\n}\n\n/**\n * An object, containing all data for the particular validation error.\n */\nexport class ValidationErrorData {\n /**\n * The validation error message.\n */\n message: string;\n\n /**\n * The parameter name that caused the validation error.\n */\n parameterName?: string;\n\n /**\n * Validator original message\n */\n validatorMessage?: string;\n\n /**\n * @param message - The `message` property value\n * @param parameterName - The `parameterName` property value\n * @param validatorMessage - The `validatorMessage` property value\n */\n constructor(message: string, parameterName?: string, validatorMessage?: string) {\n this.message = message;\n this.parameterName = parameterName;\n this.validatorMessage = validatorMessage;\n }\n}\n"],"version":3}
|
package/FluxConnection.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,MA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ACZ,cAAS,QAAQ,QAAQ;IAC1B;AACD,SAAKW,oBAAoB,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,MAAMoC,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,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}
|
|
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;KACtB,EAAC;IACH,OAAM;AACL,iBAAY,KAAK,GAAG;IACrB;GACF,EAAC;AACF,eAAY,QAAQ,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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/649c11185a3798db/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/FluxMessages.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAmBA,OAAO,SAAS,gBAAgBA,OAAwC;AACtE,QAAO,SAAS,eAAe,UAAU,YAAY,WAAW;AACjE","names":["value: unknown"],"sources":["/opt/agent/work/
|
|
1
|
+
{"mappings":"AAmBA,OAAO,SAAS,gBAAgBA,OAAwC;AACtE,QAAO,SAAS,eAAe,UAAU,YAAY,WAAW;AACjE","names":["value: unknown"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/FluxMessages.ts"],"sourcesContent":["export interface AbstractMessage {\n '@type': string;\n id: string;\n}\n\nexport interface ClientErrorMessage extends AbstractMessage {\n '@type': 'error';\n message: string;\n}\nexport interface ClientCompleteMessage extends AbstractMessage {\n '@type': 'complete';\n}\nexport interface ClientUpdateMessage extends AbstractMessage {\n '@type': 'update';\n item: any;\n}\n\nexport type ClientMessage = ClientCompleteMessage | ClientErrorMessage | ClientUpdateMessage;\n\nexport function isClientMessage(value: unknown): value is ClientMessage {\n return value != null && typeof value === 'object' && '@type' in value;\n}\n\nexport interface ServerConnectMessage extends AbstractMessage {\n id: string;\n '@type': 'subscribe';\n endpointName: string;\n methodName: string;\n params?: any;\n}\nexport interface ServerCloseMessage extends AbstractMessage {\n id: string;\n '@type': 'unsubscribe';\n}\n\nexport type ServerMessage = ServerCloseMessage | ServerConnectMessage;\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: "25.0.0-
|
|
9
|
+
version: "25.0.0-alpha10"
|
|
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/
|
|
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/649c11185a3798db/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: '25.0.0-alpha10',\n });\n})();\n"],"version":3}
|
package/package.json
CHANGED
package/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAGA,OAAO,MAAMA,6BAAsC,WAAW,aAAa","names":["VAADIN_BROWSER_ENVIRONMENT: boolean"],"sources":["/opt/agent/work/
|
|
1
|
+
{"mappings":"AAGA,OAAO,MAAMA,6BAAsC,WAAW,aAAa","names":["VAADIN_BROWSER_ENVIRONMENT: boolean"],"sources":["/opt/agent/work/649c11185a3798db/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}
|