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AAS,IAAMJ,EAAUG,EAAIC,EAAS,IAAMJ,EAAUG,EAAIC,EAAS,IAAMJ,EAAUG,EAAIC,EAAS,IAAM,IAAMJ,EAAUG,EAAIC,EAAS,IAAMJ,EAAUG,EAAIC,EAAS,IAAM,IAAMJ,EAAUG,EAAIC,EAAS,IAAMJ,EAAUG,EAAIC,EAAS,IAAM,IAAMJ,EAAUG,EAAIC,EAAS,IAAMJ,EAAUG,EAAIC,EAAS,IAAM,IAAMJ,EAAUG,EAAIC,EAAS,KAAOJ,EAAUG,EAAIC,EAAS,KAAOJ,EAAUG,EAAIC,EAAS,KAAOJ,EAAUG,EAAIC,EAAS,KAAOJ,EAAUG,EAAIC,EAAS,KAAOJ,EAAUG,EAAIC,EAAS,MAAME,cAMzf,IAAK,EAASR,GACZ,MAAMS,UAAU,+BAGlB,OAAOT,CACT,ECJA,QApBA,SAAY7qB,EAASurB,EAAKJ,GAExB,IAAIK,GADJxrB,EAAUA,GAAW,CAAC,GACHyrB,SAAWzrB,EAAQyqB,KAAOA,KAK7C,GAHAe,EAAK,GAAe,GAAVA,EAAK,GAAY,GAC3BA,EAAK,GAAe,GAAVA,EAAK,GAAY,IAEvBD,EAAK,CACPJ,EAASA,GAAU,EAEnB,IAAK,IAAIzd,EAAI,EAAGA,EAAI,KAAMA,EACxB6d,EAAIJ,EAASzd,GAAK8d,EAAK9d,GAGzB,OAAO6d,CACT,CAEA,OAAO,EAAUC,EACnB,C","sources":["webpack://aurora-new-frontend/./packages/cad-core/src/cad-view/loading-animation.tsx","webpack://aurora-new-frontend/./packages/cad-core/src/cad-view/cad-loading-page.tsx","webpack://aurora-new-frontend/./packages/cad-core/src/cad.generated.tsx","webpack://aurora-new-frontend/./packages/cad-state/src/use-once-ref.ts","webpack://aurora-new-frontend/./packages/cad-state/src/use-reactive.ts","webpack://aurora-new-frontend/./packages/cad-core/src/cad-viewport/cad-page-viewports-state.tsx","webpack://aurora-new-frontend/./packages/cad-state/src/reactive-setup.tsx","webpack://aurora-new-frontend/./packages/cad-core/src/cad-viewport/cad-viewport-action-scheduler.tsx","webpack://aurora-new-frontend/./packages/cad-core/src/cad-viewport/constants.ts","webpack://aurora-new-frontend/./packages/cad-core/src/use-cad/cad-context.tsx","webpack://aurora-new-frontend/./packages/cad-core/src/types.ts","webpack://aurora-new-frontend/./packages/cad-core/src/use-cad/lead-capture-geodata-service.ts","webpack://aurora-new-frontend/./packages/cad-preferences/src/preference-descriptor-types.ts","webpack://aurora-new-frontend/./packages/cad-preferences/src/preference-providers.ts","webpack://aurora-new-frontend/./packages/cad-preferences/src/preference-manager.ts","webpack://aurora-new-frontend/./packages/cad-preferences/src/preference-utils.ts","webpack://aurora-new-frontend/./packages/cad-preferences/src/cad-preference-descriptors.ts","webpack://aurora-new-frontend/./packages/cad-state/src/auto-designer-state/auto-designer-state.tsx","webpack://aurora-new-frontend/./packages/cad-state/src/modal-state/modal-state.tsx","webpack://aurora-new-frontend/./packages/cad-state/src/save-state/save-state.tsx","webpack://aurora-new-frontend/./packages/cad-state/src/cad-state.ts","webpack://aurora-new-frontend/./packages/cad-state/src/selected-types/selected-types-state.ts","webpack://aurora-new-frontend/./packages/cad-state/src/prism-state/prism-state.tsx","webpack://aurora-new-frontend/./packages/file-uploader/src/file-uploader.generated.tsx","webpack://aurora-new-frontend/./packages/file-uploader/src/hooks/use-create-bss-upload-urls.ts","webpack://aurora-new-frontend/./packages/file-uploader/src/hooks/use-upload-file-async-job.ts","webpack://aurora-new-frontend/./packages/file-uploader/src/hooks/use-upload-files.ts","webpack://aurora-new-frontend/./packages/cad-core/src/cad-save-callback/take-save-screenshot.ts","webpack://aurora-new-frontend/./packages/cad-core/src/cad-save-callback/get-cad-save-callback.ts","webpack://aurora-new-frontend/./packages/cad-core/src/cad-save-callback/cad-save-callback-core.ts","webpack://aurora-new-frontend/./packages/cad-core/src/use-cad/use-cad.tsx","webpack://aurora-new-frontend/./packages/common/packages/core/src/hooks/use-evict-cache/use-evict-cache.ts","webpack://aurora-new-frontend/./packages/cad-core/src/use-cad/use-lead-capture-cad.generated.tsx","webpack://aurora-new-frontend/./packages/cad-core/src/use-cad/use-lead-capture-cad.ts","webpack://aurora-new-frontend/./packages/common/packages/core/src/utils/uuid.ts","webpack://aurora-new-frontend/./packages/common/packages/shared-domain/src/use-intercept-mouse/use-intercept-mouse.tsx","webpack://aurora-new-frontend/./packages/file-uploader/src/common/types.ts","webpack://aurora-new-frontend/./packages/file-uploader/src/common/utils.ts","webpack://aurora-new-frontend/./node_modules/uuid/dist/esm-browser/rng.js","webpack://aurora-new-frontend/./node_modules/uuid/dist/esm-browser/regex.js","webpack://aurora-new-frontend/./node_modules/uuid/dist/esm-browser/validate.js","webpack://aurora-new-frontend/./node_modules/uuid/dist/esm-browser/stringify.js","webpack://aurora-new-frontend/./node_modules/uuid/dist/esm-browser/v4.js"],"sourcesContent":["import { FC, lazy, memo, Suspense, useEffect, useState } from 'react';\n\nconst lazyLoadLottie: () => Promise = async () => {\n const lottie = (\n await import(\n /* webpackChunkName: 'cad-animations' */\n /* webpackPrefetch: true */\n `./loading-animation.lottie`\n )\n ).default;\n return lottie;\n};\n\nexport const LoadingAnimation: FC<{}> = memo(() => {\n const Lottie = lazy(() => import('react-lottie-player/dist/LottiePlayerLight'));\n\n const [path, setPath] = useState();\n\n useEffect(() => {\n const loadpath = async () => {\n const pathData = await lazyLoadLottie();\n setPath(pathData);\n };\n\n loadpath();\n }, [path]);\n\n return (\n \n \n \n );\n});\n","import { FC } from 'react';\n\nimport * as DS from '@aurorasolar/ds';\nimport { styled, x } from '@xstyled/styled-components';\n\nimport { LoadingAnimation } from './loading-animation';\n\nconst LoadingText = styled.h1Box`\n &::after {\n display: inline-block;\n animation: ellipsis 1s ease infinite;\n content: '.';\n width: 1em;\n text-align: left;\n }\n\n @keyframes ellipsis {\n 0% {\n content: '.';\n }\n\n 33% {\n content: '..';\n }\n\n 66% {\n content: '...';\n }\n }\n`;\n\nexport const CadLoadingPage: FC = () => {\n return (\n \n \n \n \n\n Coming right up\n\n \n Please wait while we load the design engine\n \n \n );\n};\n","// @ts-ignore: Ignore unused { * as Types } import\nimport * as Types from '@aurorasolar/graphql-client-schema';\n\nimport { gql } from '@apollo/client';\nimport * as Apollo from '@apollo/client';\nconst defaultOptions = {} as const;\nexport type SaveDesignMutationVariables = Types.Exact<{\n designId: Types.Scalars['ID'];\n cadUpdatedDesign: Types.CadUpdatedDesign;\n}>;\n\n\nexport type SaveDesignMutation = { __typename: 'Mutation', saveDesign: { __typename: 'Design', id: string, savesDisabled?: boolean | null | undefined, designString?: string | null | undefined, designJson?: any | null | undefined, siteString?: string | null | undefined, siteJson?: any | null | undefined, latitude: number, longitude: number, savedFromNewCad: boolean, irradianceMapId?: string | null | undefined, irradianceMapStatus?: string | null | undefined, irradiancePanelsId?: string | null | undefined, irradiancePanelsStatus?: string | null | undefined, temperatureMax?: number | null | undefined, temperatureMin?: number | null | undefined, geodataBaseUrl?: string | null | undefined, geodataParentId?: number | null | undefined, updatedAt?: string | null | undefined, energyOffset?: number | null | undefined, systemSize?: number | null | undefined, pricePerWatt?: number | null | undefined, addersAndDiscounts?: Array<{ __typename: 'Adder', id: string, adderName?: string | null | undefined, adderType?: Types.AdderType | null | undefined, adderValue?: number | null | undefined }> | null | undefined, avoidedCost: { __typename: 'AvoidedCost', id: string, valid?: boolean | null | undefined, billOffset?: string | null | undefined }, masterPerformanceSimulation: { __typename: 'PerformanceSimulation', id: string, valid?: boolean | null | undefined }, financings?: Array<{ __typename: 'Financing', id: string, valid?: boolean | null | undefined }> | null | undefined, pricing: { __typename: 'Pricing', id: string, systemCost: number } } };\n\nexport type IsSavingQueryVariables = Types.Exact<{ [key: string]: never; }>;\n\n\nexport type IsSavingQuery = { __typename: 'Query', CAD: { __typename: 'CAD', isSaving: boolean } };\n\nexport type CadUberModeQueryVariables = Types.Exact<{ [key: string]: never; }>;\n\n\nexport type CadUberModeQuery = { __typename: 'Query', CAD: { __typename: 'CAD', uberMode: string } };\n\nexport type GetDesignByIdQueryVariables = Types.Exact<{\n id: Types.Scalars['ID'];\n}>;\n\n\nexport type GetDesignByIdQuery = { __typename: 'Query', designById: { __typename: 'Design', id: string, savesDisabled?: boolean | null | undefined, designString?: string | null | undefined, designJson?: any | null | undefined, siteString?: string | null | undefined, siteJson?: any | null | undefined, latitude: number, longitude: number, savedFromNewCad: boolean, irradianceMapId?: string | null | undefined, irradianceMapStatus?: string | null | undefined, irradiancePanelsId?: string | null | undefined, irradiancePanelsStatus?: string | null | undefined, temperatureMax?: number | null | undefined, temperatureMin?: number | null | undefined, geodataBaseUrl?: string | null | undefined, geodataParentId?: number | null | undefined } };\n\nexport type CadUpdateSaveQueryVariables = Types.Exact<{ [key: string]: never; }>;\n\n\nexport type CadUpdateSaveQuery = { __typename: 'Query', CAD: { __typename: 'CAD', isSaving: boolean, recentSavedVersion: string } };\n\nexport type CadModeQueryVariables = Types.Exact<{ [key: string]: never; }>;\n\n\nexport type CadModeQuery = { __typename: 'Query', CAD: { __typename: 'CAD', mode: string } };\n\n\nexport const SaveDesignDocument = gql`\n mutation SaveDesign($designId: ID!, $cadUpdatedDesign: CadUpdatedDesign!) @trace_info(traceInfo: {pod: cad}) {\n saveDesign(id: $designId, cadUpdatedDesign: $cadUpdatedDesign) {\n id\n savesDisabled\n designString\n designJson @client\n siteString\n siteJson @client\n latitude\n longitude\n savedFromNewCad\n irradianceMapId\n irradianceMapStatus\n irradiancePanelsId\n irradiancePanelsStatus\n temperatureMax\n temperatureMin\n geodataBaseUrl\n geodataParentId\n updatedAt\n energyOffset\n systemSize\n pricePerWatt\n addersAndDiscounts {\n id\n adderName\n adderType\n adderValue\n }\n avoidedCost {\n id\n valid\n billOffset\n }\n masterPerformanceSimulation {\n id\n valid\n }\n financings {\n id\n valid\n }\n pricing {\n id\n systemCost\n }\n }\n}\n `;\nexport type SaveDesignMutationFn = Apollo.MutationFunction;\n\n/**\n * __useSaveDesignMutation__\n *\n * To run a mutation, you first call `useSaveDesignMutation` within a React component and pass it any options that fit your needs.\n * When your component renders, `useSaveDesignMutation` returns a tuple that includes:\n * - A mutate function that you can call at any time to execute the mutation\n * - An object with fields that represent the current status of the mutation's execution\n *\n * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;\n *\n * @example\n * const [saveDesignMutation, { data, loading, error }] = useSaveDesignMutation({\n * variables: {\n * designId: // value for 'designId'\n * cadUpdatedDesign: // value for 'cadUpdatedDesign'\n * },\n * });\n */\nexport function useSaveDesignMutation(baseOptions?: Apollo.MutationHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useMutation(SaveDesignDocument, options);\n }\nexport type SaveDesignMutationHookResult = ReturnType;\nexport type SaveDesignMutationResult = Apollo.MutationResult;\nexport type SaveDesignMutationOptions = Apollo.BaseMutationOptions;\nexport const IsSavingDocument = gql`\n query IsSaving @trace_info(traceInfo: {pod: cad}) {\n CAD @client {\n isSaving\n }\n}\n `;\n\n/**\n * __useIsSavingQuery__\n *\n * To run a query within a React component, call `useIsSavingQuery` and pass it any options that fit your needs.\n * When your component renders, `useIsSavingQuery` returns an object from Apollo Client that contains loading, error, and data properties\n * you can use to render your UI.\n *\n * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;\n *\n * @example\n * const { data, loading, error } = useIsSavingQuery({\n * variables: {\n * },\n * });\n */\nexport function useIsSavingQuery(baseOptions?: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(IsSavingDocument, options);\n }\nexport function useIsSavingLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useLazyQuery(IsSavingDocument, options);\n }\nexport type IsSavingQueryHookResult = ReturnType;\nexport type IsSavingLazyQueryHookResult = ReturnType;\nexport type IsSavingQueryResult = Apollo.QueryResult;\nexport const CadUberModeDocument = gql`\n query CadUberMode @trace_info(traceInfo: {pod: cad}) {\n CAD @client {\n uberMode\n }\n}\n `;\n\n/**\n * __useCadUberModeQuery__\n *\n * To run a query within a React component, call `useCadUberModeQuery` and pass it any options that fit your needs.\n * When your component renders, `useCadUberModeQuery` returns an object from Apollo Client that contains loading, error, and data properties\n * you can use to render your UI.\n *\n * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;\n *\n * @example\n * const { data, loading, error } = useCadUberModeQuery({\n * variables: {\n * },\n * });\n */\nexport function useCadUberModeQuery(baseOptions?: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(CadUberModeDocument, options);\n }\nexport function useCadUberModeLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useLazyQuery(CadUberModeDocument, options);\n }\nexport type CadUberModeQueryHookResult = ReturnType;\nexport type CadUberModeLazyQueryHookResult = ReturnType;\nexport type CadUberModeQueryResult = Apollo.QueryResult;\nexport const GetDesignByIdDocument = gql`\n query GetDesignById($id: ID!) @trace_info(traceInfo: {pod: cad}) {\n designById(id: $id) {\n id\n savesDisabled\n designString\n designJson @client\n siteString\n siteJson @client\n latitude\n longitude\n savedFromNewCad\n irradianceMapId\n irradianceMapStatus\n irradiancePanelsId\n irradiancePanelsStatus\n temperatureMax\n temperatureMin\n geodataBaseUrl\n geodataParentId\n }\n}\n `;\n\n/**\n * __useGetDesignByIdQuery__\n *\n * To run a query within a React component, call `useGetDesignByIdQuery` and pass it any options that fit your needs.\n * When your component renders, `useGetDesignByIdQuery` returns an object from Apollo Client that contains loading, error, and data properties\n * you can use to render your UI.\n *\n * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;\n *\n * @example\n * const { data, loading, error } = useGetDesignByIdQuery({\n * variables: {\n * id: // value for 'id'\n * },\n * });\n */\nexport function useGetDesignByIdQuery(baseOptions: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(GetDesignByIdDocument, options);\n }\nexport function useGetDesignByIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useLazyQuery(GetDesignByIdDocument, options);\n }\nexport type GetDesignByIdQueryHookResult = ReturnType;\nexport type GetDesignByIdLazyQueryHookResult = ReturnType;\nexport type GetDesignByIdQueryResult = Apollo.QueryResult;\nexport const CadUpdateSaveDocument = gql`\n query CadUpdateSave @trace_info(traceInfo: {pod: cad}) {\n CAD @client {\n __typename\n isSaving\n recentSavedVersion\n }\n}\n `;\n\n/**\n * __useCadUpdateSaveQuery__\n *\n * To run a query within a React component, call `useCadUpdateSaveQuery` and pass it any options that fit your needs.\n * When your component renders, `useCadUpdateSaveQuery` returns an object from Apollo Client that contains loading, error, and data properties\n * you can use to render your UI.\n *\n * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;\n *\n * @example\n * const { data, loading, error } = useCadUpdateSaveQuery({\n * variables: {\n * },\n * });\n */\nexport function useCadUpdateSaveQuery(baseOptions?: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(CadUpdateSaveDocument, options);\n }\nexport function useCadUpdateSaveLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useLazyQuery(CadUpdateSaveDocument, options);\n }\nexport type CadUpdateSaveQueryHookResult = ReturnType;\nexport type CadUpdateSaveLazyQueryHookResult = ReturnType;\nexport type CadUpdateSaveQueryResult = Apollo.QueryResult;\nexport const CadModeDocument = gql`\n query CadMode @trace_info(traceInfo: {pod: cad}) {\n CAD @client {\n mode\n }\n}\n `;\n\n/**\n * __useCadModeQuery__\n *\n * To run a query within a React component, call `useCadModeQuery` and pass it any options that fit your needs.\n * When your component renders, `useCadModeQuery` returns an object from Apollo Client that contains loading, error, and data properties\n * you can use to render your UI.\n *\n * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;\n *\n * @example\n * const { data, loading, error } = useCadModeQuery({\n * variables: {\n * },\n * });\n */\nexport function useCadModeQuery(baseOptions?: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(CadModeDocument, options);\n }\nexport function useCadModeLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useLazyQuery(CadModeDocument, options);\n }\nexport type CadModeQueryHookResult = ReturnType;\nexport type CadModeLazyQueryHookResult = ReturnType;\nexport type CadModeQueryResult = Apollo.QueryResult;","import { useRef } from 'react';\n\nexport const useOnceRef = (fn: () => T) => {\n const isInitialized = useRef(false);\n const value = useRef(isInitialized.current ? (null as unknown as T) : fn());\n isInitialized.current = true;\n return value;\n};\n","/* eslint-disable react-hooks/exhaustive-deps */\nimport { useLocalObservable } from 'mobx-react-lite';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { effect } from './framework';\nimport { useOnceRef } from './use-once-ref';\n\n/**\n * `useReactive` is a hook that enables easy subscription to any MobX state.\n * The react component using the hook will subscribe to any reactive properties\n * accessed in `getReactive`, as well as deeply subscribe to any reactive objects\n * returned from it. Additionally, the hook can take a dependency array, shallow\n * changes to which will force `getReactive` to rerun and update the component's\n * reactive dependencies\n */\nexport const useReactive = (\n getReactive: () => T,\n dependencyArray: ReadonlyArray = [],\n) => {\n const isWithinRender = useRef(true);\n isWithinRender.current = true;\n\n // `result` is a React ref holding the value returned from `getReactive`.\n // `as unknown as T` here is safe because `result` will always initialize during the effect\n const result = useRef(null as unknown as T);\n const [, rerender] = useState(Symbol('useReactive'));\n\n // Since `getReactive` is wrapped in `useCallback` with a dependency array, it'll change\n // only when the dependency array is changed\n const reactiveCallback = useCallback(getReactive, dependencyArray);\n const lastReactiveCallbackRef = useRef(reactiveCallback);\n\n // An observable for `getReactive` function which will be used in the effect\n const reactiveObservable = useLocalObservable(() => ({\n reactiveCallback,\n setReactiveCallback: (newReactiveCallback: () => T) => {\n reactiveObservable.reactiveCallback = newReactiveCallback;\n },\n }));\n\n const stopEffect = useOnceRef(() =>\n effect(\n // Since we access `reactiveCallback` in this effect, when it is changed via\n // `setReactiveCallback`, e.g. when the dependency array is modified, this effect\n // will rerun as well\n () => reactiveObservable.reactiveCallback(),\n (value) => {\n result.current = value;\n // If the result is first initialized or changes due to the dependency array change\n // during render, we do not need to rerender, but is rerendered upon other changes\n if (!isWithinRender.current) {\n rerender(Symbol('useReactive'));\n }\n },\n ),\n );\n\n // The effect is stopped when component unmounts\n useEffect(() => {\n return () => {\n stopEffect.current();\n };\n }, []);\n\n // Upon dependency array change, if the callback is different, it'll recalculate\n // the effect since it depends on it\n if (lastReactiveCallbackRef.current !== reactiveCallback) {\n lastReactiveCallbackRef.current = reactiveCallback;\n reactiveObservable.setReactiveCallback(reactiveCallback);\n }\n\n isWithinRender.current = false;\n\n // Returning the current value from `getReactive` since it'll be kept\n // up to date due to rerendering\n return result.current;\n};\n","import { createReactiveSetup, ViewSettingsLayers } from '@aurorasolar/cad-state';\nimport { DEFAULT_CAD_VIEWPORT_NAME } from './constants';\nimport {\n CadViewportActionsScheduler,\n createCadViewportActionsScheduler,\n} from './cad-viewport-action-scheduler';\nimport { CadViewCamera } from './camera-utils';\n\nconst createCadContainer = () => document.createElement('div');\n\nexport type CadViewportsData = {\n // Default camera and layers are for storing camera and layer settings\n // that have been provided upon CAD initialization. Final view settings\n // for a given viewport will come from merging default settings with\n // settings for that viewport\n defaultCamera: null | CadViewCamera;\n defaultLayers: null | ViewSettingsLayers;\n\n // An array of all viewport names currently registered on the page\n // to ensure only a single viewport of the same name is registered and\n // to map a given viewport to a CAD container\n viewports: Array;\n};\n\nexport type CadContainersData = {\n // CAD containers for viewports specified in `CadViewportsData.viewports`.\n // The index of the CAD containers matches the indices in `CadViewportsData.viewports`\n cadContainers: Array;\n\n // CAD container for a default viewport. Default viewport is the one with\n // the name specified in DEFAULT_CAD_VIEWPORT_NAME. CAD always needs to have\n // at least one viewport, and the viewport the engine is initialized with\n // is the default viewport. The default viewport name can (and should) be reused\n // just like any other viewport name, with the exception that it does not need\n // to be explicitly added and removed from CAD because it'll always exist\n defaultCadContainer: HTMLElement;\n};\n\nexport type CadPageViewportsActions = ReturnType;\n\nconst createCadViewportsData = (): CadViewportsData => {\n return {\n defaultCamera: null,\n defaultLayers: null,\n viewports: [],\n };\n};\n\n/**\n * Creates data for CAD containers. This needs to be separate from `CadViewportsData`\n * because we should avoid having HTML elements as part of reactive MobX data\n */\nconst createCadContainersData = (): CadContainersData => {\n return {\n cadContainers: [],\n defaultCadContainer: createCadContainer(),\n };\n};\n\nconst createCadPageViewportsActions = (\n scheduler: CadViewportActionsScheduler,\n data: CadViewportsData,\n cadContainersData: CadContainersData,\n) => {\n return {\n addViewport: (name: string) => {\n scheduler.scheduleAddViewport(() => {\n if (data.viewports.indexOf(name) >= 0) {\n throw new Error('Only one CAD view with the same \"name\" can be registered at once');\n }\n\n const { cadContainers, defaultCadContainer } = cadContainersData;\n\n cadContainers.push(\n name === DEFAULT_CAD_VIEWPORT_NAME ? defaultCadContainer : createCadContainer(),\n );\n data.viewports.push(name);\n });\n },\n\n removeViewport: (name: string) => {\n scheduler.scheduleRemoveViewport(() => {\n const viewportIndex = data.viewports.indexOf(name);\n\n if (viewportIndex >= 0) {\n cadContainersData.cadContainers.splice(viewportIndex, 1);\n data.viewports.splice(viewportIndex, 1);\n }\n });\n },\n\n setDefaultViewSettings: ({\n camera,\n layers,\n }: {\n camera?: null | CadViewCamera;\n layers?: null | ViewSettingsLayers;\n }) => {\n if (layers !== undefined) {\n data.defaultLayers = layers;\n }\n if (camera !== undefined) {\n data.defaultCamera = camera;\n }\n },\n };\n};\n\nexport const {\n ReactiveContextProvider: CadPageViewportsStateProvider,\n useReactiveState: useCadPageViewportsState,\n} = createReactiveSetup((makeReactive) => {\n const data = makeReactive(createCadViewportsData());\n const cadContainersData = createCadContainersData();\n const scheduler = createCadViewportActionsScheduler(makeReactive);\n const actions = makeReactive(createCadPageViewportsActions(scheduler, data, cadContainersData));\n return {\n actions,\n cadContainersData,\n data,\n };\n});\n","import { createContext, FC, useContext } from 'react';\nimport { makeReactive, MakeReactive } from './framework';\nimport { useOnceRef } from './use-once-ref';\nimport { useReactive } from './use-reactive';\n\n/**\n * Creates hooks and providers that organize an instance of MobX state.\n * The state will be created when the provider mounts using the provided\n * `createState` function. `createState` takes `makeReactive` function as\n * an argument, which can be used to wrap objects and make them reactive.\n * The `useReactiveState` hook can be used to retrieve and automatically\n * subscribe to parts of the reactive state. `useReactiveState` takes a\n * function, whose first argument refers to the state; the component will\n * subscribe to anything accessed inside the function and deeply subscribe\n * to anything returned from the function. `useReactiveState` optionally\n * takes a dependency array, shallow changes to which will force\n * recalculation of the state and the component's dependencies\n */\nexport const createReactiveSetup = (\n createState: (makeReactive: MakeReactive) => State,\n) => {\n const ReactiveContext = createContext(null);\n\n const useReactiveContext = () => {\n const result = useContext(ReactiveContext);\n if (!result) {\n throw new Error('Cannot use reactive context outside of corresponding reactive context');\n }\n return result;\n };\n\n const ReactiveContextProvider: FC = ({ children }) => {\n const reactiveContextRef = useOnceRef(() => createState(makeReactive));\n return (\n \n {children}\n \n );\n };\n\n const useReactiveState = (\n fn: (state: State) => T,\n dependencyArray: ReadonlyArray = [],\n ) => {\n const reactiveContext = useReactiveContext();\n return useReactive(() => fn(reactiveContext), dependencyArray);\n };\n\n return { ReactiveContextProvider, useReactiveState };\n};\n","export type CadViewportActionsScheduler = ReturnType;\n\n/**\n * This is a workaround that ensures that `addViewport` is not called in the same\n * frame as `removeViewport`. This prevents a bug in CAD where, if the viewport\n * with the same `viewportName` is first removed, then added back in the same frame,\n * it would cause the viewport to break and not display anything\n */\nexport const createCadViewportActionsScheduler = (\n makeReactive: (value: T) => T,\n) => {\n const scheduledActions: Array<{ action: () => void; done: boolean; type: 'add' | 'remove' }> = [];\n\n const { processActions } = makeReactive({\n processActions: () => {\n // Finding the first action that hasn't been done yet\n let currentActionIndex = scheduledActions.findIndex(\n (scheduledAction) => !scheduledAction.done,\n );\n\n if (currentActionIndex >= 0) {\n const currentActionType = scheduledActions[currentActionIndex].type;\n\n // Running all consecutive actions of the same type\n for (; currentActionIndex < scheduledActions.length; currentActionIndex += 1) {\n const scheduledAction = scheduledActions[currentActionIndex];\n if (scheduledAction.type !== currentActionType) {\n break;\n } else {\n scheduledAction.action();\n scheduledAction.done = true;\n }\n }\n\n // Removing all actions that have been done\n scheduledActions.splice(0, currentActionIndex);\n } else {\n scheduledActions.splice(0, scheduledActions.length);\n }\n\n // All remaining actions should be run in the next frame\n if (scheduledActions.length > 0) {\n requestAnimationFrame(processActions);\n }\n },\n });\n\n return makeReactive({\n scheduleAddViewport: (action: () => void) => {\n if (scheduledActions.length === 0) {\n requestAnimationFrame(processActions);\n }\n if (\n scheduledActions.some(\n (scheduledAction) => !scheduledAction.done || scheduledAction.type === 'remove',\n )\n ) {\n scheduledActions.push({ action, done: false, type: 'add' });\n } else {\n action();\n scheduledActions.push({ action, done: true, type: 'add' });\n }\n },\n\n scheduleRemoveViewport: (action: () => void) => {\n if (scheduledActions.length === 0) {\n requestAnimationFrame(processActions);\n }\n if (\n scheduledActions.some(\n (scheduledAction) => !scheduledAction.done || scheduledAction.type === 'add',\n )\n ) {\n scheduledActions.push({ action, done: false, type: 'remove' });\n } else {\n action();\n scheduledActions.push({ action, done: true, type: 'remove' });\n }\n },\n });\n};\n","export const DEFAULT_CAD_VIEWPORT_NAME = 'design-3d';\n","import { createContext, FC, useContext } from 'react';\nimport { Subject } from 'rxjs';\n\nimport { CadPreferences } from '@aurorasolar/cad-preferences';\nimport { CadState, useLocalObservable, useReactive } from '@aurorasolar/cad-state';\nimport { CadEvent, CadEventTypes } from '@aurorasolar/common-data-store';\nimport { CadEngine } from '@aurorasolar/common-module-loader';\nimport { CadPageViewportsStateProvider } from '../cad-viewport/cad-page-viewports-state';\n\ntype CadContextLoadedValue = {\n designId: string;\n engine: CadEngine;\n engineSaveFn: null | (() => Promise);\n eventStream: Subject> | null;\n domNode: HTMLElement;\n state: CadState;\n preferences: CadPreferences;\n};\n\ntype CadContextInitialValue = {\n [K in keyof CadContextLoadedValue]?: null;\n};\n\ntype CadInitializerContextValue = {\n setCadContext: (cadContext: CadContextLoadedValue) => void;\n clearCadContext: () => void;\n setCadError: (error: Error) => void;\n};\n\ntype CadInitializerContextType = null | CadInitializerContextValue;\n\nexport enum CadStatus {\n Loading,\n Loaded,\n Error,\n}\n\nexport type CadContextValue =\n | ({\n status: CadStatus.Loaded;\n error: null;\n isLoaded: true;\n } & CadContextLoadedValue)\n | ({\n status: CadStatus.Loading;\n error: null;\n isLoaded: false;\n } & CadContextInitialValue)\n | ({\n status: CadStatus.Error;\n error: Error;\n isLoaded: false;\n } & CadContextInitialValue);\n\nexport type CadContextType = null | CadContextValue;\n\nexport const CadContext = createContext(null);\n\nconst CadInitializerContext = createContext(null);\n\nexport const useOptionalCadContext = () => {\n const context = useContext(CadContext);\n // Making sure component rerenders when `status` changes:\n useReactive(() => context?.status, [context]);\n return context;\n};\n\nexport const useCadContext = () => {\n const context = useOptionalCadContext();\n if (!context) {\n throw new Error('Cad context is not provided');\n }\n return context;\n};\n\n/**\n * Only for use in `useCad` hook. Exposes functions to initialize and clear\n * cad context\n */\nexport const useCadInitializerContext = () => {\n const context = useContext(CadInitializerContext);\n\n if (!context) {\n throw new Error('Cad context is not provided');\n }\n\n return context;\n};\n\nconst initialCadContext: Required = {\n designId: null,\n domNode: null,\n engine: null,\n engineSaveFn: null,\n eventStream: null,\n preferences: null,\n state: null,\n};\n\nexport const CadContextProvider: FC = ({ children }) => {\n const cadContext: CadContextValue = useLocalObservable(() => ({\n error: null,\n isLoaded: false,\n status: CadStatus.Loading,\n ...initialCadContext,\n }));\n const cadContextInitializer = useLocalObservable(() => ({\n clearCadContext() {\n const fullContext: CadContextValue = {\n error: null,\n isLoaded: false,\n status: CadStatus.Loading,\n ...initialCadContext,\n };\n Object.assign(cadContext, fullContext);\n },\n setCadContext(newCadContext) {\n const fullContext: CadContextValue = {\n error: null,\n isLoaded: true,\n status: CadStatus.Loaded,\n ...newCadContext,\n };\n Object.assign(cadContext, fullContext);\n },\n setCadError(error) {\n const fullContext: CadContextValue = {\n error,\n isLoaded: false,\n status: CadStatus.Error,\n ...initialCadContext,\n };\n Object.assign(cadContext, fullContext);\n },\n }));\n return (\n \n \n {children}\n \n \n );\n};\n","export enum CadMode {\n Site = 'default-site',\n System = 'default-design',\n Basic = 'default-basic',\n /**\n * A simplified CAD mode that allows panel toggling. Used by Sales Mode and the Client SDK.\n */\n Limited = 'default-limited',\n ReadOnly = 'read-only',\n Advanced = 'advanced',\n MoveRoof = 'move.roof',\n Paste = 'place.paste',\n DrawObstructionPolygon = 'draw.obstruction-polygon',\n DrawObstructionCircle = 'draw.obstruction-circle',\n DrawObstructionRectangle = 'draw.obstruction-rectangle',\n PasteObstructionPolygon = 'place.paste.obstruction-polygon',\n PasteObstructionCircle = 'place.paste.obstruction-circle',\n PasteObstructionRectangle = 'place.paste.obstruction-rectangle',\n DrawTree = 'draw.tree',\n PasteTree = 'place.paste.tree',\n EditOrthoImage = 'ortho-image-editing',\n PlaceOrthoImage = 'place.ortho-image-editor',\n DrawRuler = 'draw.ruler',\n Roof = 'roof',\n DrawRoof = 'draw.roof',\n DrawRoofPlane = 'draw.roof-plane',\n PasteRoof = 'place.paste.roof',\n PlaceDormer = 'place.dormer',\n PlaceKink = 'place.kink',\n DragInternalEdge = 'internal-edge-drag',\n DrawWalkway = 'draw.walkway',\n PasteWalkway = 'place.paste.draw.walkway',\n Stringing = 'stringing',\n DrawFillZone = 'draw.fill-zone',\n DrawSolarPanel = 'draw-solar-panel',\n PasteDrawSolarPanel = 'place.paste.draw-solar-panel',\n PasteDrawSolarArray = 'place.paste.draw-solar-array',\n PlaceSolarArray = 'place.solar-array',\n PlaceSolarInverter = 'place.solar-inverter',\n PlaceCombinerBox = 'place.combiner-box',\n PlaceLoadCenter = 'place.load-center',\n PlaceServicePanel = 'place.service-panel',\n PlaceMeter = 'place.meter',\n PlaceDisconnect = 'place.disconnect',\n FillRoofFace = 'fill-roof-face',\n TogglePanels = 'toggle-panels',\n DrawSolarArray = 'draw-solar-array',\n EditPanelPlane = 'edit.panel-plane',\n\n /**\n * @deprecated: basic mode is deprecated\n */\n DrawPanelPlane = 'draw.panel-plane',\n}\n","import { CADTriggerActionTypes } from '@aurorasolar/common-data-store';\nimport { CadBridge, ICADGeodataService } from '@aurorasolar/common-module-loader';\n\nimport { LeadCaptureCadQuery } from './use-lead-capture-cad.generated';\n\nexport const getLeadCaptureGeodataService = (data: LeadCaptureCadQuery): ICADGeodataService => {\n const processGroundTextures = async (cadBridge: CadBridge) => {\n cadBridge.triggerAction(CADTriggerActionTypes.ProcessGroundTextures, {\n orthoImages: [data.leadCadData.image!.orthoImage],\n });\n };\n\n return {\n deleteOrthoImage: async () => {},\n detectAllObstructions: async () => {},\n detectObstructions: async () => {},\n initialize: async (cadBridge) => processGroundTextures(cadBridge),\n initialized: true,\n onOrthoImageBoundsIncrease: async () => {},\n onProjectLocationChange: async () => {},\n onSiteBoundsChange: async () => {},\n onSpecifiedBoundsChange: async () => {},\n updateOrthoImage: async () => {},\n willDestroy: async () => {},\n };\n};\n","export enum PreferenceScope {\n /**\n * Preference saved per design\n */\n Design,\n\n /**\n * Preference saved per project\n */\n Project,\n\n /**\n * Preference saved for the entire app\n */\n App,\n}\n\nexport enum ExpirationType {\n /**\n * Never expires. Try to avoid using\n */\n Never,\n\n /**\n * Expires when exiting preference instance, e.g.\n * a single CAD instance\n */\n Instance,\n\n /**\n * Allows certain max number of preferences of the same type.\n * Once that number is reached, the oldest preferences of the same\n * type are removed when new ones are added\n */\n MaxCount,\n\n /**\n * Expires after a certain time period\n */\n MaxDuration,\n}\n\nexport enum UserScope {\n /**\n * Shared preference between all users. Default\n * option\n */\n Shared,\n\n /**\n * Separate preference for every user\n */\n PerUser,\n}\n\n/**\n * Type for preference descriptors\n */\nexport type PreferenceDescriptor = {\n preferenceScope: PreferenceScope;\n /**\n * If not provided, defaults to UserScope.Shared\n */\n userScope?: UserScope;\n isValid: (value: unknown) => value is T;\n} & (\n | {\n expirationType: ExpirationType.Never | ExpirationType.Instance;\n }\n | {\n expirationType: ExpirationType.MaxCount;\n maxCount: number;\n }\n | {\n expirationType: ExpirationType.MaxDuration;\n maxDurationMs: number;\n }\n);\n","/**\n * This shape will be stored per value and should not change in breaking ways.\n * We may only be able to add optional properties\n */\nexport type StoredValue = {\n value: T;\n timestamp: number;\n};\n\nexport type PreferenceProvider = {\n getKeys(): string[];\n has(key: string): boolean;\n get(key: string): undefined | StoredValue;\n set(key: string, value: StoredValue): void;\n remove(key: string): void;\n};\n\n/**\n * Since stored value may be manually changed or become out of date with the latest code,\n * we're ensuring that the stored value corresponds to the correct JSON object\n */\nconst getLocalStorageStoredValue = (value: string): undefined | StoredValue => {\n try {\n const json: number | string | Partial<{ [K in keyof StoredValue]: unknown }> =\n JSON.parse(value);\n if (\n json &&\n typeof json === 'object' &&\n 'value' in json &&\n 'timestamp' in json &&\n typeof json.timestamp === 'number'\n ) {\n return {\n timestamp: json.timestamp,\n value: json.value,\n };\n }\n return undefined;\n } catch (_) {\n return undefined;\n }\n};\n\n/**\n * Creates a local storage-based preference provider that keeps value in the browser\n * until it is cleaned up\n */\nexport const createLocalStoragePreferenceProvider = (storagePrefix: string) => {\n const isCadKey = (key: string) => key.startsWith(storagePrefix);\n\n const removeCadKeyPrefix = (key: string) => key.substring(storagePrefix.length);\n\n const provider: PreferenceProvider = {\n get(key) {\n if (provider.has(key)) {\n const item = localStorage.getItem(`${storagePrefix}${key}`);\n if (typeof item === 'string') {\n return getLocalStorageStoredValue(item);\n }\n }\n return undefined;\n },\n getKeys() {\n return Object.getOwnPropertyNames(localStorage).filter(isCadKey).map(removeCadKeyPrefix);\n },\n has(key) {\n return localStorage.hasOwnProperty(`${storagePrefix}${key}`);\n },\n remove(key) {\n localStorage.removeItem(`${storagePrefix}${key}`);\n },\n set(key, value) {\n localStorage.setItem(`${storagePrefix}${key}`, JSON.stringify(value));\n },\n };\n\n return provider;\n};\n\n/**\n * Creates a preference provider for a single instance of the preferences.\n * Since preferences are instantiated along with CAD, these preferences\n * are per CAD instance\n */\nexport const createInstancePreferenceProvider = () => {\n const storage: { [k: string]: StoredValue } = {};\n const provider: PreferenceProvider = {\n get(key) {\n if (provider.has(key)) {\n return storage[key];\n }\n return undefined;\n },\n getKeys() {\n return Object.getOwnPropertyNames(storage);\n },\n has(key) {\n return storage.hasOwnProperty(key);\n },\n remove(key) {\n delete storage[key];\n },\n set(key, value) {\n storage[key] = value;\n },\n };\n return provider;\n};\n","import {\n ExpirationType,\n PreferenceDescriptor,\n PreferenceScope,\n UserScope,\n} from './preference-descriptor-types';\nimport {\n createInstancePreferenceProvider,\n createLocalStoragePreferenceProvider,\n PreferenceProvider,\n} from './preference-providers';\nimport {\n GeneralPreferenceDescriptors,\n GetPreference,\n getPreferenceIds,\n KeysWithValuesOfType,\n TypedPreferenceDescriptors,\n} from './preference-utils';\n\nexport type CurrentScope = {\n getUserId: () => string | null;\n getProjectId: () => string | null;\n getDesignId: () => string | null;\n};\n\nexport const isDateMoreThanOneDayIntoTheFuture = (timestamp: number) =>\n timestamp > Date.now() + 24 * 60 * 60 * 1000;\n\nexport const isPastExpiryDate = (timestamp: number, maxDurationMs: number) =>\n Date.now() > timestamp + maxDurationMs;\n\n/**\n * Preferences are our way of storing user-, design-, project- and app-based user-entered\n * preferences. Preferences may be acquired and cleared via interactions with forms or, if\n * needed, via a dedicated page. Preferences are meant to be type-validated, type-safe and\n * geared towards long-term storage. Backwards compatibility and cleanup implications:\n * 1. Preferences must be backwards compatible. If we want to preserve the preference, then\n * `storagePrefix` and preference IDs should not change, and `isValid` of the preference\n * should remain `true` continuously (i.e. schema needs to be backwards compatible)\n * 2. The current maximum total storage should not exceed 5 megabytes, which should be\n * sufficient for a lot of preferences. But, in order to keep that well below the limit,\n * preferences should utilize `MaxCount` or `MaxDuration` expiry type as much as possible\n * 3. Cleanup (removal of stored preference) is performed when the number of preferences with\n * the same ID exceeds max count or max duration (depending on its expiry type), when the\n * setting's `isValid` returns false (e.g. when the schema changes in incompatible ways),\n * or if the setting ID was removed\n * 4. We can evolve preference's expiry type over time and the preference should automatically\n * be able to adapt to it. It is noteworthy that, as it stands, patching preference's scope\n * and user scope will not make the preference automatically get inherited. For the preference\n * to be retrieved correctly, it must have the exact same scope as at the time of storage.\n * This behavior can be changed eventually, which is why there is no preference cleanup\n * for preferences whose scope has changed since the preference introduction\n *\n * General note: preferences are designed to remove the need to write migrations, have a\n * clear cleanup strategy and provide type safety and type convenience throughout the\n * entirety of the codebase\n *\n * This function creates a preference manager for namespaced handling of preferences.\n * Provided `preferenceNames` and `preferenceDescriptors`\n * must satisfy the following constraints:\n * 1. `preferenceNames` is a map between meaningless preference IDs and\n * meaningful preference names\n * 2. Every key of `preferenceDescriptors` should be a preference name\n * defined in `preferenceNames` and vice versa\n * 3. `preferenceDescriptors` should be an object where every key matches\n * `PreferenceDescriptor` type\n */\nexport const createPreferencesManager = <\n PreferenceNames extends object,\n PreferenceDescriptors extends object,\n>(\n preferenceNames: PreferenceNames,\n preferenceDescriptors: PreferenceDescriptors,\n storagePrefix: string,\n) => {\n type Preference = GetPreference;\n\n /**\n * Various type checks for PreferenceNames and PreferenceDescriptors. This error\n * will be displayed as a result type if the type error occurs\n */\n type PreferenceTypeError = Preference['Name'] extends keyof PreferenceDescriptors\n ? keyof PreferenceDescriptors extends Preference['Name']\n ? PreferenceDescriptors extends GeneralPreferenceDescriptors\n ? PreferenceDescriptors extends TypedPreferenceDescriptors<\n Preference['Names'],\n PreferenceDescriptors\n >\n ? null\n : 'Every descriptor should match PreferenceDescriptor'\n : 'Preference descriptors should be an object where values match PreferenceDescriptor'\n : 'Every key of preferenceDescriptors should appear in preferenceNames and vice versa'\n : 'Every key of preferenceDescriptors should appear in preferenceNames and vice versa';\n\n type PreferenceName = Preference['Name'] & keyof PreferenceDescriptors;\n\n type GetPreferenceValue =\n PreferenceDescriptors[Name] extends { isValid: (value: unknown) => value is infer U }\n ? U\n : never;\n\n type GetPreferenceDescriptor = PreferenceDescriptor<\n GetPreferenceValue\n >;\n\n /**\n * This is a helper type that allows us to type-check and provide intellisense\n * autocomplete for a map between an action and its corresponding preference\n * property. The first argument the action is called with must be equal to the type\n * of the preference property\n */\n type ActionPreferenceNames = {\n [ActionName in keyof Actions]?: Actions[ActionName] extends (value: infer U) => void\n ? KeysWithValuesOfType>, Exclude>\n : never;\n };\n\n /**\n * The map from preference name back to preference ID\n */\n const preferenceIds = getPreferenceIds(preferenceNames);\n\n const createPreferences = (currentScope: CurrentScope) => {\n const localStorageProvider = createLocalStoragePreferenceProvider(storagePrefix);\n const instanceProvider = createInstancePreferenceProvider();\n const providers = [localStorageProvider, instanceProvider];\n\n const getProvider = (descriptor: PreferenceDescriptor): PreferenceProvider => {\n if (descriptor.expirationType === ExpirationType.Instance) {\n return instanceProvider;\n }\n return localStorageProvider;\n };\n\n const getDescriptor = (name: Name) => {\n return preferenceDescriptors[name] as unknown as GetPreferenceDescriptor;\n };\n\n const getCurrentProviderKey = (name: Name): string => {\n const preferenceId = String(preferenceIds[name]);\n const descriptor = getDescriptor(name);\n const userId = currentScope.getUserId();\n const projectId = currentScope.getProjectId();\n const designId = currentScope.getDesignId();\n let prefix = `pref_id:${preferenceId}`;\n if (userId && descriptor.userScope === UserScope.PerUser) {\n prefix = `${prefix}/user_id:${userId}`;\n }\n if (\n projectId &&\n (descriptor.preferenceScope === PreferenceScope.Project ||\n descriptor.preferenceScope === PreferenceScope.Design)\n ) {\n if (designId && descriptor.preferenceScope === PreferenceScope.Design) {\n return `${prefix}/project_id:${projectId}/design_id:${designId}`;\n }\n return `${prefix}/project_id:${projectId}`;\n }\n return prefix;\n };\n\n const has = (name: Name): boolean => {\n const providerKey = getCurrentProviderKey(name);\n const descriptor = getDescriptor(name);\n const provider = getProvider(descriptor);\n return provider.has(providerKey);\n };\n\n const get = (name: Name): GetPreferenceValue | undefined => {\n const providerKey = getCurrentProviderKey(name);\n const descriptor = getDescriptor(name);\n const provider = getProvider(descriptor);\n const storedValue = provider.get(providerKey);\n\n // In case \"get\" is performed before the cleanup is triggered,\n // it is valuable to check for validity in case schema changed\n // since last stored value\n if (storedValue && descriptor.isValid(storedValue.value)) {\n if (\n descriptor.expirationType === ExpirationType.MaxDuration &&\n (isDateMoreThanOneDayIntoTheFuture(storedValue.timestamp) ||\n isPastExpiryDate(storedValue.timestamp, descriptor.maxDurationMs))\n ) {\n return undefined;\n }\n return storedValue.value;\n }\n return undefined;\n };\n\n const set = (\n name: Name,\n value: GetPreferenceValue,\n ): void => {\n const providerKey = getCurrentProviderKey(name);\n const descriptor = getDescriptor(name);\n const provider = getProvider(descriptor);\n provider.set(providerKey, {\n timestamp: Date.now(),\n value,\n });\n };\n\n const remove = (name: Name): void => {\n const providerKey = getCurrentProviderKey(name);\n const descriptor = getDescriptor(name);\n const provider = getProvider(descriptor);\n provider.remove(providerKey);\n };\n\n /**\n * Wrapper function for automatically adjusting preferences whenever\n * actions are called. This is geared towards preferences that are strictly\n * typed objects. To wrap actions, provide an object that contains\n * original actions and an object representing a map between an action\n * and its corresponding preference property. Returns a new object\n * with wrapped actions\n */\n const wrapActions = (\n name: Name,\n actions: Actions,\n actionPreferenceNames: ActionPreferenceNames,\n ): Actions => {\n const newActions = { ...actions };\n Object.keys(actionPreferenceNames).forEach((actionName: string) => {\n const property = actionPreferenceNames[actionName];\n newActions[actionName] = (newValue: unknown): unknown => {\n const returnedValue = actions[actionName](newValue);\n const preferences: unknown = get(name) ?? {};\n if (preferences && typeof preferences === 'object') {\n let result: object;\n if (newValue === undefined) {\n result = { ...preferences };\n delete result[property];\n } else {\n result = {\n ...preferences,\n [property]: newValue,\n };\n }\n set(name, result as GetPreferenceValue);\n }\n return returnedValue;\n };\n });\n return newActions;\n };\n\n const getIdAndDescriptor = (providerKey: string) => {\n const prefIdPrefix = 'pref_id:';\n const preferenceId =\n providerKey\n .split('/')\n .find((value) => value.startsWith(prefIdPrefix))\n ?.substring(prefIdPrefix.length) ?? '';\n const name: PreferenceName | undefined = preferenceNames[preferenceId];\n const descriptor = name && getDescriptor(name);\n return { descriptor, preferenceId };\n };\n\n /**\n * A function for performing preference cleanup. The cleanup is for\n * making sure preferences that were removed from codebase, got expired\n * or exceed max count are cleaned up from the browser. It also ensures\n * that the value is stored in the correct provider in case the property\n * changes a provider\n */\n const cleanup = () => {\n providers.forEach((provider) => {\n const maxCountKeys: { [k: string]: Array<[timestamp: number, providerKey: string]> } = {};\n\n /**\n * If the preference changed providers, remove the value from\n * the old provider and store it in the new one\n */\n provider.getKeys().forEach((providerKey) => {\n const { descriptor } = getIdAndDescriptor(providerKey);\n if (!descriptor) {\n return;\n }\n const expectedProvider = getProvider(descriptor);\n if (provider !== expectedProvider) {\n const storedValue = provider.get(providerKey);\n if (storedValue) {\n provider.remove(providerKey);\n expectedProvider.set(providerKey, storedValue);\n }\n }\n });\n\n provider.getKeys().forEach((providerKey) => {\n const { preferenceId, descriptor } = getIdAndDescriptor(providerKey);\n const storedValue = provider.get(providerKey);\n if (\n // If the stored value is invalid (e.g. user-modified):\n !storedValue ||\n // If preference ID was deleted from our codebase:\n !(preferenceId in preferenceNames) ||\n !descriptor ||\n // If the value no longer matches schema:\n !descriptor.isValid(storedValue.value) ||\n // If the value expired:\n (descriptor.expirationType === ExpirationType.MaxDuration &&\n (isDateMoreThanOneDayIntoTheFuture(storedValue.timestamp) ||\n isPastExpiryDate(storedValue.timestamp, descriptor.maxDurationMs)))\n ) {\n provider.remove(providerKey);\n } else if (descriptor && descriptor.expirationType === ExpirationType.MaxCount) {\n // Gathering information about values possibly exceeding max count\n if (!maxCountKeys[preferenceId]) {\n maxCountKeys[preferenceId] = [];\n }\n maxCountKeys[preferenceId].push([storedValue.timestamp, providerKey]);\n }\n });\n\n // Clean up settings that exceeded max count\n Object.keys(maxCountKeys).forEach((preferenceId) => {\n const maxCountKey = maxCountKeys[preferenceId];\n const name: PreferenceName = preferenceNames[preferenceId];\n const descriptor = getDescriptor(name);\n if (descriptor.expirationType === ExpirationType.MaxCount) {\n const countDiff = maxCountKey.length - descriptor.maxCount;\n if (countDiff > 0) {\n maxCountKey\n .sort(([t1], [t2]) => t1 - t2)\n .forEach(([, providerKey], i) => {\n if (i < countDiff) {\n provider.remove(providerKey);\n }\n });\n }\n }\n });\n });\n };\n\n return {\n cleanup,\n get,\n has,\n remove,\n set,\n wrapActions,\n };\n };\n\n const manager = { createPreferences };\n return manager as PreferenceTypeError extends null ? typeof manager : PreferenceTypeError;\n};\n","import { BaseSchema, InferType } from 'yup';\n\nimport { PreferenceDescriptor } from './preference-descriptor-types';\n\nexport type GetPreference = {\n Names: PreferenceNames;\n Id: keyof PreferenceNames;\n Name: PreferenceNames[keyof PreferenceNames] extends string | number | symbol\n ? PreferenceNames[keyof PreferenceNames]\n : never;\n};\n\nexport type GeneralPreferenceDescriptors = {\n [K in GetPreference['Name']]: PreferenceDescriptor;\n};\n\nexport type TypedPreferenceDescriptors<\n PreferenceNames,\n Descriptors extends GeneralPreferenceDescriptors,\n> = {\n [K in keyof Descriptors]: Descriptors[K] extends PreferenceDescriptor\n ? PreferenceDescriptor\n : never;\n};\n\n/**\n * Inverts a map from ID to name to be from name to ID\n */\nexport const getPreferenceIds = (\n preferenceNames: PreferenceNames,\n) => {\n type Preference = GetPreference;\n\n type GetPrefIdFromPrefName = {\n [K in Preference['Id']]: PrefName extends Preference['Names'][K] ? K : never;\n }[Preference['Id']];\n\n type PreferenceIds = {\n [K in Preference['Name']]: GetPrefIdFromPrefName;\n };\n\n const result = {} as object;\n Object.entries(preferenceNames).forEach(([key, value]) => {\n result[value] = key as Preference['Id'];\n });\n return result as PreferenceIds;\n};\n\n/**\n * Returns an \"isValid\" check based on Yup schema. Additionally\n * fixes Yup's optional field behavior\n */\nexport const schemaCheck = (schema: T) => {\n type InferredType = T extends {\n __inputType: unknown;\n __outputType: unknown;\n }\n ? InferType\n : never;\n\n type PickUndefined = {\n [Key in keyof InferredType as undefined extends InferredType[Key]\n ? Key\n : never]: InferredType[Key];\n };\n\n type PickRequired = {\n [Key in keyof InferredType as undefined extends InferredType[Key]\n ? never\n : Key]: InferredType[Key];\n };\n\n /**\n * Note: this fixes an issue with Yup typescript where optional fields are\n * still required in the schema. Here, if a field can be undefined, it is\n * also considered optional\n */\n type SchemaType = {\n [Key in keyof PickUndefined]?: InferredType[Key];\n } & {\n [Key in keyof PickRequired]: InferredType[Key];\n };\n\n return (value: unknown): value is SchemaType => {\n return (schema as unknown as BaseSchema).isValidSync(value);\n };\n};\n\n/**\n * Gets keys of a type T where values are of type V\n */\nexport type KeysWithValuesOfType = keyof {\n /**\n * Note: \"T[P] extends V && V extends T[P]\" is equivalent to saying that\n * T[P] and V are completely equal types\n */\n [P in keyof T as T[P] extends V ? (V extends T[P] ? P : never) : never]: P;\n};\n","/* eslint-disable sort-keys */\nimport * as yup from 'yup';\nimport { ExpirationType, PreferenceScope } from './preference-descriptor-types';\nimport { createPreferencesManager, CurrentScope } from './preference-manager';\nimport { schemaCheck } from './preference-utils';\n\n/**\n * Prefix for local storage of CAD preferences. This should not change once\n * it goes in production, otherwise this would wipe out all preferences\n */\nconst CAD_PREFERENCE_STORAGE_PREFIX = 'CAD_PREF::';\n\n/**\n * An object that maps a preference ID to a meaningful name. The preference ID\n * should be meaningless so that it may be repurposed. We may add new IDs, remove\n * old IDs (in which case the preference will be cleaned up and removed from storage),\n * but we may never repeat previously used IDs. For that reason, we use an ID schema\n * \"p###\"\" where \"###\" are ever-increasing numbers. If we have to remove an ID with\n * the highest number, we should leave a comment here\n */\nconst preferenceNames = {\n p000: 'panelPlaceMode',\n} as const;\n\n/**\n * Descriptors for every preference. Every preference in `preferenceNames` must be\n * defined and correspond to PreferenceDescriptor. Schema should only change in\n * backwards compatible ways, otherwise the preference will be invalidated and cleaned\n * up. It is also important that these types are fully defined here rather than\n * being imported from other places to avoid accidental changes to the schema. When\n * adding or modifying preferences, it's vital to make sure that\n * `cad-preference-compatibility.test.ts` passes and that we add new test cases for\n * any new preferences / preference changes to keep them backwards compatible as the\n * schema evolves\n *\n * Reminder, preferences are our way of storing user-, design-, project- and app-based\n * user-entered preferences. Preferences may be acquired and cleared via interactions with\n * forms or, if needed, via a dedicated page. Preferences are meant to be type-validated,\n * type-safe and geared towards long-term storage with all the backwards compatibility\n * implications that are described in `createPreferencesManager`\n */\nconst preferenceDescriptors = {\n panelPlaceMode: {\n preferenceScope: PreferenceScope.Design,\n expirationType: ExpirationType.MaxCount,\n maxCount: 50,\n isValid: schemaCheck(\n yup\n .object({\n dcOptimizerId: yup.string().nullable(),\n microinverterId: yup.string().nullable(),\n solarPanelId: yup.string().nullable(),\n minSap: yup.number(),\n\n pitchedThreshold: yup.number(),\n\n flatTilt: yup.number(),\n flatRotation: yup.number(),\n flatIntermoduleSpacingX: yup.number(),\n flatRowSpacing: yup.number(),\n flatOrientation: yup.mixed<'L' | 'P'>().oneOf(['L', 'P']),\n\n pitchedTilt: yup.number(),\n pitchedRotation: yup.number(),\n pitchedIntermoduleSpacingX: yup.number(),\n pitchedRowSpacing: yup.number(),\n pitchedOrientation: yup.mixed<'L' | 'P'>().oneOf(['L', 'P']),\n })\n .required(),\n ),\n },\n} as const;\n\nconst cadPreferencesManager = createPreferencesManager(\n preferenceNames,\n preferenceDescriptors,\n CAD_PREFERENCE_STORAGE_PREFIX,\n);\n\nexport type CadPreferences = ReturnType;\n\nexport const createCadPreferences = (currentScope: CurrentScope) => {\n const preferences = cadPreferencesManager.createPreferences(currentScope);\n /**\n * Cleanup is performed right after preference initialization during\n * browser's idle period in order to slightly speed up CAD initialization.\n * Done immediately for browsers that don't support `requestIdleCallback`\n * like Safari\n */\n if ('requestIdleCallback' in window) {\n requestIdleCallback(preferences.cleanup);\n } else {\n preferences.cleanup();\n }\n return preferences;\n};\n","import { performance } from '@aurorasolar/common-performance';\n\nconst { AutoDesignerStart, AutoDesignerFinished } = performance.MarkName;\nconst { AutoDesignerDuration } = performance.MeasureName;\n\nexport type AutoDesignerData = {\n isAutoDesignerRunning: boolean;\n};\n\nexport const createAutoDesignerData = (): AutoDesignerData => {\n return {\n isAutoDesignerRunning: false,\n };\n};\n\nexport const createAutoDesignerActions = (autoDesignerData: AutoDesignerData) => {\n return {\n autoDesignerFinish: () => {\n autoDesignerData.isAutoDesignerRunning = false;\n performance.mark(AutoDesignerFinished);\n performance.measure(AutoDesignerDuration, AutoDesignerStart, AutoDesignerFinished);\n },\n autoDesignerStart: () => {\n autoDesignerData.isAutoDesignerRunning = true;\n performance.mark(AutoDesignerStart);\n },\n };\n};\n","export enum ModalType {\n None,\n Nearmap,\n Vexcel,\n}\n\nexport enum OverlayType {\n DesignSettings,\n}\n\nexport enum DesignSettingsTab {\n System = 'design-settings-system-tab',\n Simulation = 'design-settings-simulation-tab',\n}\n\nexport type OverlayData = {\n type: OverlayType.DesignSettings;\n data: {\n tab: DesignSettingsTab;\n };\n};\n\nexport type ModalData = {\n activeModal: ModalType;\n activeOverlays: OverlayData[];\n};\n\nexport const createModalData = (): ModalData => {\n return {\n activeModal: ModalType.None,\n activeOverlays: [],\n };\n};\n\nexport const createModalActions = (modalData: ModalData) => {\n return {\n closeModal: () => {\n modalData.activeModal = ModalType.None;\n },\n closeOverlay: (overlayType: OverlayType) => {\n const index = modalData.activeOverlays.findIndex((overlayDatum) => {\n return overlayDatum.type === overlayType;\n });\n if (index !== -1) {\n modalData.activeOverlays.splice(index, 1);\n }\n },\n openModal: (modalType: ModalType) => {\n modalData.activeModal = modalType;\n },\n openOverlay: (overlayData: OverlayData) => {\n const index = modalData.activeOverlays.findIndex((overlayDatum) => {\n return overlayDatum.type === overlayData.type;\n });\n if (index === -1) {\n modalData.activeOverlays.push(overlayData);\n }\n },\n setDesignSettingsTab: (designSettingsTab: DesignSettingsTab) => {\n modalData.activeOverlays.forEach((overlayDatum) => {\n if (overlayDatum.type === OverlayType.DesignSettings) {\n overlayDatum.data.tab = designSettingsTab;\n }\n });\n },\n };\n};\n","import { HistoryData } from '../cad-engine-state';\n\nexport type SaveData = {\n isSaving: boolean;\n hasUnsavedChanges: boolean;\n recentSavedVersion: string | null;\n};\n\nexport const createSaveData = (historyData: HistoryData): SaveData => {\n return {\n get hasUnsavedChanges() {\n return this.recentSavedVersion !== historyData.recentVersion;\n },\n isSaving: false,\n recentSavedVersion: historyData.recentVersion,\n };\n};\n\nexport const createSaveActions = (saveData: SaveData) => {\n return {\n finishSaving: (saveVersion: string) => {\n saveData.isSaving = false;\n saveData.recentSavedVersion = saveVersion;\n },\n startSaving: () => {\n saveData.isSaving = true;\n },\n };\n};\n","/* eslint-disable sort-keys */\nimport {\n createAutoDesignerActions,\n createAutoDesignerData,\n} from './auto-designer-state/auto-designer-state';\nimport { CadEngineState } from './cad-engine-state';\nimport { markDeepReadonly } from './deep-readonly-util';\nimport { makeReactive, provideCadStateTrace } from './framework';\nimport { createModalActions, createModalData } from './modal-state/modal-state';\nimport { createPrismActions, createPrismData } from './prism-state/prism-state';\nimport { createSaveActions, createSaveData } from './save-state/save-state';\nimport { createSelectedTypesData } from './selected-types/selected-types-state';\n\nexport type CadState = ReturnType;\n\n/**\n * Creates CAD state that React components will be able to subscribe to\n *\n * CAD state is meant for combining and managing CAD-related V2 state tied to a single CAD instance. It\n * is meant for managing CAD-wide data related to forms, modals, interactions, operations in progress, etc.\n * The returned state combines V2-specific CAD state with CAD engine state (state maintained by CAD engine\n * itself). CAD state should not contain class instances or React nodes. The entirety of CAD state data should\n * be comprised of simple JS objects containing primitive values or other simple JS objects, and CAD state\n * actions should only contain functions that can take primitive values or simple JS objects\n */\nexport const createCadState = (cadEngineState: CadEngineState) => {\n if (process.env.NODE_ENV === 'development') {\n provideCadStateTrace();\n }\n\n const selectedTypeData = makeReactive(createSelectedTypesData(cadEngineState));\n const modalData = makeReactive(createModalData());\n const modalActions = makeReactive(createModalActions(modalData));\n const autoDesignerData = makeReactive(createAutoDesignerData());\n const autoDesignerActions = makeReactive(createAutoDesignerActions(autoDesignerData));\n const saveData = makeReactive(createSaveData(cadEngineState.data.historyData));\n const saveActions = makeReactive(createSaveActions(saveData));\n const prismData = makeReactive(createPrismData());\n const prismActions = makeReactive(createPrismActions(prismData));\n\n return {\n data: markDeepReadonly({\n autoDesignerData,\n ...cadEngineState.data,\n modalData,\n prismData,\n saveData,\n selectedTypeData,\n }),\n actions: {\n autoDesignerActions,\n ...cadEngineState.actions,\n modalActions,\n prismActions,\n saveActions,\n },\n stopEffects: {\n ...cadEngineState.stopEffects,\n },\n };\n};\n\n/**\n * Cleans up CAD state by stopping all of its effects\n */\nexport const stopCadStateEffects = (cadState: CadState) => {\n const items: Record void>> = cadState.stopEffects;\n Object.keys(items).forEach((stopEffectMapKey) => {\n const stopEffectMap = items[stopEffectMapKey];\n Object.keys(stopEffectMap).forEach((stopEffectKey) => {\n const stopEffect = stopEffectMap[stopEffectKey];\n stopEffect();\n });\n });\n};\n","import { CadEngineState, CadSelectionType } from '../cad-engine-state';\n\nexport const createSelectedTypesData = (cadEngineState: CadEngineState) => {\n return {\n get selectedTypes() {\n return Object.entries(cadEngineState.data.selectionData).reduce(\n (types, [type, { count }]) => (count > 0 ? [...types, type] : types) as CadSelectionType[],\n [] as CadSelectionType[],\n );\n },\n };\n};\n","export type PrismData = {\n isPrismCadOpen: boolean;\n};\n\nexport const createPrismData = (): PrismData => {\n return {\n isPrismCadOpen: false,\n };\n};\n\nexport const createPrismActions = (prismData: PrismData) => {\n return {\n toggleIsPrismCadOpen: (newState: boolean) => {\n prismData.isPrismCadOpen = newState;\n },\n };\n};\n","// @ts-ignore: Ignore unused { * as Types } import\nimport * as Types from '@aurorasolar/graphql-client-schema';\n\nimport { gql } from '@apollo/client';\nimport * as Apollo from '@apollo/client';\nconst defaultOptions = {} as const;\nexport type GetUserInfoQueryVariables = Types.Exact<{ [key: string]: never; }>;\n\n\nexport type GetUserInfoQuery = { __typename: 'Query', currentUser?: { __typename: 'User', id: string } | null | undefined };\n\nexport type CreateBssUploadUrlsMutationVariables = Types.Exact<{\n createBSSUploadUrlsInput: Types.CreateBssUploadUrlsInput;\n}>;\n\n\nexport type CreateBssUploadUrlsMutation = { __typename: 'Mutation', createBSSUploadUrls?: Array<{ __typename: 'CreateFileBSSUploadUrl', blobId?: string | null | undefined, contentSha256?: string | null | undefined, uploadNeeded?: boolean | null | undefined, uploadUrl?: string | null | undefined, mandatoryUploadHeaders?: Array<{ __typename: 'MandatoryHeader', name?: string | null | undefined, value?: string | null | undefined } | null | undefined> | null | undefined } | null | undefined> | null | undefined };\n\n\nexport const GetUserInfoDocument = gql`\n query GetUserInfo @trace_info(traceInfo: {pod: proposals}) {\n currentUser {\n id\n }\n}\n `;\n\n/**\n * __useGetUserInfoQuery__\n *\n * To run a query within a React component, call `useGetUserInfoQuery` and pass it any options that fit your needs.\n * When your component renders, `useGetUserInfoQuery` returns an object from Apollo Client that contains loading, error, and data properties\n * you can use to render your UI.\n *\n * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;\n *\n * @example\n * const { data, loading, error } = useGetUserInfoQuery({\n * variables: {\n * },\n * });\n */\nexport function useGetUserInfoQuery(baseOptions?: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(GetUserInfoDocument, options);\n }\nexport function useGetUserInfoLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useLazyQuery(GetUserInfoDocument, options);\n }\nexport type GetUserInfoQueryHookResult = ReturnType;\nexport type GetUserInfoLazyQueryHookResult = ReturnType;\nexport type GetUserInfoQueryResult = Apollo.QueryResult;\nexport const CreateBssUploadUrlsDocument = gql`\n mutation CreateBSSUploadUrls($createBSSUploadUrlsInput: CreateBSSUploadUrlsInput!) @trace_info(traceInfo: {pod: proposals}) {\n createBSSUploadUrls(createBSSUploadUrlsInput: $createBSSUploadUrlsInput) {\n blobId\n contentSha256\n uploadNeeded\n uploadUrl\n mandatoryUploadHeaders {\n name\n value\n }\n }\n}\n `;\nexport type CreateBssUploadUrlsMutationFn = Apollo.MutationFunction;\n\n/**\n * __useCreateBssUploadUrlsMutation__\n *\n * To run a mutation, you first call `useCreateBssUploadUrlsMutation` within a React component and pass it any options that fit your needs.\n * When your component renders, `useCreateBssUploadUrlsMutation` returns a tuple that includes:\n * - A mutate function that you can call at any time to execute the mutation\n * - An object with fields that represent the current status of the mutation's execution\n *\n * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;\n *\n * @example\n * const [createBssUploadUrlsMutation, { data, loading, error }] = useCreateBssUploadUrlsMutation({\n * variables: {\n * createBSSUploadUrlsInput: // value for 'createBSSUploadUrlsInput'\n * },\n * });\n */\nexport function useCreateBssUploadUrlsMutation(baseOptions?: Apollo.MutationHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useMutation(CreateBssUploadUrlsDocument, options);\n }\nexport type CreateBssUploadUrlsMutationHookResult = ReturnType;\nexport type CreateBssUploadUrlsMutationResult = Apollo.MutationResult;\nexport type CreateBssUploadUrlsMutationOptions = Apollo.BaseMutationOptions;","import { useCallback, useRef } from 'react';\n\nimport { ApolloClient, FileUploadHandler, useAppModule } from '@aurorasolar/common-module-loader';\n\nimport {\n GetUserInfoDocument,\n GetUserInfoQuery,\n GetUserInfoQueryVariables,\n useCreateBssUploadUrlsMutation,\n} from '../file-uploader.generated';\n\nexport const useCreateBssUploadUrls = () => {\n const userId = useRef();\n const fileUploader = useAppModule(FileUploadHandler);\n const client = useAppModule(ApolloClient);\n\n const fetchUserId = useCallback(async () => {\n if (!client) {\n throw new Error('Apollo Client is not initialized');\n }\n\n if (userId.current) {\n return userId.current;\n }\n\n const userData = await client.query({\n fetchPolicy: 'cache-first',\n query: GetUserInfoDocument,\n });\n\n const newUserId = userData.data.currentUser?.id;\n userId.current = newUserId;\n return newUserId;\n }, [client]);\n\n const [createBssUploadUrls] = useCreateBssUploadUrlsMutation();\n\n const fetchBssUploadUrls = useCallback(\n async (files: File[]) => {\n let currentUserId = userId.current;\n if (!currentUserId) {\n try {\n currentUserId = await fetchUserId();\n } catch {\n throw new Error('Failed to fetch userId');\n }\n }\n\n // Fetch worked but still came back undefined\n if (!currentUserId) {\n throw new Error('Cannot request BSS Urls without a userId');\n }\n\n if (!fileUploader?.hashFile) {\n throw new Error('fileUploader must be ready to use');\n }\n\n const bssUploadInputsPromises = files.map(async (file) => {\n const hash = (await fileUploader?.hashFile?.(file)) ?? '';\n return {\n blobName: file.name,\n contentLength: file.size,\n contentSha256: hash,\n mimeType: file.type,\n };\n });\n\n const bssUploadInputs = await Promise.all(bssUploadInputsPromises);\n\n try {\n const result = await createBssUploadUrls({\n variables: {\n createBSSUploadUrlsInput: {\n files: bssUploadInputs,\n id: currentUserId,\n },\n },\n });\n\n return result.data?.createBSSUploadUrls;\n } catch (e) {\n throw new Error(`Failed to fetch BSS Upload tokens ${e}`);\n }\n },\n [fileUploader, createBssUploadUrls, fetchUserId],\n );\n\n return fileUploader ? fetchBssUploadUrls : undefined;\n};\n","import { useCallback } from 'react';\n\nimport { useStartAsyncJobMutation } from '@aurorasolar/common-data-access-layer';\nimport { ApolloClient, AsyncJob, useAppModule } from '@aurorasolar/common-module-loader';\nimport {\n AsyncJobType,\n FileUploaderResult,\n UserFileLabel,\n} from '@aurorasolar/graphql-client-schema';\n\nexport const useUploadFileAsyncJob = () => {\n const [startAsyncJob] = useStartAsyncJobMutation();\n const invalidateJobs = useAppModule(AsyncJob)?.invalidateJobs;\n const client = useAppModule(ApolloClient);\n\n const runUploadFileAsyncJob = useCallback(\n async (\n temporaryBlobId: string,\n fileName: string,\n label: UserFileLabel,\n mimeType: string,\n parentId?: string,\n parentType?: string,\n parentRoleType?: string,\n ) => {\n try {\n const result = await startAsyncJob({\n variables: {\n settings: {\n fileName,\n label,\n mimeType,\n parentId,\n parentRoleType,\n parentType,\n temporaryBlobId,\n },\n type: AsyncJobType.FileUploader,\n },\n });\n\n return result?.data?.startAsyncJob as FileUploaderResult;\n } catch (e) {\n throw new Error(`Upload File async job failed ${e}`);\n }\n },\n [startAsyncJob],\n );\n\n const invalidateUploadFileAsyncJob = useCallback(\n (id) => {\n invalidateJobs?.([`file_uploader_${id}`]);\n },\n [invalidateJobs],\n );\n\n return {\n invalidateUploadFileAsyncJob: invalidateJobs ? invalidateUploadFileAsyncJob : undefined,\n runUploadFileAsyncJob: client ? runUploadFileAsyncJob : undefined,\n };\n};\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { generateUuid } from '@aurorasolar/common-core/src/utils';\nimport { FileUploadHandler, useAppModule } from '@aurorasolar/common-module-loader';\nimport { UserFileLabel } from '@aurorasolar/graphql-client-schema';\n\nimport { FileResult, FileResultUploadStatus, getFileResultType } from '../common';\nimport { useCreateBssUploadUrls } from './use-create-bss-upload-urls';\nimport { useUploadFileAsyncJob } from './use-upload-file-async-job';\n\nexport const SERVER_ERROR_MESSAGE = 'Failed to upload to server';\n\nconst fileResultNotInProgress = (fileResult: FileResult): boolean => {\n return fileResult.status !== FileResultUploadStatus.IN_PROGRESS;\n};\n\nexport interface UserFileOptions {\n label: UserFileLabel;\n parentId?: string;\n parentType?: string;\n parentRoleType?: string;\n}\n\nexport const useUploadFiles = (userFileOptions: UserFileOptions) => {\n // Store fileResults in a ref so that they can be accessed inside a useCallback function without stale values\n // Store in object so that getting fileResult by ID is quicker\n const fileMap = useRef<{ [key: string]: FileResult }>({});\n // fileResults is an array of references to items in the fileMap\n // keeps ordering of files, when updated allows for rerender to give updated results\n const [fileResults, setFileResults] = useState([]);\n\n // Needed to get the signed urls for uploading file directly\n const fetchBssUploadUrls = useCreateBssUploadUrls();\n // fileUploader.uploadToSignedUrl makes POST request to upload file to signed url\n const fileUploader = useAppModule(FileUploadHandler);\n // runUploadFileAsyncJob used to tell BE file is ready to run validations on\n // returns results of successful validated UserFiles or validation errors\n // invalidateUploadFileAsyncJob is used to cancel the asyncJob if the file upload is canceled\n const { runUploadFileAsyncJob, invalidateUploadFileAsyncJob } = useUploadFileAsyncJob();\n\n const updateFileResult = useCallback((id: string, updatedOptions: Partial) => {\n setFileResults((prev) => {\n const newFileResults = [...prev];\n const updateIndex = newFileResults.findIndex((fileResult) => fileResult.id === id);\n if (updateIndex >= 0) {\n fileMap.current[id] = {\n ...newFileResults[updateIndex],\n ...updatedOptions,\n };\n newFileResults[updateIndex] = fileMap.current[id];\n\n return newFileResults;\n }\n return prev;\n });\n }, []);\n\n // Set the status of a fileResult to cancel to queue the canceling of asyncJob (if it exists)\n const cancelFileUpload = useCallback(\n (id: string) => {\n const fileResult = fileMap.current[id];\n if (\n fileResult?.status === FileResultUploadStatus.IN_PROGRESS ||\n fileResult?.status === FileResultUploadStatus.PENDING\n ) {\n updateFileResult(id, { status: FileResultUploadStatus.CANCELED });\n } else {\n console.warn(\n `Cannot cancel file upload when file result status is \"${fileResult?.status}\". Status must be \"in-progress\" or \"pending\"`,\n );\n }\n },\n [updateFileResult],\n );\n\n // Set the status of the fileResult to pending to re-queue the file for upload\n const retryFileUpload = useCallback(\n (id: string) => {\n const fileResult = fileMap.current[id];\n if (\n fileResult?.status === FileResultUploadStatus.NON_VALIDATION_ERROR ||\n fileResult?.status === FileResultUploadStatus.VALIDATION_ERROR\n ) {\n updateFileResult(id, {\n errorText: undefined,\n result: undefined,\n status: FileResultUploadStatus.PENDING,\n });\n } else {\n console.warn(\n `Cannot retry file upload when file result status is \"${fileResult?.status}\". Status must be \"validation-error\" or \"non-validation-error\"`,\n );\n }\n },\n [updateFileResult],\n );\n\n // Remove a fileResult from the array (used after canceling completed)\n const removeFileUpload = useCallback((id: string) => {\n setFileResults((prev) => {\n const newFileResults = [...prev].filter((fileResult) => fileResult.id !== id);\n delete fileMap.current[id];\n return newFileResults;\n });\n }, []);\n\n const clearResults = useCallback(() => {\n setFileResults([]);\n fileMap.current = {};\n }, []);\n\n // Used to add files that failed external validation to the results list\n const addErroredFiles = useCallback((erroredFiles: { errorText: string; file: File }[]) => {\n const newErroredFileResults = erroredFiles.map(({ errorText, file }) => {\n const id = generateUuid();\n const newErroredFileResult = {\n errorText,\n file,\n fileType: getFileResultType(file.type),\n id,\n status: FileResultUploadStatus.VALIDATION_ERROR,\n };\n\n fileMap.current[id] = newErroredFileResult;\n return fileMap.current[id];\n });\n\n setFileResults((prev) => [...prev, ...newErroredFileResults]);\n }, []);\n\n const uploadFiles = useCallback(async (newFiles: File[]) => {\n const newFileResults = newFiles.map((newFile) => {\n const id = generateUuid();\n const newFileResult = {\n file: newFile,\n fileType: getFileResultType(newFile.type),\n id,\n status: FileResultUploadStatus.PENDING,\n };\n\n fileMap.current[id] = newFileResult;\n return fileMap.current[id];\n });\n\n setFileResults((prev) => [...prev, ...newFileResults]);\n }, []);\n\n // LOGIC TO UPLOAD QUEUED PENDING FILES\n useEffect(() => {\n const asyncUploadFiles = async () => {\n const pendingFileResults = fileResults.filter(\n (fileResult) => fileResult.status === FileResultUploadStatus.PENDING,\n );\n\n if (pendingFileResults.length > 0) {\n const pendingFiles = pendingFileResults.map((fileResult) => {\n updateFileResult(fileResult.id, { status: FileResultUploadStatus.IN_PROGRESS });\n return fileResult.file;\n });\n\n try {\n // Get the all the signed urls needed to upload files\n const bssUploadUrls = await fetchBssUploadUrls?.(pendingFiles);\n bssUploadUrls?.forEach(async (uploadUrl, i) => {\n const inProgressFileResult = fileMap.current[pendingFileResults[i]?.id];\n if (uploadUrl) {\n try {\n // Stop upload process early if status has changed\n if (fileResultNotInProgress(inProgressFileResult)) {\n return;\n }\n\n // Upload file directly to BSS from FE\n const blobId = await fileUploader?.uploadToSignedUrl?.(pendingFiles[i], uploadUrl);\n\n // Stop upload process early if status has changed\n if (fileResultNotInProgress(inProgressFileResult)) {\n return;\n }\n if (blobId) {\n // Start the async job to run validations for label\n const result = await runUploadFileAsyncJob?.(\n blobId,\n pendingFiles[i].name,\n userFileOptions.label,\n pendingFiles[i].type,\n userFileOptions.parentId,\n userFileOptions.parentType,\n userFileOptions.parentRoleType,\n );\n\n updateFileResult(inProgressFileResult.id, { result });\n\n // Stop upload process early if status has changed\n if (fileResultNotInProgress(inProgressFileResult)) {\n return;\n }\n\n // Full upload has finished, save the result (either success or validation error)\n if (result?.errors?.length) {\n const [firstError] = result.errors;\n updateFileResult(inProgressFileResult.id, {\n errorText: firstError,\n status: FileResultUploadStatus.VALIDATION_ERROR,\n });\n } else {\n updateFileResult(inProgressFileResult?.id, {\n status: FileResultUploadStatus.COMPLETE,\n });\n }\n }\n } catch (e) {\n // If something has errored during the individual file upload process set a non validation error\n updateFileResult(inProgressFileResult?.id, {\n errorText: SERVER_ERROR_MESSAGE,\n status: FileResultUploadStatus.NON_VALIDATION_ERROR,\n });\n }\n }\n });\n } catch (e) {\n pendingFileResults.forEach((fileResult) => {\n updateFileResult(fileResult.id, {\n errorText: SERVER_ERROR_MESSAGE,\n status: FileResultUploadStatus.NON_VALIDATION_ERROR,\n });\n });\n }\n }\n };\n\n if (fileResults && fetchBssUploadUrls && fileUploader && runUploadFileAsyncJob) {\n asyncUploadFiles();\n }\n }, [\n fileResults,\n fetchBssUploadUrls,\n updateFileResult,\n fileUploader,\n runUploadFileAsyncJob,\n userFileOptions,\n ]);\n\n // LOGIC TO CANCEL UPLOAD FOR QUEUED CANCELED FILES\n useEffect(() => {\n const cancelFileResults = fileResults.filter(\n (fileResult) => fileResult.status === FileResultUploadStatus.CANCELED,\n );\n\n if (cancelFileResults.length > 0 && invalidateUploadFileAsyncJob) {\n cancelFileResults.forEach(async (fileResult) => {\n await invalidateUploadFileAsyncJob(fileResult?.id);\n removeFileUpload(fileResult.id);\n });\n }\n }, [fileResults, removeFileUpload, invalidateUploadFileAsyncJob]);\n\n return {\n addErroredFiles,\n cancelFileUpload,\n clearResults,\n results: fileResults,\n retryFileUpload,\n uploadFiles,\n };\n};\n","import { Store } from 'redux';\nimport { filter, firstValueFrom, map, Subject } from 'rxjs';\n\nimport {\n CadEvent,\n CadEventTypes,\n CADTriggerActionTypes,\n triggerCADAction,\n} from '@aurorasolar/common-data-store';\nimport { CadEngine } from '@aurorasolar/common-module-loader';\nimport { useUploadFiles } from '@aurorasolar/file-uploader';\n\nexport interface ScreenshotDeps {\n cadEvents$: Subject>;\n designId: string;\n engine: CadEngine;\n fileUploader: ReturnType;\n reduxStore: Store;\n saveVersion: string;\n}\n\n/**\n * Adds a timeout to a Promise.\n * Throws the an error with the timeout message if the timeout is reached before the promise resolves.\n * */\nconst withTimeout = (promise: Promise, time: number, timeoutMessage: string) => {\n const timeoutPromise = new Promise((resolve) => {\n setTimeout(resolve, time);\n }).then(() => {\n throw new Error(timeoutMessage);\n });\n return Promise.race([promise, timeoutPromise]);\n};\n\n/**\n * Resolves a promise with the first screenshot event it sees with a matching id\n */\nconst listenForScreenshotResponse = (cadEvents$: Subject>, id: string) =>\n firstValueFrom(\n cadEvents$.pipe(\n filter(\n (event): event is CadEvent =>\n event.eventType === CadEventTypes.CadScreenshot && event.payload.id === id,\n ),\n map((event) => event.payload),\n ),\n );\n\n/**\n * Requests a screenshot from CAD and then uploads that screenshot\n * with the fileUploader\n */\nexport const takeSaveScreenshot = async ({\n cadEvents$,\n designId,\n engine,\n fileUploader,\n reduxStore,\n saveVersion,\n}: ScreenshotDeps) => {\n const screenshotPromise = listenForScreenshotResponse(cadEvents$, saveVersion);\n reduxStore.dispatch(\n triggerCADAction({\n actionType: CADTriggerActionTypes.TakeScreenshot,\n cadInstance: { engine },\n props: { id: saveVersion, imageType: 'png' },\n }),\n );\n const screenshotResponse = await withTimeout(\n screenshotPromise,\n 30000,\n 'Timed out taking a screenshot',\n );\n\n const screenshotFile = new File(\n [screenshotResponse.data],\n `${designId}.${screenshotResponse.imageType}`,\n { type: screenshotResponse.data.type },\n );\n\n await withTimeout(\n fileUploader.uploadFiles([screenshotFile]),\n 60000,\n 'Screenshot upload timed out',\n );\n};\n","import { CadSaveData } from '@aurorasolar/common-module-loader';\n\nimport { cadSaveCallbackCore, CadSaveCallbackDeps } from './cad-save-callback-core';\n\nexport type SaveFn = typeof cadSaveCallbackCore;\n\n/**\n * This creates a callback to be passed in to the CAD engine during setup.\n * It ensures that only one save function will run at a time.\n * Subsequent save calls will be chained on to the end of the current call.\n */\nexport const getCadSaveCallback = (saveDependencies: CadSaveCallbackDeps) => {\n let currentSave: Promise = Promise.resolve();\n\n return async (data: CadSaveData) => {\n const result = currentSave.then(() => cadSaveCallbackCore(saveDependencies, data));\n\n currentSave = result.catch(() => {});\n\n await result;\n\n if (result === currentSave) {\n currentSave = Promise.resolve();\n }\n };\n};\n","import { Store } from 'redux';\nimport { Subject } from 'rxjs';\n\nimport { ApolloClient, NormalizedCacheObject } from '@apollo/client';\nimport { CadEvent, CadEventTypes } from '@aurorasolar/common-data-store';\nimport { CadEngine, CadSaveData } from '@aurorasolar/common-module-loader';\nimport { useUploadFiles } from '@aurorasolar/file-uploader';\nimport { Query, CadUpdatedDesign, IrradianceStates } from '@aurorasolar/graphql-client-schema';\nimport type { Reference, StoreObject } from '@apollo/client';\n\nimport {\n SaveDesignDocument,\n SaveDesignMutation,\n SaveDesignMutationVariables,\n} from '../cad.generated';\nimport { CadContextType } from '../use-cad';\nimport {\n EndSavingDocument,\n EndSavingQuery,\n PreSaveDocument,\n PreSaveQuery,\n StartSavingDocument,\n StartSavingQuery,\n} from './cad-save-callback.generated';\nimport { checkCadCanSave } from './check-cad-can-save';\nimport { takeSaveScreenshot } from './take-save-screenshot';\n\nexport interface CadSaveCallbackDeps {\n apolloClient: ApolloClient;\n cadContext: CadContextType;\n cadEvents$: Subject>;\n engine: CadEngine;\n fileUploader: ReturnType;\n reduxStore: Store;\n evictCache: (fieldName: K) => void;\n evictCacheById: (storeObject: StoreObject | Reference) => void;\n}\n\n/**\n * Not to be used directly outside of `getCadSaveCallback()`.\n * This is the save callback that will be passed to the CAD engine during setup,\n * it only intended to be called by the CAD engine.\n * */\nexport const cadSaveCallbackCore = async (\n {\n apolloClient,\n reduxStore,\n engine,\n evictCache,\n evictCacheById,\n cadEvents$,\n fileUploader,\n cadContext,\n }: CadSaveCallbackDeps,\n { designId, saveVersion, jsonToSave: { site, system, designJsonSchemaVersion } }: CadSaveData,\n) => {\n if (!(await checkCadCanSave(apolloClient, designId))) {\n return;\n }\n\n const { CAD } = await apolloClient\n .query({\n fetchPolicy: 'cache-first',\n query: PreSaveDocument,\n variables: { designId },\n })\n .then(({ data }) => data);\n\n // indicate within CAD state that a save is in process\n apolloClient.writeQuery({\n data: {\n __typename: 'Query',\n CAD: { __typename: 'CAD', isSaving: true },\n },\n query: StartSavingDocument,\n });\n cadContext?.state?.actions?.saveActions.startSaving();\n\n const systemStats = cadContext?.state?.data.systemStatsData;\n\n const cadUpdatedDesign: CadUpdatedDesign = {\n carportSystemSizeStc: systemStats?.offRoofSystemSizeStc,\n design: JSON.stringify(system),\n designJsonSchemaVersion: designJsonSchemaVersion ?? 0,\n id: designId,\n irradianceMapId: CAD.irradiance.roof.mapId,\n irradianceMapStatus: CAD.irradiance.roof.status || IrradianceStates.Invalid,\n irradiancePanelsId: CAD.irradiance.panels.mapId,\n irradiancePanelsStatus: CAD.irradiance.panels.status || IrradianceStates.Invalid,\n roofSystemSizeStc: systemStats?.roofSystemSizeStc,\n site: JSON.stringify(site),\n systemSizeAc: systemStats?.systemSizeAc,\n systemSizePtc: systemStats?.systemSizePtc,\n systemSizeStc: systemStats?.systemSizeStc,\n };\n\n const savePromise = apolloClient\n .mutate({\n awaitRefetchQueries: true,\n mutation: SaveDesignDocument,\n variables: {\n cadUpdatedDesign,\n designId,\n },\n })\n .finally(() => {\n evictCache('componentSummaryByDesignId');\n evictCacheById({\n __typename: 'Design',\n id: designId,\n });\n });\n\n const screenshotPromise = takeSaveScreenshot({\n cadEvents$,\n designId,\n engine,\n fileUploader,\n reduxStore,\n saveVersion,\n }).catch((error) => {\n console.warn('Save screenshot failed');\n console.warn(error);\n });\n\n await Promise.all([savePromise, screenshotPromise]);\n\n apolloClient.writeQuery({\n data: {\n __typename: 'Query',\n CAD: {\n __typename: 'CAD',\n isSaving: false,\n recentSavedVersion: saveVersion,\n },\n },\n query: EndSavingDocument,\n });\n cadContext?.state?.actions?.saveActions.finishSaving(saveVersion);\n};\n","import { useEffect, useRef } from 'react';\nimport { Subject } from 'rxjs';\n\nimport { ApolloClient, NormalizedCacheObject } from '@apollo/client';\nimport { createCadPreferences } from '@aurorasolar/cad-preferences';\nimport {\n CadEngineState,\n cloneInert,\n createCadState,\n effect,\n makeReactive,\n stopCadStateEffects,\n} from '@aurorasolar/cad-state';\nimport { CadEvent, CadEventTypes } from '@aurorasolar/common-data-store';\nimport {\n Analytics,\n AnalyticsEventTypes,\n ApolloClient as ApolloClientModule,\n AppConfig,\n AuroraApiEnvironment,\n AuthToken,\n CadEngine,\n CadEngineOptions,\n CADLib,\n FeatureFlags,\n ICadDataServiceSettings,\n ICadFeatureGate,\n ICADGeodataService,\n IOrgPermissions,\n Notifications,\n OrgPermissions,\n ReduxStore,\n Tracking,\n useAppModule,\n} from '@aurorasolar/common-module-loader';\nimport { TOAST_CHANNEL } from '@aurorasolar/common-notifications';\nimport { useUploadFiles } from '@aurorasolar/file-uploader';\nimport { UserFileLabel } from '@aurorasolar/graphql-client-schema';\nimport { IIntlContext, SUPPORTED_LOCALES, useIntl } from '@aurorasolar/intl';\n\nimport { useEvictCache } from '@aurorasolar/common-core/src/hooks';\n\nimport { getCadSaveCallback } from '../cad-save-callback';\nimport { cleanupCad } from '../provide-cad/cleanup-cad';\nimport { getCadEventHandler, stopEvents, subscribeToCadEvent } from '../provide-cad/event-handler';\nimport { CadMode } from '../types';\nimport { getBrowserWebglInfo } from '../webgl-check';\nimport { useCadContext, useCadInitializerContext } from './cad-context';\n\nlet unknownProjectIdCount = 0;\nlet unknownDesignIdCount = 0;\n\nexport const WEBGL_ERROR = 'WebGL not supported by device';\n\nconst performUnknownProjectDesignEffect = (\n providedProjectId: string | undefined,\n providedDesignId: string | undefined,\n) => {\n if (!providedProjectId) {\n unknownProjectIdCount += 1;\n }\n if (!providedDesignId) {\n unknownDesignIdCount += 1;\n }\n return () => {\n if (!providedProjectId) {\n unknownProjectIdCount -= 1;\n }\n if (!providedDesignId) {\n unknownDesignIdCount -= 1;\n }\n };\n};\n\nconst performDOMEventsEffect = (cadContainer: HTMLElement) => {\n const preventDefault = (e: Event) => {\n e.preventDefault();\n };\n cadContainer.addEventListener('touchmove', preventDefault, {\n passive: false,\n });\n cadContainer.addEventListener('contextmenu', preventDefault);\n return () => {\n cadContainer.removeEventListener('touchmove', preventDefault);\n cadContainer.removeEventListener('contextmenu', preventDefault);\n };\n};\n\ninterface CadDataServiceProps {\n client?: ApolloClient;\n environment: AuroraApiEnvironment;\n orgPermissions?: IOrgPermissions;\n designId?: string;\n featureGate: ICadFeatureGate;\n intl: IIntlContext;\n}\n\ninterface CadAsyncEngineInitProps {\n engine: CadEngine;\n}\n\nexport interface UseCadProps {\n isShown?: boolean;\n\n // TODO: As of now, Homeowner Leave Behind does not\n // have its own app container, so we cannot provide\n // a different feature gate / org permissions. Hence,\n // we have to rely on passing different featureGate\n // for HLB. Ideally, we would handle this with a\n // different org permissions module provider.\n featureGate: ICadFeatureGate | undefined;\n\n geodataService: ICADGeodataService | undefined;\n projectId?: string;\n designId?: string;\n userId?: string;\n designRequestId?: string;\n createDataProvider?: (props: CadDataServiceProps) => ICadDataServiceSettings;\n engineOptions: Omit<\n CadEngineOptions,\n 'dataProvider' | 'environment' | 'stateFramework' | 'eventEmitter' | 'stateMode'\n > & { stateMode: CadMode };\n asyncEngineInit?: (props: CadAsyncEngineInitProps) => void;\n}\n\nexport const useCad = ({\n isShown = true,\n geodataService,\n projectId: providedProjectId,\n designId: providedDesignId,\n userId,\n designRequestId,\n createDataProvider,\n engineOptions,\n featureGate,\n asyncEngineInit,\n}: UseCadProps) => {\n const config = useAppModule(AppConfig);\n const authToken = useAppModule(AuthToken);\n const cadLib = useAppModule(CADLib);\n const reduxStore = useAppModule(ReduxStore);\n const notifications = useAppModule(Notifications);\n const trackingModule = useAppModule(Tracking);\n const analytics = useAppModule(Analytics);\n const orgPermissions = useAppModule(OrgPermissions);\n\n const fileUploader = useUploadFiles({\n label: UserFileLabel.Screenshot,\n parentId: providedDesignId,\n parentRoleType: 'save_auto_screenshot',\n parentType: 'Design',\n });\n const featureFlags = useAppModule(FeatureFlags);\n const cadContextValue = useCadContext();\n const cadInitializerContextValue = useCadInitializerContext();\n const { evictCache, evictCacheById } = useEvictCache();\n\n // This ref is to ensure CAD is only initialized once per mount\n const effectInfo = useRef({\n effectCleanup: () => {},\n isInitialized: false,\n });\n\n // Note: we'd like `useCad` to be mostly independent of apolloClient, so do not\n // add extra dependencies on apolloClient within `useCad` other than for screenshots\n // and DXF download handling.\n const apolloClient = useAppModule(ApolloClientModule);\n\n const intl = useIntl();\n\n useEffect(() => {\n const cadContainer = engineOptions.viewData[0].domElement;\n if (\n effectInfo.current.isInitialized ||\n !isShown ||\n !cadLib ||\n !reduxStore ||\n !notifications ||\n !apolloClient ||\n !config ||\n !authToken ||\n !trackingModule ||\n !analytics ||\n !geodataService ||\n !featureGate ||\n !createDataProvider ||\n !featureFlags ||\n !cadContainer\n ) {\n return;\n }\n\n effectInfo.current.isInitialized = true;\n\n if (getBrowserWebglInfo().webgl === 'none') {\n cadInitializerContextValue.setCadError(new Error(WEBGL_ERROR));\n return;\n }\n\n const events$ = new Subject>();\n const subscription = subscribeToCadEvent(\n events$,\n CadEventTypes.Notify,\n ({ dismissType, message, messageType, title, variables }) => {\n const channel = notifications.getChannel(TOAST_CHANNEL);\n channel.push({ dismissType, message, messageType, title, variables }, Symbol(message));\n },\n );\n\n const projectId = providedProjectId ?? `unknown-project-id-${unknownProjectIdCount}`;\n const designId = providedDesignId ?? `unknown-design-id-${unknownDesignIdCount}`;\n const cleanupDOMEventsEffect = performDOMEventsEffect(cadContainer);\n\n const cleanupUnknownProjectDesignEffect = performUnknownProjectDesignEffect(\n providedProjectId,\n providedDesignId,\n );\n\n // todo add featuregate\n const dataProvider = createDataProvider({\n client: apolloClient,\n designId,\n environment: config.apiEnvironment,\n featureGate,\n intl,\n orgPermissions,\n });\n\n const eventEmitter = {\n trigger: getCadEventHandler({\n appConfig: config,\n client: apolloClient,\n designId,\n eventStream: events$,\n projectId,\n store: reduxStore,\n track: analytics.track,\n trackingModule,\n }),\n };\n\n const engine = cadLib.Factory.getEngineInstance(\n designId,\n {\n ...engineOptions,\n dataProvider,\n environment: config.apiEnvironment,\n eventEmitter,\n stateFramework: {\n cloneInert,\n effect,\n makeReactive,\n },\n useToastMessage: false,\n },\n true,\n );\n\n if (engine instanceof Error) {\n cadInitializerContextValue.setCadError(engine);\n return;\n }\n\n const locale: SUPPORTED_LOCALES = document.documentElement.lang as SUPPORTED_LOCALES;\n const asyncInitEngineInstance = cadLib.Factory.initEngineInstance(engine, {\n dataProvider,\n eventEmitter,\n geodataService,\n irradianceMapService: new cadLib.Services.IrradianceMapService(),\n locale,\n saveHandler: {\n save:\n engineOptions.stateMode !== CadMode.ReadOnly\n ? getCadSaveCallback({\n apolloClient,\n cadContext: cadContextValue,\n cadEvents$: events$,\n engine,\n evictCache,\n evictCacheById,\n fileUploader,\n reduxStore,\n })\n : () => Promise.reject(new Error('Saving is not enabled')),\n },\n store: dataProvider,\n });\n\n let isCadLoadCancelled = false;\n asyncInitEngineInstance\n .then(() => {\n if (isCadLoadCancelled) {\n return false;\n }\n\n cadInitializerContextValue.setCadContext({\n designId,\n domNode: cadContainer,\n engine,\n engineSaveFn:\n engineOptions.stateMode !== CadMode.ReadOnly\n ? () => {\n const engineScoped = cadLib?.Factory.getActiveEngineInstance(designId);\n if (!engineScoped) {\n return Promise.reject();\n }\n analytics.track(AnalyticsEventTypes.DesignClickedSave);\n return engineScoped.bridge.save();\n }\n : null,\n eventStream: events$,\n preferences: createCadPreferences({\n getDesignId: () => providedDesignId ?? null,\n getProjectId: () => providedProjectId ?? null,\n getUserId: () => userId ?? null,\n }),\n state: createCadState(engine.state as CadEngineState),\n });\n\n // TODO fix cad so this doesnt need to wait\n geodataService.initialize(engine.bridge, {\n designRequestId,\n projectId,\n });\n\n window.cadReady = true;\n if (CYPRESS_BUILD) {\n window.cadReduxStore = reduxStore;\n window.cadScreenshot$ = new Subject();\n window.cadActivity = { track() {} };\n window.cadInstance = { engine };\n // eslint-disable-next-line\n import('sinon').then((sinon) => sinon.spy(reduxStore, 'dispatch')).catch(() => {});\n }\n\n asyncEngineInit?.({ engine });\n return true;\n })\n .catch((e) => {\n cadInitializerContextValue.setCadError(e);\n return false;\n });\n\n effectInfo.current.effectCleanup = () => {\n subscription.unsubscribe();\n cleanupDOMEventsEffect();\n cleanupUnknownProjectDesignEffect();\n cleanupCad({ CadLib: cadLib, store: reduxStore });\n stopEvents(events$);\n\n if (cadContextValue.state) {\n stopCadStateEffects(cadContextValue.state);\n }\n isCadLoadCancelled = true;\n cadInitializerContextValue.clearCadContext();\n };\n }, [\n effectInfo,\n cadLib,\n reduxStore,\n notifications,\n apolloClient,\n config,\n authToken,\n fileUploader,\n trackingModule,\n analytics,\n providedProjectId,\n providedDesignId,\n designRequestId,\n createDataProvider,\n engineOptions,\n geodataService,\n featureGate,\n isShown,\n cadContextValue,\n cadInitializerContextValue,\n orgPermissions,\n asyncEngineInit,\n featureFlags,\n intl,\n userId,\n evictCache,\n evictCacheById,\n ]);\n\n useEffect(() => {\n return () => {\n // Both the initialization and cleanup should only run once\n // eslint-disable-next-line react-hooks/exhaustive-deps\n effectInfo.current.effectCleanup();\n };\n }, []);\n};\n","import { useCallback } from 'react';\n\nimport { ApolloClient, useAppModule } from '@aurorasolar/common-module-loader';\nimport { Query } from '@aurorasolar/graphql-client-schema';\n\nimport type { Reference, StoreObject } from '@apollo/client';\n\nexport const useEvictCache = () => {\n const client = useAppModule(ApolloClient);\n\n const evictCache = useCallback(\n (fieldName: K) => {\n client?.cache.evict({ fieldName });\n client?.cache.gc();\n },\n [client],\n );\n\n const evictCacheById = useCallback(\n (storeObject: StoreObject | Reference) => {\n client?.cache.evict({ id: client.cache.identify(storeObject) });\n client?.cache.gc();\n },\n [client],\n );\n\n return { evictCache, evictCacheById };\n};\n","// @ts-ignore: Ignore unused { * as Types } import\nimport * as Types from '@aurorasolar/graphql-client-schema';\n\nimport { gql } from '@apollo/client';\nimport * as Apollo from '@apollo/client';\nconst defaultOptions = {} as const;\nexport type LeadCaptureCadQueryVariables = Types.Exact<{\n id: Types.Scalars['ID'];\n}>;\n\n\nexport type LeadCaptureCadQuery = { __typename: 'Query', leadCadData: { __typename: 'LeadCaptureProject', id: string, location?: { __typename: 'LeadCaptureLocation', latitude: number, longitude: number } | null | undefined, image?: { __typename: 'LeadCaptureImage', id: string, orthoImage: { __typename: 'OrthoImage', id: string, source: Types.OrthoImageSource, url?: string | null | undefined, name: string, active: boolean, opacity?: number | null | undefined, width?: number | null | undefined, height?: number | null | undefined, worldfileA?: number | null | undefined, worldfileB?: number | null | undefined, worldfileC?: number | null | undefined, worldfileD?: number | null | undefined, worldfileE?: number | null | undefined, worldfileF?: number | null | undefined, resource?: { __typename: 'GeodataResource', id?: string | null | undefined, source: string, url?: string | null | undefined, type: Types.GeodataResourceType, worldfile?: { __typename: 'Worldfile', a?: number | null | undefined, b?: number | null | undefined, c?: number | null | undefined, e?: number | null | undefined, d?: number | null | undefined, f?: number | null | undefined } | null | undefined, dimensions?: { __typename: 'GeodataDimensions', width?: number | null | undefined, height?: number | null | undefined } | null | undefined, metadata?: { __typename: 'GeodataMeta', opacity?: number | null | undefined, name?: string | null | undefined } | null | undefined } | null | undefined } } | null | undefined, site?: { __typename: 'LeadCaptureSite', id: string, data?: { __typename: 'LeadCaptureCadSite', baseElevation: number, centerLat: number, centerLng: number, roofPlanes: Array<{ __typename: 'LeadCaptureCadRoofPlane', height: number, pitch: number, azimuthEdgeIndex: number, shell: Array<{ __typename: 'LeadCaptureCadRoofPlaneNode', x: number, y: number, edgeType: string }>, holes: Array | null | undefined> }>, obstructions: Array<{ __typename: 'LeadCaptureCadObstruction', shape: string, center: Array, azimuthVector: Array, radius?: number | null | undefined, width?: number | null | undefined, length?: number | null | undefined, flush: boolean, heightAbove?: number | null | undefined, confidence: number }> } | null | undefined } | null | undefined, scenarios: Array<{ __typename: 'LeadCaptureScenario', design?: { __typename: 'LeadCaptureDesign', id: string, data?: any | null | undefined } | null | undefined }>, components?: { __typename: 'LeadCaptureComponents', panels: Array<{ __typename: 'SolarPanel', id: string, efficiency?: number | null | undefined, height?: number | null | undefined, imp?: number | null | undefined, isc?: number | null | undefined, length?: number | null | undefined, name?: string | null | undefined, noct?: number | null | undefined, panelType?: string | null | undefined, price?: number | null | undefined, ratingPtc?: number | null | undefined, ratingStc?: number | null | undefined, tempCoeffIsc?: number | null | undefined, tempCoeffPmax?: number | null | undefined, tempCoeffVoc?: number | null | undefined, vmp?: number | null | undefined, voc?: number | null | undefined, width?: number | null | undefined, manufacturer?: { __typename: 'Manufacturer', id: string, displayName?: string | null | undefined, name?: string | null | undefined } | null | undefined, mlpe?: { __typename: 'MLPE', id: string, type?: string | null | undefined, isSolarInverter?: boolean | null | undefined, isDcOptimizer?: boolean | null | undefined, isCellStringOptimizer?: boolean | null | undefined, solarInverter?: { __typename: 'SolarInverter', id: string, efficiencyCec?: number | null | undefined, efficiencyEuropean?: number | null | undefined, efficiencyMax?: number | null | undefined, hasGlobalMppt?: boolean | null | undefined, inputVoltageMax?: number | null | undefined, inputVoltageMin?: number | null | undefined, inputVoltageSE?: number | null | undefined, isSolarEdge?: boolean | null | undefined, mpptRatedPowerVoltageMax?: number | null | undefined, mpptRatedPowerVoltageMin?: number | null | undefined, mppts?: number | null | undefined, name?: string | null | undefined, numPhases?: number | null | undefined, numPhysicalDcInputs?: number | null | undefined, outputCurrent?: number | null | undefined, outputVoltageNominal?: number | null | undefined, price?: number | null | undefined, ratedPower?: number | null | undefined, usableInputCurrentMax?: number | null | undefined, usableInputPowerMax?: number | null | undefined, manufacturer?: { __typename: 'Manufacturer', id: string, displayName?: string | null | undefined, name?: string | null | undefined } | null | undefined } | null | undefined, dcOptimizer?: { __typename: 'DcOptimizer', id: string, efficiency?: number | null | undefined, efficiencyMax?: number | null | undefined, hasGlobalMppt?: boolean | null | undefined, inputShortCircuitCurrentMax?: number | null | undefined, inputVoltageMax?: number | null | undefined, isLongString?: boolean | null | undefined, isSolarEdge?: boolean | null | undefined, mpptOperatingVoltageMax?: number | null | undefined, mpptOperatingVoltageMin?: number | null | undefined, name?: string | null | undefined, numInputs?: number | null | undefined, operatingModel?: string | null | undefined, optimizationBehavior?: string | null | undefined, outputCurrentMax?: number | null | undefined, outputVoltageMax?: number | null | undefined, price?: number | null | undefined, stcInputPowerMax?: number | null | undefined, systemVoltageMax?: number | null | undefined, usesSelectiveOptimization?: boolean | null | undefined, manufacturer?: { __typename: 'Manufacturer', id: string, displayName?: string | null | undefined, name?: string | null | undefined } | null | undefined } | null | undefined, cellStringOptimizer?: { __typename: 'CellStringOptimizer', id: string, name?: string | null | undefined, voltageLimit?: boolean | null | undefined, maxOutputVoltage?: number | null | undefined, manufacturer?: { __typename: 'Manufacturer', id: string, displayName?: string | null | undefined, name?: string | null | undefined } | null | undefined } | null | undefined } | null | undefined }>, inverters: Array<{ __typename: 'SolarInverter', id: string, efficiencyCec?: number | null | undefined, efficiencyEuropean?: number | null | undefined, efficiencyMax?: number | null | undefined, hasGlobalMppt?: boolean | null | undefined, inputVoltageMax?: number | null | undefined, inputVoltageMin?: number | null | undefined, inputVoltageSE?: number | null | undefined, isSolarEdge?: boolean | null | undefined, mpptRatedPowerVoltageMin?: number | null | undefined, mppts?: number | null | undefined, name?: string | null | undefined, numPhases?: number | null | undefined, numPhysicalDcInputs?: number | null | undefined, outputCurrent?: number | null | undefined, outputVoltageNominal?: number | null | undefined, price?: number | null | undefined, ratedPower?: number | null | undefined, usableInputCurrentMax?: number | null | undefined, usableInputPowerMax?: number | null | undefined, manufacturer?: { __typename: 'Manufacturer', id: string, displayName?: string | null | undefined, name?: string | null | undefined } | null | undefined }> } | null | undefined } };\n\n\nexport const LeadCaptureCadDocument = gql`\n query LeadCaptureCad($id: ID!) @trace_info(traceInfo: {pod: leads}) {\n leadCadData: getLeadCaptureProjectData(id: $id) {\n id\n location {\n latitude\n longitude\n }\n image {\n id\n orthoImage {\n id\n source\n url\n name\n active\n opacity\n width\n height\n worldfileA\n worldfileB\n worldfileC\n worldfileD\n worldfileE\n worldfileF\n resource {\n id\n source\n url\n type\n worldfile {\n a\n b\n c\n e\n d\n f\n }\n dimensions {\n width\n height\n }\n metadata {\n opacity\n name\n }\n }\n }\n }\n site {\n id\n data {\n roofPlanes {\n shell {\n x\n y\n edgeType\n }\n holes {\n x\n y\n edgeType\n }\n height\n pitch\n azimuthEdgeIndex\n }\n obstructions {\n shape\n center\n azimuthVector\n radius\n width\n length\n flush\n heightAbove\n confidence\n }\n baseElevation\n centerLat\n centerLng\n }\n }\n scenarios {\n design {\n id\n data\n }\n }\n components {\n panels {\n id\n efficiency\n height\n imp\n isc\n length\n name\n noct\n panelType\n price\n ratingPtc\n ratingStc\n tempCoeffIsc\n tempCoeffPmax\n tempCoeffVoc\n vmp\n voc\n width\n manufacturer {\n id\n displayName\n name\n }\n mlpe {\n id\n type\n isSolarInverter\n isDcOptimizer\n isCellStringOptimizer\n solarInverter {\n id\n efficiencyCec\n efficiencyEuropean\n efficiencyMax\n hasGlobalMppt\n inputVoltageMax\n inputVoltageMin\n inputVoltageSE\n isSolarEdge\n mpptRatedPowerVoltageMax\n mpptRatedPowerVoltageMin\n mppts\n name\n numPhases\n numPhysicalDcInputs\n outputCurrent\n outputVoltageNominal\n price\n ratedPower\n usableInputCurrentMax\n usableInputPowerMax\n manufacturer {\n id\n displayName\n name\n }\n }\n dcOptimizer {\n id\n efficiency\n efficiencyMax\n hasGlobalMppt\n inputShortCircuitCurrentMax\n inputVoltageMax\n isLongString\n isSolarEdge\n mpptOperatingVoltageMax\n mpptOperatingVoltageMin\n name\n numInputs\n operatingModel\n optimizationBehavior\n outputCurrentMax\n outputVoltageMax\n price\n stcInputPowerMax\n systemVoltageMax\n usesSelectiveOptimization\n manufacturer {\n id\n displayName\n name\n }\n }\n cellStringOptimizer {\n id\n name\n voltageLimit\n maxOutputVoltage\n manufacturer {\n id\n displayName\n name\n }\n }\n }\n }\n inverters {\n id\n efficiencyCec\n efficiencyEuropean\n efficiencyMax\n hasGlobalMppt\n inputVoltageMax\n inputVoltageMin\n inputVoltageSE\n isSolarEdge\n mpptRatedPowerVoltageMin\n mppts\n name\n numPhases\n numPhysicalDcInputs\n outputCurrent\n outputVoltageNominal\n price\n ratedPower\n usableInputCurrentMax\n usableInputPowerMax\n manufacturer {\n id\n displayName\n name\n }\n }\n }\n }\n}\n `;\n\n/**\n * __useLeadCaptureCadQuery__\n *\n * To run a query within a React component, call `useLeadCaptureCadQuery` and pass it any options that fit your needs.\n * When your component renders, `useLeadCaptureCadQuery` returns an object from Apollo Client that contains loading, error, and data properties\n * you can use to render your UI.\n *\n * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;\n *\n * @example\n * const { data, loading, error } = useLeadCaptureCadQuery({\n * variables: {\n * id: // value for 'id'\n * },\n * });\n */\nexport function useLeadCaptureCadQuery(baseOptions: Apollo.QueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useQuery(LeadCaptureCadDocument, options);\n }\nexport function useLeadCaptureCadLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) {\n const options = {...defaultOptions, ...baseOptions}\n return Apollo.useLazyQuery(LeadCaptureCadDocument, options);\n }\nexport type LeadCaptureCadQueryHookResult = ReturnType;\nexport type LeadCaptureCadLazyQueryHookResult = ReturnType;\nexport type LeadCaptureCadQueryResult = Apollo.QueryResult;","import isChromatic from 'chromatic';\nimport { useMemo } from 'react';\n\nimport { ApolloClient as ApolloClientType, NormalizedCacheObject } from '@apollo/client';\nimport { buildUnitsAdapter, peekRecord } from '@aurorasolar/common-cad-data-service';\nimport { CADTriggerActionTypes } from '@aurorasolar/common-data-store';\nimport {\n ApolloClient,\n AuroraApiEnvironment,\n CadEngine,\n CompassPosition,\n ICadDataServiceSettings,\n ICadFeatureGate,\n useAppModule,\n} from '@aurorasolar/common-module-loader';\nimport { IrradianceStates, TemperatureUnit, UnitSystem } from '@aurorasolar/graphql-client-schema';\nimport { IIntlContext, useIntl } from '@aurorasolar/intl';\n\nimport { CadMode } from '../types';\nimport { getLeadCaptureGeodataService } from './lead-capture-geodata-service';\nimport { useCad, UseCadProps } from './use-cad';\nimport { LeadCaptureCadQuery, useLeadCaptureCadQuery } from './use-lead-capture-cad.generated';\n\ninterface CreateLeadCaptureCadDataProviderProps {\n client: ApolloClientType;\n id: string;\n intl: IIntlContext;\n lat: number;\n lng: number;\n}\n\nconst createLeadCaptureCadDataProvider = ({\n client,\n id,\n intl,\n lat,\n lng,\n}: CreateLeadCaptureCadDataProviderProps) => {\n return ({\n environment,\n featureGate,\n }: {\n featureGate: ICadFeatureGate;\n environment: AuroraApiEnvironment;\n }): ICadDataServiceSettings => ({\n design: {\n latitude: lat,\n longitude: lng,\n },\n designId: id,\n distanceUnit: UnitSystem.Metric,\n environment,\n featureGate,\n getIrradiance: async () => null,\n getTemplateJsonById: async () => null,\n get irradianceState() {\n return {\n id,\n panels: {\n id: null,\n status: IrradianceStates.Invalid,\n },\n roof: {\n id: null,\n status: IrradianceStates.Invalid,\n },\n };\n },\n lidarAccessible: false,\n moduleSpacingSettings: {\n rowSpacing: 0,\n x: 0,\n y: 0,\n },\n peekRecord(type: string, compId: string) {\n return peekRecord(client, type, compId);\n },\n pricePerWatt: 0,\n projectId: '',\n projectType: '',\n recentSavedVersion: '',\n selectedImageryTypes: {\n basic: true,\n },\n timeZoneOffset: Math.round(lng / 15),\n units: buildUnitsAdapter(UnitSystem.Metric, TemperatureUnit.C, intl),\n });\n};\n\nconst getLeadCaptureFeatureGate = () => ({\n ambientOcclusion: false,\n autoDesigner: false,\n autoRoof: false,\n balanceOfSystem: false,\n compassToLowerRight: true,\n csvMonthly: false,\n datamodelLibrary: false,\n editSiteModel: false,\n fillZone: false,\n fitTreesToLidar: false,\n focusOnSelection: false,\n lidar: false,\n saveDesignJsonSchemaVersion2: false,\n walkway: false,\n});\n\nconst getLeadCaptureViewSettings = () => ({\n 'design-3d': {\n azimuthArrows: false,\n edges: false,\n ground: true,\n irradianceMap: false,\n irradianceMapPanels: false,\n lidar: false,\n mapImagery: true,\n mapView: false,\n measurements: false,\n projectCenter: false,\n setbacks: false,\n shadows: true,\n sky: true,\n streetView: false,\n sunpath: false,\n },\n});\n\ninterface GetLeadCaptureAsyncEngineInitProps {\n data: LeadCaptureCadQuery;\n hasOrbitMode: boolean;\n}\n\nconst getLeadCaptureAsyncEngineInit = ({\n data,\n hasOrbitMode,\n}: GetLeadCaptureAsyncEngineInitProps) => {\n return ({ engine }: { engine: CadEngine }): void => {\n engine.bridge.triggerAction(CADTriggerActionTypes.DrawReconstructedRoofPlanes, {\n ...data.leadCadData.site!.data,\n });\n\n engine.bridge.triggerAction(CADTriggerActionTypes.LoadSystemDesign, {\n design: data.leadCadData.scenarios[0].design!.data,\n });\n\n if (!CYPRESS_BUILD && !isChromatic() && hasOrbitMode) {\n engine.bridge.triggerAction(CADTriggerActionTypes.ZoomAndOrbit, {});\n }\n };\n};\n\ninterface UseLeadCaptureCadProps {\n cadContainer: HTMLElement | null;\n id: string;\n hasOrbitMode?: boolean;\n showCompass?: boolean;\n}\n\nexport const useLeadCaptureCad = ({\n cadContainer,\n id,\n hasOrbitMode = false,\n showCompass = false,\n}: UseLeadCaptureCadProps) => {\n const client = useAppModule(ApolloClient);\n\n const { data, loading } = useLeadCaptureCadQuery({\n variables: { id },\n });\n\n const geodataService = useMemo(\n () => (!data || loading ? undefined : getLeadCaptureGeodataService(data)),\n [loading, data],\n );\n\n const intl = useIntl();\n\n const lat = data?.leadCadData.location?.latitude || 0;\n const lng = data?.leadCadData.location?.longitude || 0;\n\n const createDataProvider = useMemo(() => {\n if (loading || !client) {\n return undefined;\n }\n\n return createLeadCaptureCadDataProvider({\n client,\n id,\n intl,\n lat,\n lng,\n });\n }, [client, id, intl, lat, lng, loading]);\n\n const asyncEngineInit = useMemo(() => {\n if (loading || !data) {\n return undefined;\n }\n\n return getLeadCaptureAsyncEngineInit({\n data,\n hasOrbitMode,\n });\n }, [data, loading, hasOrbitMode]);\n\n const propsForUseCad = useMemo(\n () => ({\n asyncEngineInit,\n createDataProvider,\n designId: id,\n engineOptions: {\n designJson: {\n site: {},\n system: {} as JSON,\n },\n designJsonSchemaVersion: 1,\n lat,\n lng,\n renderMode: 'main',\n saveFormat: '1.0',\n stateMode: CadMode.ReadOnly,\n useCompassPosition: showCompass\n ? CompassPosition.LowerRightCorner\n : CompassPosition.Invisible,\n useMapView: false,\n useSimplePointerControls: true,\n useSimpleTouchControls: false,\n useStreetView: false,\n useToastMessage: false,\n viewData: [\n {\n domElement: cadContainer as HTMLElement,\n name: 'design-3d',\n },\n ],\n viewSettings: getLeadCaptureViewSettings(),\n },\n featureGate: getLeadCaptureFeatureGate(),\n geodataService,\n isShown: !!(id && createDataProvider),\n }),\n [asyncEngineInit, createDataProvider, id, lat, lng, cadContainer, geodataService, showCompass],\n );\n\n return useCad(propsForUseCad);\n};\n","import { v4 as uuidv4 } from 'uuid';\n\nexport const generateUuid = (): string => uuidv4();\n","import { useEffect, useState } from 'react';\n\ninterface UseInterceptMouseProps {\n cadDomNode?: HTMLCanvasElement | null;\n}\n\nexport const useInterceptMouse = ({ cadDomNode }: UseInterceptMouseProps) => {\n const [clicked, setClicked] = useState(false);\n\n useEffect(() => {\n if (!cadDomNode) return undefined;\n const onMouse = () => {\n setClicked(true);\n };\n const options = { capture: true, once: true, passive: true };\n // NOTE: This may fire more than once, but the total number of events should be small\n cadDomNode.addEventListener('pointerdown', onMouse, options);\n\n return () => {\n cadDomNode.removeEventListener('pointerdown', onMouse, options);\n };\n }, [cadDomNode]);\n\n return clicked;\n};\n","import { FileUploaderResult } from '@aurorasolar/graphql-client-schema';\n\nexport enum FileResultType {\n IMAGE = 'image',\n DOCUMENT = 'document',\n VIDEO = 'video',\n UNKNOWN = 'unknown',\n}\n\nexport enum FileResultUploadStatus {\n // Upload manually canceled\n CANCELED = 'canceled',\n COMPLETE = 'complete',\n IN_PROGRESS = 'in-progress',\n // Unknown error - can retry upload\n NON_VALIDATION_ERROR = 'non-validation-error',\n // Awaiting upload kickoff\n PENDING = 'pending',\n // File will not pass validation, do not allow retry upload\n VALIDATION_ERROR = 'validation-error',\n}\n\nexport interface FileResult {\n errorText?: string;\n file: File;\n fileType: FileResultType;\n status: FileResultUploadStatus;\n id: string;\n result?: FileUploaderResult | null;\n}\n\nexport interface BSSClientResponse {\n blob_id: string;\n upload_needed: boolean;\n upload_url: string;\n mandatory_upload_headers?:\n | ({ name?: string | null; value?: string | null } | null | undefined)[]\n | null;\n}\n\nexport enum SupportedMimeTypes {\n GIF = 'image/gif',\n HEIC = 'image/heic',\n JPEG = 'image/jpeg',\n PDF = 'application/pdf',\n PNG = 'image/png',\n WEBP = 'image/webp',\n ZIP = 'application/zip',\n DXF = 'image/vnd.dxf',\n DWG = 'image/vnd.dwg',\n}\n","import { FileResultType, SupportedMimeTypes } from './types';\n\nexport const getFileResultType = (mimeType: string) => {\n switch (mimeType) {\n case SupportedMimeTypes.GIF:\n case SupportedMimeTypes.JPEG:\n case SupportedMimeTypes.PNG:\n case SupportedMimeTypes.WEBP:\n case SupportedMimeTypes.HEIC:\n case SupportedMimeTypes.DXF:\n case SupportedMimeTypes.DWG:\n return FileResultType.IMAGE;\n case SupportedMimeTypes.PDF:\n return FileResultType.DOCUMENT;\n default:\n return FileResultType.UNKNOWN;\n }\n};\n\nexport const getFileSizeFormatted = (fileSize: number): string => {\n if (fileSize <= 0) {\n return '0 KB';\n }\n const kbSize = Math.round((fileSize / 1024) * 100) / 100;\n if (kbSize < 1024) {\n return `${kbSize} KB`;\n }\n const mbSize = Math.round((kbSize / 1024) * 100) / 100;\n if (mbSize < 1024) {\n return `${mbSize} MB`;\n }\n const gbSize = Math.round((mbSize / 1024) * 100) / 100;\n return `${gbSize} GB`;\n};\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;"],"names":["LoadingAnimation","memo","Lottie","lazy","path","setPath","useState","useEffect","async","pathData","default","lazyLoadLottie","loadpath","Suspense","fallback","className","loop","play","rendererSettings","preserveAspectRatio","style","backgroundColor","height","width","LoadingText","h1Box","CadLoadingPage","alignItems","flexDirection","h","justifyContent","mb","x","h3","color","textAlign","defaultOptions","SaveDesignDocument","CadUberModeDocument","useCadUberModeQuery","baseOptions","options","useOnceRef","fn","isInitialized","useRef","value","current","useReactive","getReactive","dependencyArray","isWithinRender","result","rerender","Symbol","reactiveCallback","useCallback","lastReactiveCallbackRef","reactiveObservable","setReactiveCallback","newReactiveCallback","stopEffect","createCadContainer","document","createElement","ReactiveContextProvider","CadPageViewportsStateProvider","useReactiveState","useCadPageViewportsState","createState","ReactiveContext","createContext","children","reactiveContextRef","Provider","reactiveContext","useContext","Error","useReactiveContext","createReactiveSetup","makeReactive","data","defaultCamera","defaultLayers","viewports","cadContainersData","cadContainers","defaultCadContainer","scheduler","scheduledActions","processActions","currentActionIndex","findIndex","scheduledAction","done","currentActionType","type","length","action","splice","requestAnimationFrame","scheduleAddViewport","some","push","scheduleRemoveViewport","createCadViewportActionsScheduler","actions","addViewport","name","indexOf","removeViewport","viewportIndex","setDefaultViewSettings","camera","layers","undefined","createCadPageViewportsActions","CadStatus","CadContext","CadInitializerContext","useCadContext","context","status","useOptionalCadContext","useCadInitializerContext","initialCadContext","designId","domNode","engine","engineSaveFn","eventStream","preferences","state","CadContextProvider","cadContext","error","isLoaded","Loading","cadContextInitializer","clearCadContext","fullContext","Object","assign","setCadContext","newCadContext","Loaded","setCadError","CadMode","getLeadCaptureGeodataService","deleteOrthoImage","detectAllObstructions","detectObstructions","initialize","cadBridge","triggerAction","ProcessGroundTextures","orthoImages","leadCadData","image","orthoImage","processGroundTextures","initialized","onOrthoImageBoundsIncrease","onProjectLocationChange","onSiteBoundsChange","onSpecifiedBoundsChange","updateOrthoImage","willDestroy","PreferenceScope","ExpirationType","UserScope","createLocalStoragePreferenceProvider","storagePrefix","isCadKey","key","startsWith","removeCadKeyPrefix","substring","provider","get","has","item","localStorage","getItem","json","JSON","parse","timestamp","_","getLocalStorageStoredValue","getKeys","getOwnPropertyNames","filter","map","hasOwnProperty","remove","removeItem","set","setItem","stringify","isDateMoreThanOneDayIntoTheFuture","Date","now","isPastExpiryDate","maxDurationMs","schema","cadPreferencesManager","preferenceNames","preferenceDescriptors","preferenceIds","entries","forEach","getPreferenceIds","manager","createPreferences","currentScope","localStorageProvider","instanceProvider","storage","createInstancePreferenceProvider","providers","getProvider","descriptor","expirationType","Instance","getDescriptor","getCurrentProviderKey","preferenceId","String","userId","getUserId","projectId","getProjectId","getDesignId","prefix","userScope","PerUser","preferenceScope","Project","Design","providerKey","storedValue","isValid","MaxDuration","getIdAndDescriptor","prefIdPrefix","split","find","cleanup","maxCountKeys","expectedProvider","MaxCount","keys","maxCountKey","countDiff","maxCount","sort","t1","t2","i","wrapActions","actionPreferenceNames","newActions","actionName","property","newValue","returnedValue","createPreferencesManager","p000","panelPlaceMode","dcOptimizerId","nullable","microinverterId","solarPanelId","minSap","pitchedThreshold","flatTilt","flatRotation","flatIntermoduleSpacingX","flatRowSpacing","flatOrientation","oneOf","pitchedTilt","pitchedRotation","pitchedIntermoduleSpacingX","pitchedRowSpacing","pitchedOrientation","required","isValidSync","createCadPreferences","window","requestIdleCallback","AutoDesignerStart","AutoDesignerFinished","performance","MarkName","AutoDesignerDuration","MeasureName","ModalType","OverlayType","DesignSettingsTab","createSaveData","historyData","hasUnsavedChanges","this","recentSavedVersion","recentVersion","isSaving","createCadState","cadEngineState","selectedTypeData","selectedTypes","selectionData","reduce","types","count","createSelectedTypesData","modalData","activeModal","None","activeOverlays","modalActions","closeModal","closeOverlay","overlayType","index","overlayDatum","openModal","modalType","openOverlay","overlayData","setDesignSettingsTab","designSettingsTab","DesignSettings","tab","createModalActions","autoDesignerData","isAutoDesignerRunning","autoDesignerActions","autoDesignerFinish","mark","measure","autoDesignerStart","createAutoDesignerActions","saveData","saveActions","finishSaving","saveVersion","startSaving","createSaveActions","prismData","isPrismCadOpen","prismActions","toggleIsPrismCadOpen","newState","createPrismActions","stopEffects","GetUserInfoDocument","CreateBssUploadUrlsDocument","useCreateBssUploadUrls","fileUploader","client","fetchUserId","userData","query","fetchPolicy","newUserId","currentUser","id","createBssUploadUrls","useCreateBssUploadUrlsMutation","fetchBssUploadUrls","files","currentUserId","hashFile","bssUploadInputsPromises","file","hash","blobName","contentLength","size","contentSha256","mimeType","bssUploadInputs","Promise","all","variables","createBSSUploadUrlsInput","createBSSUploadUrls","e","SERVER_ERROR_MESSAGE","fileResultNotInProgress","fileResult","IN_PROGRESS","useUploadFiles","userFileOptions","fileMap","fileResults","setFileResults","runUploadFileAsyncJob","invalidateUploadFileAsyncJob","startAsyncJob","invalidateJobs","temporaryBlobId","fileName","label","parentId","parentType","parentRoleType","settings","FileUploader","useUploadFileAsyncJob","updateFileResult","updatedOptions","prev","newFileResults","updateIndex","cancelFileUpload","PENDING","CANCELED","console","warn","retryFileUpload","NON_VALIDATION_ERROR","VALIDATION_ERROR","errorText","removeFileUpload","clearResults","addErroredFiles","erroredFiles","newErroredFileResults","newErroredFileResult","fileType","uploadFiles","newFiles","newFile","newFileResult","pendingFileResults","pendingFiles","bssUploadUrls","uploadUrl","inProgressFileResult","blobId","uploadToSignedUrl","errors","firstError","COMPLETE","asyncUploadFiles","cancelFileResults","results","withTimeout","promise","time","timeoutMessage","timeoutPromise","resolve","setTimeout","then","race","takeSaveScreenshot","cadEvents$","reduxStore","screenshotPromise","firstValueFrom","pipe","event","eventType","CadScreenshot","payload","listenForScreenshotResponse","dispatch","actionType","TakeScreenshot","cadInstance","props","imageType","screenshotResponse","screenshotFile","File","getCadSaveCallback","saveDependencies","currentSave","apolloClient","evictCache","evictCacheById","jsonToSave","site","system","designJsonSchemaVersion","CAD","writeQuery","__typename","systemStats","systemStatsData","cadUpdatedDesign","carportSystemSizeStc","offRoofSystemSizeStc","design","irradianceMapId","irradiance","roof","mapId","irradianceMapStatus","Invalid","irradiancePanelsId","panels","irradiancePanelsStatus","roofSystemSizeStc","systemSizeAc","systemSizePtc","systemSizeStc","savePromise","mutate","awaitRefetchQueries","mutation","finally","catch","cadSaveCallbackCore","unknownProjectIdCount","unknownDesignIdCount","useCad","isShown","geodataService","providedProjectId","providedDesignId","designRequestId","createDataProvider","engineOptions","featureGate","asyncEngineInit","config","authToken","cadLib","notifications","trackingModule","analytics","orgPermissions","Screenshot","featureFlags","cadContextValue","cadInitializerContextValue","fieldName","cache","evict","gc","storeObject","identify","useEvictCache","effectInfo","effectCleanup","intl","cadContainer","viewData","domElement","webgl","events$","Subject","subscription","Notify","dismissType","message","messageType","title","getChannel","cleanupDOMEventsEffect","preventDefault","addEventListener","passive","removeEventListener","performDOMEventsEffect","cleanupUnknownProjectDesignEffect","performUnknownProjectDesignEffect","dataProvider","environment","apiEnvironment","eventEmitter","trigger","appConfig","store","track","Factory","getEngineInstance","stateFramework","cloneInert","effect","useToastMessage","locale","documentElement","lang","asyncInitEngineInstance","initEngineInstance","irradianceMapService","Services","IrradianceMapService","saveHandler","save","stateMode","ReadOnly","reject","isCadLoadCancelled","engineScoped","getActiveEngineInstance","DesignClickedSave","bridge","cadReady","unsubscribe","CadLib","cadState","items","stopEffectMapKey","stopEffectMap","stopEffectKey","stopCadStateEffects","LeadCaptureCadDocument","useLeadCaptureCad","hasOrbitMode","showCompass","loading","useLeadCaptureCadQuery","useMemo","lat","location","latitude","lng","longitude","distanceUnit","Metric","getIrradiance","getTemplateJsonById","irradianceState","lidarAccessible","moduleSpacingSettings","rowSpacing","y","peekRecord","compId","pricePerWatt","projectType","selectedImageryTypes","basic","timeZoneOffset","Math","round","units","C","createLeadCaptureCadDataProvider","DrawReconstructedRoofPlanes","LoadSystemDesign","scenarios","isChromatic","ZoomAndOrbit","getLeadCaptureAsyncEngineInit","propsForUseCad","designJson","renderMode","saveFormat","useCompassPosition","LowerRightCorner","Invisible","useMapView","useSimplePointerControls","useSimpleTouchControls","useStreetView","viewSettings","azimuthArrows","edges","ground","irradianceMap","irradianceMapPanels","lidar","mapImagery","mapView","measurements","projectCenter","setbacks","shadows","sky","streetView","sunpath","ambientOcclusion","autoDesigner","autoRoof","balanceOfSystem","compassToLowerRight","csvMonthly","datamodelLibrary","editSiteModel","fillZone","fitTreesToLidar","focusOnSelection","saveDesignJsonSchemaVersion2","walkway","generateUuid","useInterceptMouse","cadDomNode","clicked","setClicked","onMouse","capture","once","FileResultType","FileResultUploadStatus","SupportedMimeTypes","getFileResultType","GIF","JPEG","PNG","WEBP","HEIC","DXF","DWG","IMAGE","PDF","DOCUMENT","UNKNOWN","getFileSizeFormatted","fileSize","kbSize","mbSize","getRandomValues","rnds8","Uint8Array","rng","crypto","bind","msCrypto","uuid","test","byteToHex","toString","substr","arr","offset","arguments","toLowerCase","TypeError","buf","rnds","random"],"sourceRoot":""}