@vaadin/hilla-frontend 24.7.14 → 24.7.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"mappings":"AACA,OAAO,uCAAwC;AAC/C,SACE,mBACA,yCACA,4CACA,0CACsB;AAExB,MAAM,kBAAkB;AAExB,SAAS,mCAAmCA,MAAsC;CAChF,MAAM,MAAM,IAAI,YAAY,gBAAgB,MAAM,YAAY;AAC9D,QAAO,kBAAkB,IAAI;AAC9B;AAED,SAAS,0BAA0B;AACjC,OAAM,KACJ,SAAS,KAAK,iBAAiB,oFAA8E,CAC9G,CAAC,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;AAC/B;AAED,SAAS,yBAAyBC,gBAAwC;AACxE,0BAAyB;CACzB,MAAMC,iBAAkC,SAAS,cAAc,OAAO;AACtE,gBAAe,OAAO;AACtB,gBAAe,UAAU,eAAe;AACxC,UAAS,KAAK,YAAY,eAAe;CACzC,MAAMC,YAA6B,SAAS,cAAc,OAAO;AACjE,WAAU,OAAO;AACjB,WAAU,UAAU,eAAe;AACnC,UAAS,KAAK,YAAY,UAAU;AACrC;AAED,MAAM,qCAAqC,CAACH,SAAqC;CAC/E,MAAM,QAAQ,6EAA6E,KAAK,KAAK;AACrG,QAAO,QAAQ,MAAM,KAAK;AAC3B;AAED,eAAe,gCAAgCI,UAAiD;CAC9F,MAAM,eAAe,MAAM,SAAS,MAAM;CAC1C,MAAM,QAAQ,mCAAmC,aAAa;CAC9D,MAAM,sBAAsB,mCAAmC,aAAa;AAC5E,0BAAyB,oBAAoB;AAE7C,QAAO;AACR;AAED,eAAe,cAAcC,WAAyBC,SAAiC;CACrF,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;AAE/C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ACF","names":["body: string","springCsrfInfo: Record<string, string>","headerNameMeta: HTMLMetaElement","tokenMeta: HTMLMetaElement","response: Response","logoutUrl: URL | string","headers: Record<string, string>","url: URL | string","parameters: Record<string, string>","doc: Document","options?: LogoutOptions","url: string","to: string","username: string","password: string","options?: LoginOptions","springCsrfTokenInfo: Record<string, string>","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 {\n getSpringCsrfInfo,\n getSpringCsrfTokenHeadersForAuthRequest,\n getSpringCsrfTokenParametersForAuthRequest,\n VAADIN_CSRF_HEADER,\n} from './CsrfUtils.js';\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nfunction getSpringCsrfTokenFromResponseBody(body: string): Record<string, string> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return getSpringCsrfInfo(doc);\n}\n\nfunction clearSpringCsrfMetaTags() {\n Array.from(\n document.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"], meta[name=\"_csrf_parameter\"]'),\n ).forEach((el) => el.remove());\n}\n\nfunction updateSpringCsrfMetaTags(springCsrfInfo: Record<string, string>) {\n clearSpringCsrfMetaTags();\n const headerNameMeta: HTMLMetaElement = document.createElement('meta');\n headerNameMeta.name = '_csrf_header';\n headerNameMeta.content = springCsrfInfo._csrf_header;\n document.head.appendChild(headerNameMeta);\n const tokenMeta: HTMLMetaElement = document.createElement('meta');\n tokenMeta.name = '_csrf';\n tokenMeta.content = springCsrfInfo._csrf;\n document.head.appendChild(tokenMeta);\n}\n\nconst getVaadinCsrfTokenFromResponseBody = (body: string): string | undefined => {\n const match = /window\\.Vaadin = \\{TypeScript: \\{\"csrfToken\":\"([0-9a-zA-Z\\\\-]{36})\"\\}\\};/iu.exec(body);\n return match ? match[1] : undefined;\n};\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<string | undefined> {\n const responseText = await response.text();\n const token = getVaadinCsrfTokenFromResponseBody(responseText);\n const springCsrfTokenInfo = getSpringCsrfTokenFromResponseBody(responseText);\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n\n return token;\n}\n\nasync function doFetchLogout(logoutUrl: URL | string, headers: Record<string, string>) {\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\n return response;\n}\n\nasync function doFormLogout(url: URL | string, parameters: Record<string, string>): 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 Object.entries(parameters)) {\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 if (shouldSubmitFormLogout) {\n const parameters = getSpringCsrfTokenParametersForAuthRequest(doc);\n await doFormLogout(logoutUrl, parameters);\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 headers = getSpringCsrfTokenHeadersForAuthRequest(doc);\n return await doFetchLogout(logoutUrl, headers);\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 headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n headers.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 vaadinCsrfToken = response.headers.get('Vaadin-CSRF') ?? undefined;\n\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 const springCsrfTokenInfo: Record<string, string> = {};\n springCsrfTokenInfo._csrf = springCsrfToken;\n // eslint-disable-next-line camelcase\n springCsrfTokenInfo._csrf_header = springCsrfHeader;\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\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 token: vaadinCsrfToken,\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 clearSpringCsrfMetaTags();\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,SACE,mBACA,yCACA,4CACA,0CACsB;AAExB,MAAM,kBAAkB;AAExB,SAAS,mCAAmCA,MAAsC;CAChF,MAAM,MAAM,IAAI,YAAY,gBAAgB,MAAM,YAAY;AAC9D,QAAO,kBAAkB,IAAI;AAC9B;AAED,SAAS,0BAA0B;AACjC,OAAM,KACJ,SAAS,KAAK,iBAAiB,oFAA8E,CAC9G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M;GACjD,MAAM,MAAM,IAAI,YAAY,gBAAgB,cAAc,YAAY;AACtE,cAAW,MAAM,SAAS,KAAK,QAAQ;EACxC,SAAQ,OAAO;AAEd,4BAAyB;AACzB,SAAM;EACP;CACF,UAAS;AACR,gBAAc,OAAO,gBAAgB;AACrC,MAAI,YAAY,SAAS,MAAM,SAAS,YAAY;AAClD,OAAI,SAAS,WAAW;AACtB,UAAM,QAAQ,WAAW;GAC1B;GACD,MAAM,SAAS,cAAc,SAAS,IAAI;GAC1C,MAAM,WAAW,SAAS,YAAY;AACtC,YAAS,OAAO;EACjB;CACF;AACF;;;;;;AAeD,OAAO,MAAM,yBAAoD;CAC/D,AAAiB;CAEjB,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":["body: string","springCsrfInfo: Record<string, string>","headerNameMeta: HTMLMetaElement","tokenMeta: HTMLMetaElement","response: Response","logoutUrl: URL | string","headers: Record<string, string>","url: URL | string","parameters: Record<string, string>","doc: Document","options?: LogoutOptions","url: string","to: string","username: string","password: string","options?: LoginOptions","springCsrfTokenInfo: Record<string, string>","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 {\n getSpringCsrfInfo,\n getSpringCsrfTokenHeadersForAuthRequest,\n getSpringCsrfTokenParametersForAuthRequest,\n VAADIN_CSRF_HEADER,\n} from './CsrfUtils.js';\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nfunction getSpringCsrfTokenFromResponseBody(body: string): Record<string, string> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return getSpringCsrfInfo(doc);\n}\n\nfunction clearSpringCsrfMetaTags() {\n Array.from(\n document.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"], meta[name=\"_csrf_parameter\"]'),\n ).forEach((el) => el.remove());\n}\n\nfunction updateSpringCsrfMetaTags(springCsrfInfo: Record<string, string>) {\n clearSpringCsrfMetaTags();\n const headerNameMeta: HTMLMetaElement = document.createElement('meta');\n headerNameMeta.name = '_csrf_header';\n headerNameMeta.content = springCsrfInfo._csrf_header;\n document.head.appendChild(headerNameMeta);\n const tokenMeta: HTMLMetaElement = document.createElement('meta');\n tokenMeta.name = '_csrf';\n tokenMeta.content = springCsrfInfo._csrf;\n document.head.appendChild(tokenMeta);\n}\n\nconst getVaadinCsrfTokenFromResponseBody = (body: string): string | undefined => {\n const match = /window\\.Vaadin = \\{TypeScript: \\{\"csrfToken\":\"([0-9a-zA-Z\\\\-]{36})\"\\}\\};/iu.exec(body);\n return match ? match[1] : undefined;\n};\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<string | undefined> {\n const responseText = await response.text();\n const token = getVaadinCsrfTokenFromResponseBody(responseText);\n const springCsrfTokenInfo = getSpringCsrfTokenFromResponseBody(responseText);\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n\n return token;\n}\n\nasync function doFetchLogout(logoutUrl: URL | string, headers: Record<string, string>) {\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\n return response;\n}\n\nasync function doFormLogout(url: URL | string, parameters: Record<string, string>): 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 Object.entries(parameters)) {\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 if (shouldSubmitFormLogout) {\n const parameters = getSpringCsrfTokenParametersForAuthRequest(doc);\n await doFormLogout(logoutUrl, parameters);\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 });\n }\n const headers = getSpringCsrfTokenHeadersForAuthRequest(doc);\n return await doFetchLogout(logoutUrl, headers);\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 headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n headers.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 vaadinCsrfToken = response.headers.get('Vaadin-CSRF') ?? undefined;\n\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 const springCsrfTokenInfo: Record<string, string> = {};\n springCsrfTokenInfo._csrf = springCsrfToken;\n // eslint-disable-next-line camelcase\n springCsrfTokenInfo._csrf_header = springCsrfHeader;\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\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 token: vaadinCsrfToken,\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 clearSpringCsrfMetaTags();\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);\n }\n }\n return response;\n }\n}\n"],"version":3}
package/Connect.js.map CHANGED
@@ -1 +1 @@
1
- {"mappings":"AACA,SAAS,qBAAqB,gDAAiD;AAC/E,SAAS,6DAA8D;AACvE,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;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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 { ConnectionIndicator, ConnectionState } from '@vaadin/common-frontend';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n EndpointError,\n EndpointResponseError,\n EndpointValidationError,\n ForbiddenResponseError,\n UnauthorizedResponseError,\n type ValidationErrorData,\n} from './EndpointErrors.js';\nimport {\n type ActionOnLostSubscription,\n FluxConnection,\n type FluxSubscriptionStateChangeEvent,\n} from './FluxConnection.js';\nimport type { VaadinGlobal } from './types.js';\n\nconst $wnd = globalThis as VaadinGlobal;\n\n$wnd.Vaadin ??= {};\n$wnd.Vaadin.registrations ??= [];\n$wnd.Vaadin.registrations.push({\n is: 'endpoint',\n});\n\nexport const BODY_PART_NAME = 'hilla_body_part';\n\nexport type MaybePromise<T> = Promise<T> | T;\n\n/**\n * Represents the connection to and endpoint returning a subscription rather than a value.\n */\nexport interface Subscription<T> {\n /** Cancels the subscription. No values are made available after calling this. */\n cancel(): void;\n\n /*\n * Binds to the given context (element) so that when the context is deactivated (element detached), the subscription is closed.\n */\n context(context: ReactiveControllerHost): Subscription<T>;\n\n /** Called when the subscription has completed. No values are made available after calling this. */\n onComplete(callback: () => void): Subscription<T>;\n\n /** Called when an exception occured in the subscription. */\n onError(callback: (message: string) => void): Subscription<T>;\n\n /** Called when a new value is available. */\n onNext(callback: (value: T) => void): Subscription<T>;\n\n /** Called when the subscription state changes. */\n onConnectionStateChange(callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<T>;\n\n /**\n * Called when the connection is restored, but there's no longer a valid subscription. If the callback returns\n * `ActionOnLostSubscription.RESUBSCRIBE`, the subscription will be re-established by connecting to the same\n * server method again. If the callback returns `ActionOnLostSubscription.REMOVE`, the subscription will be\n * forgotten. This is also the default behavior if the callback is not set or if it returns `undefined`.\n */\n onSubscriptionLost(callback: () => ActionOnLostSubscription | void): Subscription<T>;\n}\n\ninterface ConnectExceptionData {\n detail?: any;\n message: string;\n type: string;\n validationErrorData?: ValidationErrorData[];\n}\n\n/**\n * Throws a TypeError if the response is not 200 OK.\n * @param response - The response to assert.\n */\nconst assertResponseIsOk = async (response: Response): Promise<void> => {\n if (!response.ok) {\n const errorText = await response.text();\n let errorJson: ConnectExceptionData | null;\n try {\n errorJson = JSON.parse(errorText);\n } catch {\n // not a json\n errorJson = null;\n }\n\n const message =\n errorJson?.message ??\n (errorText.length > 0\n ? errorText\n : `expected \"200 OK\" response, but got ${response.status} ${response.statusText}`);\n const type = errorJson?.type;\n\n if (errorJson?.validationErrorData) {\n throw new EndpointValidationError(message, errorJson.validationErrorData, type);\n }\n\n if (type) {\n throw new EndpointError(message, type, errorJson?.detail);\n }\n\n switch (response.status) {\n case 401:\n throw new UnauthorizedResponseError(message, response);\n case 403:\n throw new ForbiddenResponseError(message, response);\n default:\n throw new EndpointResponseError(message, response);\n }\n }\n};\n\n/**\n * The `ConnectClient` constructor options.\n */\nexport interface ConnectClientOptions {\n /**\n * The `middlewares` property value.\n */\n middlewares?: Middleware[];\n /**\n * The `prefix` property value.\n */\n prefix?: string;\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions?: Partial<Atmosphere.Request>;\n}\n\nexport interface EndpointCallMetaInfo {\n /**\n * The endpoint name.\n */\n endpoint: string;\n\n /**\n * The method name to call on in the endpoint class.\n */\n method: string;\n\n /**\n * Optional object with method call arguments.\n */\n params?: Record<string, unknown>;\n}\n\n/**\n * An object with the call arguments and the related Request instance.\n * See also {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface MiddlewareContext extends EndpointCallMetaInfo {\n /**\n * The Fetch API Request object reflecting the other properties.\n */\n request: Request;\n}\n\n/**\n * An async middleware callback that invokes the next middleware in the chain\n * or makes the actual request.\n * @param context - The information about the call and request\n */\nexport type MiddlewareNext = (context: MiddlewareContext) => MaybePromise<Response>;\n\n/**\n * An interface that allows defining a middleware as a class.\n */\nexport interface MiddlewareClass {\n /**\n * @param context - The information about the call and request\n * @param next - Invokes the next in the call chain\n */\n invoke(context: MiddlewareContext, next: MiddlewareNext): MaybePromise<Response>;\n}\n\n/**\n * An async callback function that can intercept the request and response\n * of a call.\n */\nexport type MiddlewareFunction = (context: MiddlewareContext, next: MiddlewareNext) => MaybePromise<Response>;\n\n/**\n * An async callback that can intercept the request and response\n * of a call, could be either a function or a class.\n */\nexport type Middleware = MiddlewareClass | MiddlewareFunction;\n\nfunction isFlowLoaded(): boolean {\n return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;\n}\n\n/**\n * Extracts file objects from the object that is used to build the request body.\n *\n * @param obj - The object to extract files from.\n * @returns A tuple with the object without files and a map of files.\n */\nfunction extractFiles(obj: Record<string, unknown>): [Record<string, unknown>, Map<string, File>] {\n const fileMap = new Map<string, File>();\n\n function recursiveExtract(prop: unknown, path: string): unknown {\n if (prop !== null && typeof prop === 'object') {\n if (prop instanceof File) {\n fileMap.set(path, prop);\n return null;\n }\n if (Array.isArray(prop)) {\n return prop.map((item, index) => recursiveExtract(item, `${path}/${index}`));\n }\n return Object.entries(prop).reduce<Record<string, unknown>>((acc, [key, value]) => {\n const newPath = `${path}/${key}`;\n if (value instanceof File) {\n fileMap.set(newPath, value);\n } else {\n acc[key] = recursiveExtract(value, newPath);\n }\n return acc;\n }, {});\n }\n return prop;\n }\n\n return [recursiveExtract(obj, '') as Record<string, unknown>, fileMap];\n}\n\n/**\n * A list of parameters supported by {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface EndpointRequestInit {\n /**\n * An AbortSignal to set request's signal.\n */\n signal?: AbortSignal | null;\n /**\n * If set to true, the connection state will not be updated during the request.\n */\n mute?: boolean;\n}\n\n/**\n * A low-level network calling utility. It stores\n * a prefix and facilitates remote calls to endpoint class methods\n * on the Hilla backend.\n *\n * Example usage:\n *\n * ```js\n * const client = new ConnectClient();\n * const responseData = await client.call('MyEndpoint', 'myMethod');\n * ```\n *\n * ### Prefix\n *\n * The client supports an `prefix` constructor option:\n * ```js\n * const client = new ConnectClient({prefix: '/my-connect-prefix'});\n * ```\n *\n * The default prefix is '/connect'.\n *\n */\nexport class ConnectClient {\n /**\n * The array of middlewares that are invoked during a call.\n */\n middlewares: Middleware[] = [];\n /**\n * The Hilla endpoint prefix\n */\n prefix = '/connect';\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions: Partial<Atmosphere.Request> = {};\n\n #fluxConnection?: FluxConnection;\n\n /**\n * @param options - Constructor options.\n */\n constructor(options: ConnectClientOptions = {}) {\n if (options.prefix) {\n this.prefix = options.prefix;\n }\n\n if (options.middlewares) {\n this.middlewares = options.middlewares;\n }\n\n if (options.atmosphereOptions) {\n this.atmosphereOptions = options.atmosphereOptions;\n }\n\n // add connection indicator to DOM\n ConnectionIndicator.create();\n\n // Listen to browser online/offline events and update the loading indicator accordingly.\n // Note: if Flow.ts is loaded, it instead handles the state transitions.\n addEventListener('online', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;\n }\n });\n }\n\n /**\n * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint\n * methods.\n */\n get fluxConnection(): FluxConnection {\n if (!this.#fluxConnection) {\n this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);\n }\n return this.#fluxConnection;\n }\n\n /**\n * Calls the given endpoint method defined using the endpoint and method\n * parameters with the parameters given as params.\n * Asynchronously returns the parsed JSON response data.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @param init - Optional parameters for the request\n * @returns Decoded JSON response data.\n */\n async call(\n endpoint: string,\n method: string,\n params?: Record<string, unknown>,\n init?: EndpointRequestInit,\n ): Promise<any> {\n if (arguments.length < 2) {\n throw new TypeError(`2 arguments required, but got only ${arguments.length}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...csrfHeaders,\n };\n\n const [paramsWithoutFiles, files] = extractFiles(params ?? {});\n let body;\n\n if (files.size > 0) {\n // in this case params is not undefined, otherwise there would be no files\n body = new FormData();\n body.append(\n BODY_PART_NAME,\n JSON.stringify(paramsWithoutFiles, (_, value) => (value === undefined ? null : value)),\n );\n\n for (const [path, file] of files) {\n body.append(path, file);\n }\n } else {\n headers['Content-Type'] = 'application/json';\n if (params) {\n body = JSON.stringify(params, (_, value) => (value === undefined ? null : value));\n }\n }\n\n const request = new Request(`${this.prefix}/${endpoint}/${method}`, {\n body, // automatically sets Content-Type header\n headers,\n method: 'POST',\n });\n\n // The middleware `context`, includes the call arguments and the request\n // constructed from them\n const initialContext: MiddlewareContext = {\n endpoint,\n method,\n params,\n request,\n };\n\n // The internal middleware to assert and parse the response. The internal\n // response handling should come last after the other middlewares are done\n // with processing the response. That is why this middleware is first\n // in the final middlewares array.\n async function responseHandlerMiddleware(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const response = await next(context);\n await assertResponseIsOk(response);\n const text = await response.text();\n return JSON.parse(text, (_, value: any) => (value === null ? undefined : value));\n }\n\n // The actual fetch call itself is expressed as a middleware\n // chain item for our convenience. Always having an ending of the chain\n // this way makes the folding down below more concise.\n async function fetchNext(context: MiddlewareContext) {\n // if the request is not \"muted\", notify the connection state about changes\n const connectionState = init?.mute ? undefined : $wnd.Vaadin?.connectionState;\n connectionState?.loadingStarted();\n try {\n const response = await fetch(context.request, { signal: init?.signal });\n connectionState?.loadingFinished();\n return response;\n } catch (error: unknown) {\n // don't bother about connections aborted by purpose\n if (error instanceof Error && error.name === 'AbortError') {\n connectionState?.loadingFinished();\n } else {\n connectionState?.loadingFailed();\n }\n throw error;\n }\n }\n\n // Assemble the final middlewares array from internal\n // and external middlewares\n const middlewares = [responseHandlerMiddleware as Middleware, ...this.middlewares];\n\n // Fold the final middlewares array into a single function\n const chain = middlewares.reduceRight(\n (next: MiddlewareNext, middleware) =>\n // Compose and return the new chain step, that takes the context and\n // invokes the current middleware with the context and the further chain\n // as the next argument\n async (context) => {\n if (typeof middleware === 'function') {\n return middleware(context, next);\n }\n return middleware.invoke(context, next);\n },\n // Initialize reduceRight the accumulator with `fetchNext`\n fetchNext,\n );\n\n // Invoke all the folded async middlewares and return\n return chain(initialContext);\n }\n\n /**\n * Subscribes to the given method defined using the endpoint and method\n * parameters with the parameters given as params. The method must return a\n * compatible type such as a Flux.\n * Returns a subscription that is used to fetch values as they become available.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @returns A subscription used to handles values as they become available.\n */\n subscribe(endpoint: string, method: string, params?: any): Subscription<any> {\n return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);\n }\n}\n"],"version":3}
1
+ {"mappings":"AACA,SAAS,qBAAqB,gDAAiD;AAC/E,SAAS,6DAA8D;AACvE,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;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iC;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 { ConnectionIndicator, ConnectionState } from '@vaadin/common-frontend';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n EndpointError,\n EndpointResponseError,\n EndpointValidationError,\n ForbiddenResponseError,\n UnauthorizedResponseError,\n type ValidationErrorData,\n} from './EndpointErrors.js';\nimport {\n type ActionOnLostSubscription,\n FluxConnection,\n type FluxSubscriptionStateChangeEvent,\n} from './FluxConnection.js';\nimport type { VaadinGlobal } from './types.js';\n\nconst $wnd = globalThis as VaadinGlobal;\n\n$wnd.Vaadin ??= {};\n$wnd.Vaadin.registrations ??= [];\n$wnd.Vaadin.registrations.push({\n is: 'endpoint',\n});\n\nexport const BODY_PART_NAME = 'hilla_body_part';\n\nexport type MaybePromise<T> = Promise<T> | T;\n\n/**\n * Represents the connection to and endpoint returning a subscription rather than a value.\n */\nexport interface Subscription<T> {\n /** Cancels the subscription. No values are made available after calling this. */\n cancel(): void;\n\n /*\n * Binds to the given context (element) so that when the context is deactivated (element detached), the subscription is closed.\n */\n context(context: ReactiveControllerHost): Subscription<T>;\n\n /** Called when the subscription has completed. No values are made available after calling this. */\n onComplete(callback: () => void): Subscription<T>;\n\n /** Called when an exception occured in the subscription. */\n onError(callback: (message: string) => void): Subscription<T>;\n\n /** Called when a new value is available. */\n onNext(callback: (value: T) => void): Subscription<T>;\n\n /** Called when the subscription state changes. */\n onConnectionStateChange(callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<T>;\n\n /**\n * Called when the connection is restored, but there's no longer a valid subscription. If the callback returns\n * `ActionOnLostSubscription.RESUBSCRIBE`, the subscription will be re-established by connecting to the same\n * server method again. If the callback returns `ActionOnLostSubscription.REMOVE`, the subscription will be\n * forgotten. This is also the default behavior if the callback is not set or if it returns `undefined`.\n */\n onSubscriptionLost(callback: () => ActionOnLostSubscription | void): Subscription<T>;\n}\n\ninterface ConnectExceptionData {\n detail?: any;\n message: string;\n type: string;\n validationErrorData?: ValidationErrorData[];\n}\n\n/**\n * Throws a TypeError if the response is not 200 OK.\n * @param response - The response to assert.\n */\nconst assertResponseIsOk = async (response: Response): Promise<void> => {\n if (!response.ok) {\n const errorText = await response.text();\n let errorJson: ConnectExceptionData | null;\n try {\n errorJson = JSON.parse(errorText);\n } catch {\n // not a json\n errorJson = null;\n }\n\n const message =\n errorJson?.message ??\n (errorText.length > 0\n ? errorText\n : `expected \"200 OK\" response, but got ${response.status} ${response.statusText}`);\n const type = errorJson?.type;\n\n if (errorJson?.validationErrorData) {\n throw new EndpointValidationError(message, errorJson.validationErrorData, type);\n }\n\n if (type) {\n throw new EndpointError(message, type, errorJson?.detail);\n }\n\n switch (response.status) {\n case 401:\n throw new UnauthorizedResponseError(message, response);\n case 403:\n throw new ForbiddenResponseError(message, response);\n default:\n throw new EndpointResponseError(message, response);\n }\n }\n};\n\n/**\n * The `ConnectClient` constructor options.\n */\nexport interface ConnectClientOptions {\n /**\n * The `middlewares` property value.\n */\n middlewares?: Middleware[];\n /**\n * The `prefix` property value.\n */\n prefix?: string;\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions?: Partial<Atmosphere.Request>;\n}\n\nexport interface EndpointCallMetaInfo {\n /**\n * The endpoint name.\n */\n endpoint: string;\n\n /**\n * The method name to call on in the endpoint class.\n */\n method: string;\n\n /**\n * Optional object with method call arguments.\n */\n params?: Record<string, unknown>;\n}\n\n/**\n * An object with the call arguments and the related Request instance.\n * See also {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface MiddlewareContext extends EndpointCallMetaInfo {\n /**\n * The Fetch API Request object reflecting the other properties.\n */\n request: Request;\n}\n\n/**\n * An async middleware callback that invokes the next middleware in the chain\n * or makes the actual request.\n * @param context - The information about the call and request\n */\nexport type MiddlewareNext = (context: MiddlewareContext) => MaybePromise<Response>;\n\n/**\n * An interface that allows defining a middleware as a class.\n */\nexport interface MiddlewareClass {\n /**\n * @param context - The information about the call and request\n * @param next - Invokes the next in the call chain\n */\n invoke(context: MiddlewareContext, next: MiddlewareNext): MaybePromise<Response>;\n}\n\n/**\n * An async callback function that can intercept the request and response\n * of a call.\n */\nexport type MiddlewareFunction = (context: MiddlewareContext, next: MiddlewareNext) => MaybePromise<Response>;\n\n/**\n * An async callback that can intercept the request and response\n * of a call, could be either a function or a class.\n */\nexport type Middleware = MiddlewareClass | MiddlewareFunction;\n\nfunction isFlowLoaded(): boolean {\n return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;\n}\n\n/**\n * Extracts file objects from the object that is used to build the request body.\n *\n * @param obj - The object to extract files from.\n * @returns A tuple with the object without files and a map of files.\n */\nfunction extractFiles(obj: Record<string, unknown>): [Record<string, unknown>, Map<string, File>] {\n const fileMap = new Map<string, File>();\n\n function recursiveExtract(prop: unknown, path: string): unknown {\n if (prop !== null && typeof prop === 'object') {\n if (prop instanceof File) {\n fileMap.set(path, prop);\n return null;\n }\n if (Array.isArray(prop)) {\n return prop.map((item, index) => recursiveExtract(item, `${path}/${index}`));\n }\n return Object.entries(prop).reduce<Record<string, unknown>>((acc, [key, value]) => {\n const newPath = `${path}/${key}`;\n if (value instanceof File) {\n fileMap.set(newPath, value);\n } else {\n acc[key] = recursiveExtract(value, newPath);\n }\n return acc;\n }, {});\n }\n return prop;\n }\n\n return [recursiveExtract(obj, '') as Record<string, unknown>, fileMap];\n}\n\n/**\n * A list of parameters supported by {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface EndpointRequestInit {\n /**\n * An AbortSignal to set request's signal.\n */\n signal?: AbortSignal | null;\n /**\n * If set to true, the connection state will not be updated during the request.\n */\n mute?: boolean;\n}\n\n/**\n * A low-level network calling utility. It stores\n * a prefix and facilitates remote calls to endpoint class methods\n * on the Hilla backend.\n *\n * Example usage:\n *\n * ```js\n * const client = new ConnectClient();\n * const responseData = await client.call('MyEndpoint', 'myMethod');\n * ```\n *\n * ### Prefix\n *\n * The client supports an `prefix` constructor option:\n * ```js\n * const client = new ConnectClient({prefix: '/my-connect-prefix'});\n * ```\n *\n * The default prefix is '/connect'.\n *\n */\nexport class ConnectClient {\n /**\n * The array of middlewares that are invoked during a call.\n */\n middlewares: Middleware[] = [];\n /**\n * The Hilla endpoint prefix\n */\n prefix = '/connect';\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions: Partial<Atmosphere.Request> = {};\n\n #fluxConnection?: FluxConnection;\n\n /**\n * @param options - Constructor options.\n */\n constructor(options: ConnectClientOptions = {}) {\n if (options.prefix) {\n this.prefix = options.prefix;\n }\n\n if (options.middlewares) {\n this.middlewares = options.middlewares;\n }\n\n if (options.atmosphereOptions) {\n this.atmosphereOptions = options.atmosphereOptions;\n }\n\n // add connection indicator to DOM\n ConnectionIndicator.create();\n\n // Listen to browser online/offline events and update the loading indicator accordingly.\n // Note: if Flow.ts is loaded, it instead handles the state transitions.\n addEventListener('online', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;\n }\n });\n }\n\n /**\n * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint\n * methods.\n */\n get fluxConnection(): FluxConnection {\n if (!this.#fluxConnection) {\n this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);\n }\n return this.#fluxConnection;\n }\n\n /**\n * Calls the given endpoint method defined using the endpoint and method\n * parameters with the parameters given as params.\n * Asynchronously returns the parsed JSON response data.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @param init - Optional parameters for the request\n * @returns Decoded JSON response data.\n */\n async call(\n endpoint: string,\n method: string,\n params?: Record<string, unknown>,\n init?: EndpointRequestInit,\n ): Promise<any> {\n if (arguments.length < 2) {\n throw new TypeError(`2 arguments required, but got only ${arguments.length}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...csrfHeaders,\n };\n\n const [paramsWithoutFiles, files] = extractFiles(params ?? {});\n let body;\n\n if (files.size > 0) {\n // in this case params is not undefined, otherwise there would be no files\n body = new FormData();\n body.append(\n BODY_PART_NAME,\n JSON.stringify(paramsWithoutFiles, (_, value) => (value === undefined ? null : value)),\n );\n\n for (const [path, file] of files) {\n body.append(path, file);\n }\n } else {\n headers['Content-Type'] = 'application/json';\n if (params) {\n body = JSON.stringify(params, (_, value) => (value === undefined ? null : value));\n }\n }\n\n const request = new Request(`${this.prefix}/${endpoint}/${method}`, {\n body, // automatically sets Content-Type header\n headers,\n method: 'POST',\n });\n\n // The middleware `context`, includes the call arguments and the request\n // constructed from them\n const initialContext: MiddlewareContext = {\n endpoint,\n method,\n params,\n request,\n };\n\n // The internal middleware to assert and parse the response. The internal\n // response handling should come last after the other middlewares are done\n // with processing the response. That is why this middleware is first\n // in the final middlewares array.\n async function responseHandlerMiddleware(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const response = await next(context);\n await assertResponseIsOk(response);\n const text = await response.text();\n return JSON.parse(text, (_, value: any) => (value === null ? undefined : value));\n }\n\n // The actual fetch call itself is expressed as a middleware\n // chain item for our convenience. Always having an ending of the chain\n // this way makes the folding down below more concise.\n async function fetchNext(context: MiddlewareContext) {\n // if the request is not \"muted\", notify the connection state about changes\n const connectionState = init?.mute ? undefined : $wnd.Vaadin?.connectionState;\n connectionState?.loadingStarted();\n try {\n const response = await fetch(context.request, { signal: init?.signal });\n connectionState?.loadingFinished();\n return response;\n } catch (error: unknown) {\n // don't bother about connections aborted by purpose\n if (error instanceof Error && error.name === 'AbortError') {\n connectionState?.loadingFinished();\n } else {\n connectionState?.loadingFailed();\n }\n throw error;\n }\n }\n\n // Assemble the final middlewares array from internal\n // and external middlewares\n const middlewares = [responseHandlerMiddleware as Middleware, ...this.middlewares];\n\n // Fold the final middlewares array into a single function\n const chain = middlewares.reduceRight(\n (next: MiddlewareNext, middleware) =>\n // Compose and return the new chain step, that takes the context and\n // invokes the current middleware with the context and the further chain\n // as the next argument\n async (context) => {\n if (typeof middleware === 'function') {\n return middleware(context, next);\n }\n return middleware.invoke(context, next);\n },\n // Initialize reduceRight the accumulator with `fetchNext`\n fetchNext,\n );\n\n // Invoke all the folded async middlewares and return\n return chain(initialContext);\n }\n\n /**\n * Subscribes to the given method defined using the endpoint and method\n * parameters with the parameters given as params. The method must return a\n * compatible type such as a Flux.\n * Returns a subscription that is used to fetch values as they become available.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @returns A subscription used to handles values as they become available.\n */\n subscribe(endpoint: string, method: string, params?: any): Subscription<any> {\n return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);\n }\n}\n"],"version":3}
@@ -1 +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,EAE3D,MAAM,cAAc,IAAI,IAAI,WAAW,UAAU,WAAW,KAAK,CAClE,EAAC;AAEF,eAAe","names":["CookieManager: typeof Cookies"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/CookieManager.ts"],"sourcesContent":["import Cookies from 'js-cookie';\n\nexport function calculatePath({ pathname }: URL): string {\n return pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;\n}\n\nconst CookieManager: typeof Cookies = Cookies.withAttributes({\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n path: calculatePath(new URL(globalThis.document?.baseURI ?? '/')),\n});\n\nexport default CookieManager;\n"],"version":3}
1
+ {"mappings":"AAAA,OAAO,wBAAyB;AAEhC,OAAO,SAAS,cAAc,EAAE,UAAe,EAAU;AACvD,QAAO,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GAAG,SAAS,MAAM,IAAI,EAAE,GAAG;AAChF;AAED,MAAMA,gBAAgC,QAAQ,eAAe,EAE3D,MAAM,cAAc,IAAI,IAAI,WAAW,UAAU,WAAW,KAAK,CAClE,EAAC;AAEF,eAAe","names":["CookieManager: typeof Cookies"],"sources":["/opt/agent/work/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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n path: calculatePath(new URL(globalThis.document?.baseURI ?? '/')),\n});\n\nexport default CookieManager;\n"],"version":3}
package/CsrfUtils.js.map CHANGED
@@ -1 +1 @@
1
- {"mappings":"AAAA,OAAO,uCAAwC;;AAG/C,OAAO,MAAM,qBAAqB;;AAElC,OAAO,MAAM,0BAA0B;;AAEvC,OAAO,MAAM,0BAA0B;AAEvC,SAAS,0BAA0BA,KAAeC,SAAqC;CACrF,MAAM,UAAU,IA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],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/CsrfUtils.ts"],"sourcesContent":["import CookieManager from './CookieManager.js';\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 if (element) {\n const value = element.content;\n if (value && value.toLowerCase() !== 'undefined') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getSpringCsrfInfo(doc: Document): Record<string, string> {\n let csrf = CookieManager.get(SPRING_CSRF_COOKIE_NAME);\n if (!csrf || csrf.length === 0) {\n csrf = extractContentFromMetaTag(doc, '_csrf');\n }\n const csrfHeader = extractContentFromMetaTag(doc, '_csrf_header');\n\n const headers: Record<string, string> = {};\n if (csrf && csrfHeader) {\n headers._csrf = csrf;\n // eslint-disable-next-line camelcase\n headers._csrf_header = csrfHeader;\n\n const csrfParameter = extractContentFromMetaTag(doc, '_csrf_parameter');\n if (csrfParameter) {\n // eslint-disable-next-line camelcase\n headers._csrf_parameter = csrfParameter;\n }\n }\n return headers;\n}\n\n/** @internal */\nexport function getSpringCsrfTokenHeadersForAuthRequest(doc: Document): Record<string, string> {\n const csrfInfo = getSpringCsrfInfo(doc);\n const headers: Record<string, string> = {};\n if (csrfInfo._csrf && csrfInfo._csrf_header) {\n headers[csrfInfo._csrf_header] = csrfInfo._csrf;\n }\n return headers;\n}\n\n/** @internal */\nexport function getCsrfTokenHeadersForEndpointRequest(doc: Document): Record<string, string> {\n const headers: Record<string, string> = {};\n\n const csrfInfo = getSpringCsrfInfo(doc);\n if (csrfInfo._csrf && csrfInfo._csrf_header) {\n headers[csrfInfo._csrf_header] = csrfInfo._csrf;\n } else {\n headers[VAADIN_CSRF_HEADER] = CookieManager.get(VAADIN_CSRF_COOKIE_NAME) ?? '';\n }\n\n return headers;\n}\n\n/** @internal */\nexport function getSpringCsrfTokenParametersForAuthRequest(doc: Document): Record<string, string> {\n const csrfInfo = getSpringCsrfInfo(doc);\n const parameters: Record<string, string> = {};\n if (csrfInfo._csrf && csrfInfo._csrf_parameter) {\n parameters[csrfInfo._csrf_parameter] = csrfInfo._csrf;\n }\n return parameters;\n}\n"],"version":3}
1
+ {"mappings":"AAAA,OAAO,uCAAwC;;AAG/C,OAAO,MAAM,qBAAqB;;AAElC,OAAO,MAAM,0BAA0B;;AAEvC,OAAO,MAAM,0BAA0B;AAEvC,SAAS,0BAA0BA,KAAeC,SAAqC;CACrF,MAAM,UAAU,IAAI,KAAK,eAAgC,aAAa,QAAQ,IAAI;AAClF,KAAI,SAAS;EACX,MAAM,QAAQ,QAAQ;AACtB,MAAI,SAAS,MAAM,aAAa,KAAK,aAAa;AAChD,UAAO;EACR;CACF;AACD,QAAO;AACR;AAED,OAAO,SAAS,kBAAkBD,KAAuC;CACvE,IAAI,OAAO,cAAc,IAAI,wBAAwB;AACrD,MAAK,QAAQ,KAAK,WAAW,GAAG;AAC9B,SAAO,0BAA0B,KAAK,QAAQ;CAC/C;CACD,MAAM,aAAa,0BAA0B,KAAK,eAAe;CAEjE,MAAME,UAAkC,CAAE;AAC1C,KAAI,QAAQ,YAAY;AACtB,UAAQ,QAAQ;AAEhB,UAAQ,eAAe;EAEvB,MAAM,gBAAgB,0BAA0B,KAAK,kBAAkB;AACvE,MAAI,eAAe;AAEjB,WAAQ,kBAAkB;EAC3B;CACF;AACD,QAAO;AACR;;AAGD,OAAO,SAAS,wCAAwCF,KAAuC;CAC7F,MAAM,WAAW,kBAAkB,IAAI;CACvC,MAAME,UAAkC,CAAE;AAC1C,KAAI,SAAS,SAAS,SAAS,cAAc;AAC3C,UAAQ,SAAS,gBAAgB,SAAS;CAC3C;AACD,QAAO;AACR;;AAGD,OAAO,SAAS,sCAAsCF,KAAuC;CAC3F,MAAME,UAAkC,CAAE;CAE1C,MAAM,WAAW,kBAAkB,IAAI;AACvC,KAAI,SAAS,SAAS,SAAS,cAAc;AAC3C,UAAQ,SAAS,gBAAgB,SAAS;CAC3C,OAAM;AACL,UAAQ,sBAAsB,cAAc,IAAI,wBAAwB,IAAI;CAC7E;AAED,QAAO;AACR;;AAGD,OAAO,SAAS,2CAA2CF,KAAuC;CAChG,MAAM,WAAW,kBAAkB,IAAI;CACvC,MAAMG,aAAqC,CAAE;AAC7C,KAAI,SAAS,SAAS,SAAS,iBAAiB;AAC9C,aAAW,SAAS,mBAAmB,SAAS;CACjD;AACD,QAAO;AACR","names":["doc: Document","metaTag: string","headers: Record<string, string>","parameters: Record<string, string>"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/CsrfUtils.ts"],"sourcesContent":["import CookieManager from './CookieManager.js';\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 if (element) {\n const value = element.content;\n if (value && value.toLowerCase() !== 'undefined') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getSpringCsrfInfo(doc: Document): Record<string, string> {\n let csrf = CookieManager.get(SPRING_CSRF_COOKIE_NAME);\n if (!csrf || csrf.length === 0) {\n csrf = extractContentFromMetaTag(doc, '_csrf');\n }\n const csrfHeader = extractContentFromMetaTag(doc, '_csrf_header');\n\n const headers: Record<string, string> = {};\n if (csrf && csrfHeader) {\n headers._csrf = csrf;\n // eslint-disable-next-line camelcase\n headers._csrf_header = csrfHeader;\n\n const csrfParameter = extractContentFromMetaTag(doc, '_csrf_parameter');\n if (csrfParameter) {\n // eslint-disable-next-line camelcase\n headers._csrf_parameter = csrfParameter;\n }\n }\n return headers;\n}\n\n/** @internal */\nexport function getSpringCsrfTokenHeadersForAuthRequest(doc: Document): Record<string, string> {\n const csrfInfo = getSpringCsrfInfo(doc);\n const headers: Record<string, string> = {};\n if (csrfInfo._csrf && csrfInfo._csrf_header) {\n headers[csrfInfo._csrf_header] = csrfInfo._csrf;\n }\n return headers;\n}\n\n/** @internal */\nexport function getCsrfTokenHeadersForEndpointRequest(doc: Document): Record<string, string> {\n const headers: Record<string, string> = {};\n\n const csrfInfo = getSpringCsrfInfo(doc);\n if (csrfInfo._csrf && csrfInfo._csrf_header) {\n headers[csrfInfo._csrf_header] = csrfInfo._csrf;\n } else {\n headers[VAADIN_CSRF_HEADER] = CookieManager.get(VAADIN_CSRF_COOKIE_NAME) ?? '';\n }\n\n return headers;\n}\n\n/** @internal */\nexport function getSpringCsrfTokenParametersForAuthRequest(doc: Document): Record<string, string> {\n const csrfInfo = getSpringCsrfInfo(doc);\n const parameters: Record<string, string> = {};\n if (csrfInfo._csrf && csrfInfo._csrf_parameter) {\n parameters[csrfInfo._csrf_parameter] = csrfInfo._csrf;\n }\n return parameters;\n}\n"],"version":3}
@@ -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/1af72d8adc613024/hilla/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}
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}
@@ -1 +1 @@
1
- {"mappings":"AACA,OAAO,+BAAgC;AAEvC,SAAS,6DAA8D;AACvE,SACE,0CAIyB;AAE3B,OAAO,IAAK,wBAAL;AACL;AACA;AACA;;AACD;;;;AAiBD,OAAO,IAAK,8DAAL;;;;AAIL;;;;AAIA;;AACD;;;;AAKD,OAAO,IAAK,wDAAL;;;;AAIL;;;;AAIA;;;;AAIA;;AACD;;;;AAiBD,OAAO,MAAM,uBAAuB,YAAY;CAC9C,Q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AAO,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,OAAKL,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,MAAMmC,SAAwB;AAC5B,MAAI,KAAK,UAAU,MAAM,UAAU;AACjC,QAAKC,iBAAiB,KAAK,QAAQ;EACpC,OAAM;AACL,QAAKP,SAAS,OAAO,KAAK,UAAU,QAAQ,CAAC;EAC9C;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","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 atmosphere from 'atmosphere.js';\nimport type { Subscription } from './Connect.js';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n isClientMessage,\n type ServerCloseMessage,\n type ServerConnectMessage,\n type ServerMessage,\n} from './FluxMessages.js';\n\nexport enum State {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n RECONNECTING = 'reconnecting',\n}\n\ntype ActiveEvent = CustomEvent<{ active: boolean }>;\ninterface EventMap {\n 'state-changed': ActiveEvent;\n}\n\ntype ListenerType<T extends keyof EventMap> =\n | ((this: FluxConnection, ev: EventMap[T]) => any)\n | {\n handleEvent(ev: EventMap[T]): void;\n }\n | null;\n\n/**\n * Possible options for dealing with lost subscriptions after a websocket is reopened.\n */\nexport enum ActionOnLostSubscription {\n /**\n * The subscription should be resubscribed using the same server method and parameters.\n */\n RESUBSCRIBE = 'resubscribe',\n /**\n * The subscription should be removed.\n */\n REMOVE = 'remove',\n}\n\n/**\n * Possible states of a flux subscription.\n */\nexport enum FluxSubscriptionState {\n /**\n * The subscription is not connected and is trying to connect.\n */\n CONNECTING = 'connecting',\n /**\n * The subscription is connected and receiving updates.\n */\n CONNECTED = 'connected',\n /**\n * The subscription is closed and is not trying to reconnect.\n */\n CLOSED = 'closed',\n}\n\n/**\n * Event wrapper for flux subscription connection state change callback\n */\nexport type FluxSubscriptionStateChangeEvent = CustomEvent<{ state: FluxSubscriptionState }>;\n\ntype EndpointInfo = {\n endpointName: string;\n methodName: string;\n params: unknown[] | undefined;\n reconnect?(): ActionOnLostSubscription | void;\n};\n\n/**\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\n constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {\n super();\n 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 * 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 #connectWebsocket(prefix: string, atmosphereOptions: Partial<Atmosphere.Request>) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const extraHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const pushUrl = 'HILLA/push';\n const url = prefix.length === 0 ? pushUrl : (prefix.endsWith('/') ? prefix : `${prefix}/`) + pushUrl;\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) {\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":"AACA,OAAO,+BAAgC;AAEvC,SAAS,6DAA8D;AACvE,SACE,0CAIyB;AAE3B,OAAO,IAAK,wBAAL;AACL;AACA;AACA;;AACD;;;;AAiBD,OAAO,IAAK,8DAAL;;;;AAIL;;;;AAIA;;AACD;;;;AAKD,OAAO,IAAK,wDAAL;;;;AAIL;;;;AAIA;;;;AAIA;;AACD;;;;AAiBD,OAAO,MAAM,uBAAuB,YAAY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U,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,OAAKL,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,MAAMmC,SAAwB;AAC5B,MAAI,KAAK,UAAU,MAAM,UAAU;AACjC,QAAKC,iBAAiB,KAAK,QAAQ;EACpC,OAAM;AACL,QAAKP,SAAS,OAAO,KAAK,UAAU,QAAQ,CAAC;EAC9C;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","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 atmosphere from 'atmosphere.js';\nimport type { Subscription } from './Connect.js';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n isClientMessage,\n type ServerCloseMessage,\n type ServerConnectMessage,\n type ServerMessage,\n} from './FluxMessages.js';\n\nexport enum State {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n RECONNECTING = 'reconnecting',\n}\n\ntype ActiveEvent = CustomEvent<{ active: boolean }>;\ninterface EventMap {\n 'state-changed': ActiveEvent;\n}\n\ntype ListenerType<T extends keyof EventMap> =\n | ((this: FluxConnection, ev: EventMap[T]) => any)\n | {\n handleEvent(ev: EventMap[T]): void;\n }\n | null;\n\n/**\n * Possible options for dealing with lost subscriptions after a websocket is reopened.\n */\nexport enum ActionOnLostSubscription {\n /**\n * The subscription should be resubscribed using the same server method and parameters.\n */\n RESUBSCRIBE = 'resubscribe',\n /**\n * The subscription should be removed.\n */\n REMOVE = 'remove',\n}\n\n/**\n * Possible states of a flux subscription.\n */\nexport enum FluxSubscriptionState {\n /**\n * The subscription is not connected and is trying to connect.\n */\n CONNECTING = 'connecting',\n /**\n * The subscription is connected and receiving updates.\n */\n CONNECTED = 'connected',\n /**\n * The subscription is closed and is not trying to reconnect.\n */\n CLOSED = 'closed',\n}\n\n/**\n * Event wrapper for flux subscription connection state change callback\n */\nexport type FluxSubscriptionStateChangeEvent = CustomEvent<{ state: FluxSubscriptionState }>;\n\ntype EndpointInfo = {\n endpointName: string;\n methodName: string;\n params: unknown[] | undefined;\n reconnect?(): ActionOnLostSubscription | void;\n};\n\n/**\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\n constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {\n super();\n 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 * 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 #connectWebsocket(prefix: string, atmosphereOptions: Partial<Atmosphere.Request>) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const extraHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const pushUrl = 'HILLA/push';\n const url = prefix.length === 0 ? pushUrl : (prefix.endsWith('/') ? prefix : `${prefix}/`) + pushUrl;\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) {\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 +1 @@
1
- {"mappings":"AAmBA,OAAO,SAAS,gBAAgBA,OAAwC;AACtE,QAAO,SAAS,eAAe,UAAU,YAAY,WAAW;AACjE","names":["value: unknown"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/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}
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/LICENSE CHANGED
@@ -1,201 +1,3 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ This program is available under Vaadin Commercial License and Service Terms.
2
+ See https://vaadin.com/commercial-license-and-service-terms for the full
3
+ license.
package/README.md CHANGED
@@ -27,7 +27,7 @@ Read the [contributing guide](https://vaadin.com/docs/latest/contributing-docs/o
27
27
 
28
28
  ## License
29
29
 
30
- Apache License 2.0
30
+ This program is available under Vaadin Commercial License and Service Terms. For license terms, see LICENSE.
31
31
 
32
32
  Vaadin collects development time usage statistics to improve this product.
33
33
  For details and to opt-out, see https://github.com/vaadin/vaadin-usage-statistics.
package/index.js CHANGED
@@ -6,7 +6,7 @@ export { ActionOnLostSubscription, FluxConnection, State } from "./FluxConnectio
6
6
  vaadinObj.registrations ??= [];
7
7
  vaadinObj.registrations.push({
8
8
  is: feature ? `@vaadin/hilla-frontend/${feature}` : "@vaadin/hilla-frontend",
9
- version: "24.7.14"
9
+ version: "24.7.16"
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,OAAO,WAAW,CAAE,MAAM;AAChD,WAAU,kBAAkB,CAAE;AAC9B,WAAU,cAAc,KAAK;EAC3B,IAAI,WAAW,yBAAyB,QAAQ,IAAI;EACpD,SAAS;CACV,EAAC;AACH,IAAG","names":[],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/index.ts"],"sourcesContent":["export * from './Authentication.js';\nexport * from './Connect.js';\nexport * from './EndpointErrors.js';\nexport { ActionOnLostSubscription, FluxConnection, State } from './FluxConnection.js';\n\n// @ts-expect-error: esbuild injection\n// eslint-disable-next-line @typescript-eslint/no-unsafe-call\n((feature, vaadinObj = (window.Vaadin ??= {})) => {\n vaadinObj.registrations ??= [];\n vaadinObj.registrations.push({\n is: feature ? `@vaadin/hilla-frontend/${feature}` : '@vaadin/hilla-frontend',\n version: '24.7.14',\n });\n})();\n"],"version":3}
1
+ {"mappings":"AAAA;AACA;AACA;AACA,SAAS,0BAA0B,gBAAgB;AAInD,CAAC,CAAC,SAAS,YAAa,OAAO,WAAW,CAAE,MAAM;AAChD,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 = (window.Vaadin ??= {})) => {\n vaadinObj.registrations ??= [];\n vaadinObj.registrations.push({\n is: feature ? `@vaadin/hilla-frontend/${feature}` : '@vaadin/hilla-frontend',\n version: '24.7.16',\n });\n})();\n"],"version":3}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vaadin/hilla-frontend",
3
- "version": "24.7.14",
3
+ "version": "24.7.16",
4
4
  "description": "Hilla core frontend utils",
5
5
  "main": "index.js",
6
6
  "module": "index.js",
@@ -50,7 +50,7 @@
50
50
  }
51
51
  },
52
52
  "author": "Vaadin Ltd",
53
- "license": "Apache-2.0",
53
+ "license": "SEE LICENSE IN LICENSE",
54
54
  "bugs": {
55
55
  "url": "https://github.com/vaadin/hilla/issues"
56
56
  },
@@ -64,7 +64,7 @@
64
64
  "dependencies": {
65
65
  "@vaadin/common-frontend": "0.0.19",
66
66
  "atmosphere.js": "3.1.3",
67
- "js-cookie": "3.0.5"
67
+ "js-cookie": "3.0.8"
68
68
  },
69
69
  "peerDependencies": {
70
70
  "lit": "^3.0.0"