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,EAAI,KAAOyc,SAAS,IAAIC,OAAO,IAoBjD,QAjBA,SAAmBC,GACjB,IAAIC,EAASC,UAAUjiB,OAAS,QAAsB4F,IAAjBqc,UAAU,GAAmBA,UAAU,GAAK,EAG7EP,GAAQE,EAAUG,EAAIC,EAAS,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,SAAYroB,EAAS+oB,EAAKJ,GAExB,IAAIK,GADJhpB,EAAUA,GAAW,CAAC,GACHipB,SAAWjpB,EAAQioB,KAAOA,KAK7C,GAHAe,EAAK,GAAe,GAAVA,EAAK,GAAY,GAC3BA,EAAK,GAAe,GAAVA,EAAK,GAAY,IAEvBD,EAAK,CACPJ,EAASA,GAAU,EAEnB,IAAK,IAAI5c,EAAI,EAAGA,EAAI,KAAMA,EACxBgd,EAAIJ,EAAS5c,GAAKid,EAAKjd,GAGzB,OAAOgd,CACT,CAEA,OAAO,EAAUC,EACnB,C","sources":["webpack://aurora-new-frontend/./packages/cad-core/src/cad-wrapper/loading-animation.tsx","webpack://aurora-new-frontend/./packages/cad-core/src/cad-wrapper/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/use-cad/cad-viewports-state.tsx","webpack://aurora-new-frontend/./packages/cad-state/src/reactive-setup.tsx","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/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/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 } from '@aurorasolar/cad-state';\n\n/**\n * Note: this will be heavily refactored for multi viewport CAD support\n */\nexport type CadViewportsData = {\n activeViewportName: string | null;\n};\n\nexport type CadViewportsActions = ReturnType;\n\nconst createCadViewportsData = (): CadViewportsData => {\n return {\n activeViewportName: null,\n };\n};\n\nconst createCadViewportsActions = (cadViewportsData: CadViewportsData) => {\n return {\n setActiveViewportName: (newViewportName: string | null) => {\n cadViewportsData.activeViewportName = newViewportName;\n },\n };\n};\n\nexport const {\n ReactiveContextProvider: CadViewportsStateProvider,\n useReactiveState: useCadViewportsState,\n} = createReactiveSetup((makeReactive) => {\n const cadContainer: HTMLElement = document.createElement('div');\n const data = makeReactive(createCadViewportsData());\n const actions = makeReactive(createCadViewportsActions(data));\n return {\n actions,\n cadContainer,\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","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 { CadViewportsStateProvider } from './cad-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 { 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\n return {\n data: markDeepReadonly({\n autoDesignerData,\n ...cadEngineState.data,\n modalData,\n saveData,\n selectedTypeData,\n }),\n actions: {\n autoDesignerActions,\n ...cadEngineState.actions,\n modalActions,\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","// @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, useIntl } from '@aurorasolar/intl';\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 asyncInitEngineInstance = cadLib.Factory.initEngineInstance(engine, {\n dataProvider,\n eventEmitter,\n geodataService,\n irradianceMapService: new cadLib.Services.IrradianceMapService(),\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 { 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","ReactiveContextProvider","CadViewportsStateProvider","useReactiveState","useCadViewportsState","createState","ReactiveContext","createContext","children","reactiveContextRef","Provider","reactiveContext","useContext","Error","useReactiveContext","createReactiveSetup","makeReactive","cadContainer","document","createElement","data","activeViewportName","cadViewportsData","actions","setActiveViewportName","newViewportName","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","length","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","name","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","push","keys","maxCountKey","countDiff","maxCount","sort","t1","t2","i","wrapActions","actionPreferenceNames","newActions","actionName","property","newValue","returnedValue","undefined","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","type","count","createSelectedTypesData","modalData","activeModal","None","activeOverlays","modalActions","closeModal","closeOverlay","overlayType","index","findIndex","overlayDatum","splice","openModal","modalType","openOverlay","overlayData","setDesignSettingsTab","designSettingsTab","DesignSettings","tab","createModalActions","autoDesignerData","isAutoDesignerRunning","autoDesignerActions","autoDesignerFinish","mark","measure","autoDesignerStart","createAutoDesignerActions","saveData","saveActions","finishSaving","saveVersion","startSaving","createSaveActions","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","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","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","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":""}