{"version":3,"file":"provider.cjs","sources":["../src/provider.ts"],"sourcesContent":["/** Data provider for information that needs to be loaded in bulk for frontend views */\nimport baseFetch from \"cross-fetch\";\nimport {\n  createContext,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { StoreApi, useStore } from \"zustand\";\nimport { createStore } from \"zustand/vanilla\";\nimport {\n  ColumnGeoJSONRecord,\n  ColumnGeoJSONRecordWithID,\n  Environment,\n  MacrostratRef,\n  StratName,\n  Interval,\n} from \"@macrostrat/api-types\";\nimport {\n  type ColumnProjectScope,\n  fetchAllColumns,\n  fetchEnvironments,\n  fetchIntervals,\n  fetchLithAttributes,\n  fetchLithologies,\n  fetchTimescales,\n  fetchRefs,\n  fetchStratNames,\n  type ColumnStatusCode,\n} from \"./fetch\";\nimport { APIProvider, usePrevious } from \"@macrostrat/ui-components\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface MacrostratDataProviderProps {\n  baseURL?: string;\n  store?: StoreApi<MacrostratStore>;\n  children: React.ReactNode;\n}\n\ninterface ColumnFootprintsStorage {\n  project_id: ColumnProjectScope;\n  // Whether the \"in process\" flag was used\n  inProcess: boolean;\n  // The column footprints\n  columns: ColumnGeoJSONRecordWithID[];\n}\n\ninterface RefsSlice {\n  refs: Map<number, MacrostratRef>;\n  /** Requests in flight, so duplicates can share one response */\n  inFlightRequests: Map<string, Promise<Response>>;\n  getRefs(ids: number[]): Promise<MacrostratRef[]>;\n}\n\ninterface MacrostratStore extends RefsSlice {\n  baseURL: string;\n  fetch: any;\n  lithologies: Map<number, any> | null;\n  getLithologies(ids: number[] | null): Promise<any>;\n  intervals: Map<number, any> | null;\n  getIntervals(\n    ids: number[] | null,\n    timescaleID: number | null,\n  ): Promise<Interval[]>;\n  environments: Map<number, Environment> | null;\n  getEnvironments(ids: number[] | null): Promise<Environment[]>;\n  lithAttributes: Map<number, LithAttribute> | null;\n  getLithAttributes(ids: number[] | null): Promise<LithAttribute[]>;\n  timescales: Map<number, Timescale> | null;\n  getTimescales(ids: number[] | null): Promise<Timescale[]>;\n  /** Keyed by `columnScopeKey(projectID)`, not by a raw project id. */\n  columnFootprints: Map<string, ColumnFootprintsStorage>;\n  getColumns(\n    projectID: ColumnProjectScope,\n    inProcess: boolean,\n  ): Promise<ColumnGeoJSONRecord[]>;\n  // Strat names unify both \"strat names\" and \"concepts\"\n  stratNames: Map<number, StratName> | null;\n  getStratNames(ids: number[] | null): Promise<StratName[]>;\n}\n\n/** A lithology attribute definition, as `/defs/lithology_attributes` reports it. */\nexport interface LithAttribute {\n  lith_att_id: number;\n  name: string;\n  /** What kind of attribute: `grains`, `bedform`, `sed structure`, `color`… */\n  type?: string;\n  t_units?: number;\n}\n\n/** A timescale, as `/defs/timescales` reports it (`timescale` is its name). */\nexport interface Timescale {\n  timescale_id: number;\n  timescale: string;\n  n_intervals?: number;\n  max_age?: number;\n  min_age?: number;\n  ref_id?: number;\n}\n\nconst globalStoreMap = new Map<string, StoreApi<MacrostratStore>>();\n\nexport function createMacrostratStore(\n  baseURL: string = \"https://macrostrat.org/api/v2\",\n) {\n  /* Check if there's already a store for this baseURL */\n  if (globalStoreMap.has(baseURL)) {\n    return globalStoreMap.get(baseURL);\n  }\n\n  return createStore<MacrostratStore>((set, get): MacrostratStore => {\n    return {\n      baseURL,\n      inFlightRequests: new Map(),\n      async fetch(url: string, options?: RequestInit) {\n        /** Fetch function that shares a request already in flight */\n        let url1 = url;\n        if (!(url.startsWith(\"http://\") || url.startsWith(\"https://\"))) {\n          url1 = baseURL + url;\n        }\n\n        // A duplicate request waits on the one in flight and reads a copy of\n        // its response. Returning nothing instead — as this did — looks to the\n        // caller exactly like a request that came back empty, and callers\n        // cache that: a second ask for the same data while the first is still\n        // open would leave whatever needed it permanently blank.\n        const { inFlightRequests } = get();\n        const pending = inFlightRequests.get(url1);\n        if (pending != null) {\n          const res = await pending;\n          return res?.clone() ?? res;\n        }\n\n        // Every caller reads a clone, so the response this promise carries is\n        // never consumed and stays safe to clone again\n        const request = baseFetch(url1, options);\n        inFlightRequests.set(url1, request);\n        try {\n          const res = await request;\n          return res?.clone() ?? res;\n        } finally {\n          inFlightRequests.delete(url1);\n        }\n      },\n      ...createLithologiesSlice(set, get),\n      ...createIntervalsSlice(set, get),\n      ...createEnvironmentsSlice(set, get),\n      lithAttributes: null,\n      getLithAttributes: definitionsGetter<LithAttribute>(\n        set,\n        get,\n        \"lithAttributes\",\n        fetchLithAttributes,\n        (d) => d.lith_att_id,\n      ),\n      timescales: null,\n      getTimescales: definitionsGetter<Timescale>(\n        set,\n        get,\n        \"timescales\",\n        fetchTimescales,\n        (d) => d.timescale_id,\n      ),\n      ...createColumnsSlice(set, get),\n      ...createRefsSlice(set, get),\n      ...createStratNamesSlice(set, get),\n    };\n  });\n}\n\nfunction createRefsSlice(set: any, get: any) {\n  return {\n    refs: new Map(),\n    async getRefs(ids: number[]): Promise<MacrostratRef[]> {\n      const { refs, fetch } = get();\n      const missing = ids.filter((id) => !refs.has(id));\n      if (missing.length == 0) {\n        return ids.map((id) => refs.get(id));\n      }\n      const data = await fetchRefs(missing, { fetch });\n      if (data == null) return [];\n      for (const d of data) {\n        refs.set(d.ref_id, d);\n      }\n      set({ refs });\n      return ids.map((id) => refs.get(id));\n    },\n  };\n}\n\n/** Cache key for a project scope. A list is order-insensitive so that\n * `[3, 1]` and `[1, 3]` share one entry. */\nexport function columnScopeKey(projectID: ColumnProjectScope): string {\n  if (Array.isArray(projectID)) {\n    return [...projectID].sort((a, b) => a - b).join(\",\");\n  }\n  return String(projectID);\n}\n\n/** Re-exported so consumers get the scope type from the same module as the\n * hooks that take it. */\nexport type { ColumnProjectScope };\n\nfunction createColumnsSlice(set, get) {\n  // Column footprints separated by project scope\n  return {\n    columnFootprints: new Map(),\n    async getColumns(projectID: ColumnProjectScope, inProcess: boolean) {\n      const { columnFootprints, fetch } = get();\n      const key = columnScopeKey(projectID);\n\n      let footprints = columnFootprints.get(key);\n      if (footprints == null || footprints.inProcess != inProcess) {\n        // Fetch the columns\n        const statusCode: ColumnStatusCode[] = [\"active\"];\n        if (inProcess) {\n          statusCode.push(\"in process\");\n        }\n        const columns = await fetchAllColumns({\n          projectID,\n          statusCode,\n          fetch,\n        });\n        if (columns == null) {\n          return;\n        }\n        footprints = {\n          project_id: projectID,\n          inProcess,\n          columns,\n        };\n        // We could break multi-project result sets into separate caches here...\n        // Copy the original map\n        const columnFootprints2 = new Map(columnFootprints);\n        columnFootprints2.set(key, footprints);\n        set({ columnFootprints: columnFootprints2 });\n      }\n      return footprints.columns;\n    },\n  };\n}\n\nfunction createLithologiesSlice(set, get) {\n  return {\n    lithologies: null,\n    async getLithologies(ids: number[] | null) {\n      const { lithologies, fetch } = get();\n      let lithMap = lithologies;\n      if (lithMap == null) {\n        const data = await fetchLithologies({ fetch });\n        if (data == null) return;\n        lithMap = new Map(data.map((d) => [d.lith_id, d]));\n        set({ lithologies: lithMap });\n      }\n      // Now get the lithologies\n      if (ids == null) return lithMap.values();\n      return ids.map((id) => lithMap.get(id));\n    },\n  };\n}\n\nfunction createEnvironmentsSlice(set, get) {\n  return {\n    environments: null,\n    async getEnvironments(ids: number[] | null): Promise<Environment[]> {\n      const { environments, fetch } = get();\n      let envMap = environments;\n      if (envMap == null) {\n        const data = await fetchEnvironments({ fetch });\n        if (data == null) return [];\n        envMap = new Map(data.map((d) => [d.environ_id, d]));\n        set({ environments: envMap });\n      }\n      // Now get the environments\n      if (ids == null) return envMap.values();\n      return ids.map((id) => envMap.get(id));\n    },\n  };\n}\n\n/** The getter for a vocabulary fetched whole on first use and kept in the\n * store as a map by id, under `key`. */\nfunction definitionsGetter<T>(\n  set,\n  get,\n  key: string,\n  fetcher: (opts: { fetch: any }) => Promise<T[] | null>,\n  idOf: (d: T) => number,\n) {\n  return async (ids: number[] | null): Promise<T[]> => {\n    const { fetch } = get();\n    let defs: Map<number, T> | null = get()[key];\n    if (defs == null) {\n      const data = await fetcher({ fetch });\n      if (data == null) return [];\n      defs = new Map(data.map((d) => [idOf(d), d]));\n      set({ [key]: defs });\n    }\n    if (ids == null) return Array.from(defs.values());\n    return ids.map((id) => defs.get(id)) as T[];\n  };\n}\n\nfunction createIntervalsSlice(set, get) {\n  // One request per scope (\"all\", or a timescale id) while it is in flight,\n  // so that the pickers mounting together — one per interval cell — share a\n  // fetch and write the store once, rather than once each.\n  const pending = new Map<string, Promise<boolean>>();\n\n  /** Fetch a scope's intervals and merge them into the store. Resolves to\n   * whether the fetch succeeded. */\n  function loadIntervals(timescaleID: number | null): Promise<boolean> {\n    const key = String(timescaleID ?? \"all\");\n    const inFlight = pending.get(key);\n    if (inFlight != null) return inFlight;\n    const request = (async () => {\n      let data: any[] | null;\n      try {\n        data = await fetchIntervals(timescaleID, { fetch: get().fetch });\n      } finally {\n        pending.delete(key);\n      }\n      if (data == null) return false;\n      // Merge into whatever is in the store *now*, not into the snapshot\n      // taken before the fetch. Several timescales are often requested at\n      // once, and each request would otherwise start from the map as it was\n      // before any of them resolved — so the last one to land drops the\n      // others' intervals, and the timescales they recorded as fetched.\n      set((state) => {\n        const merged = new Map(state.intervals ?? []);\n        for (const d of data) {\n          merged.set(d.int_id, mergeInterval(merged.get(d.int_id), d));\n        }\n        let fetchedTimescales = state.fetchedTimescales;\n        if (timescaleID != null) {\n          fetchedTimescales = new Set(state.fetchedTimescales);\n          fetchedTimescales.add(timescaleID);\n        }\n        // A request without a timescale is for every interval, so once it\n        // lands nothing more needs fetching. Without recording that, every\n        // call fetched them all again and replaced the store's map,\n        // re-rendering everything that reads it.\n        return {\n          intervals: merged,\n          fetchedAll: timescaleID == null || state.fetchedAll,\n          fetchedTimescales,\n        };\n      });\n      return true;\n    })();\n    pending.set(key, request);\n    return request;\n  }\n\n  return {\n    intervals: null,\n    fetchedTimescales: new Set(),\n    fetchedAll: false,\n    async getIntervals(ids: number[] | null, timescaleID: number | null) {\n      /** We can either fetch by timescale (if requesting a specific timescale)\n       * or request all\n       * */\n      const { intervals, fetchedTimescales, fetchedAll } = get();\n      let _intervals = intervals ?? new Map();\n\n      let mustFetch = !fetchedAll;\n      if (timescaleID != null) {\n        mustFetch = !(fetchedAll || fetchedTimescales.has(timescaleID));\n      }\n      if (ids != null) {\n        // If any ids are not found, we fetch all\n        mustFetch = !(fetchedAll || ids.every((d) => _intervals.has(d)));\n      }\n\n      if (mustFetch) {\n        const loaded = await loadIntervals(timescaleID);\n        if (!loaded) return [];\n        _intervals = get().intervals;\n      }\n\n      // Now, get the intervals\n      if (ids != null) {\n        return ids.map((id) => _intervals.get(id));\n      } else if (timescaleID != null) {\n        return Array.from(_intervals.values() as any[]).filter((d) =>\n          intervalIsInTimescale(d, timescaleID),\n        );\n      } else {\n        return Array.from(_intervals?.values() ?? []);\n      }\n    },\n  };\n}\n\n/** Combine two records of the same interval.\n *\n * A request for one timescale reports only *that* timescale in each\n * interval's `timescales`, so records from different requests each know a\n * different part of the answer. Overwriting loses the rest: fetching the\n * Russian stages would quietly take the ICS ages that are also Russian stages\n * out of the international timescale, and the timescale drawn from it would\n * lose whole levels.\n */\nfunction mergeInterval(existing: any, incoming: any) {\n  if (existing == null) return incoming;\n  const timescales = [...(existing.timescales ?? [])];\n  for (const timescale of incoming.timescales ?? []) {\n    const known = timescales.some(\n      (d) => d.timescale_id === timescale.timescale_id,\n    );\n    if (!known) timescales.push(timescale);\n  }\n  return { ...existing, ...incoming, timescales };\n}\n\nfunction intervalIsInTimescale(interval: Interval, timescaleID: number) {\n  return (\n    interval.timescales?.some((t) => t.timescale_id === timescaleID) ?? false\n  );\n}\n\nfunction createStratNamesSlice(set, get) {\n  return {\n    stratNames: null,\n    async getStratNames(ids: number[] | null): Promise<StratName[]> {\n      const { stratNames, fetch } = get();\n      if (ids == null) {\n        return stratNames?.values() ?? [];\n      }\n      let nameMap = stratNames ?? new Map();\n      let stratNamesAlreadyLoaded: StratName[] = [];\n      let stratNamesToLoad: number[] = [];\n      for (const id of ids) {\n        const nameForID = nameMap.get(id);\n        if (nameForID != null) {\n          stratNamesAlreadyLoaded.push(nameForID);\n        } else {\n          stratNamesToLoad.push(id);\n        }\n      }\n      if (stratNamesToLoad.length > 0) {\n        const data = await fetchStratNames(stratNamesToLoad, { fetch });\n        if (data == null) return stratNamesAlreadyLoaded;\n        for (const d of data) {\n          nameMap.set(d.strat_name_id, d);\n        }\n        set({ stratNames: nameMap });\n      }\n      return ids.map((id) => nameMap.get(id));\n    },\n  };\n}\n\nexport function useStratNames(ids: number[] | null) {\n  const stratNames = useMemo(() => ids, ids ?? []);\n  return useMacrostratData(\"strat_names\", stratNames);\n}\n\ntype MacrostratSelector = (store: MacrostratStore) => any;\n\nexport function useMacrostratStore(selector: MacrostratSelector | \"api\") {\n  const ctx = useContext(MacrostratDataProviderContext);\n  if (ctx == null) {\n    throw new Error(\"Missing MacrostratDataProvider\");\n  }\n  if (selector === \"api\") {\n    return ctx;\n  }\n  return useStore(ctx, selector);\n}\n\nexport function useMacrostratBaseURL(\n  defaultURL = \"https://macrostrat.org/api/v2\",\n): string {\n  /** Get the Macrostrat base URL from the store if set, otherwise return a default value */\n  const ctx = useContext(MacrostratDataProviderContext);\n  if (ctx == null) {\n    // Return default URL if no provider is present\n    return defaultURL;\n  }\n  return ctx.getState().baseURL;\n}\n\nexport function useMacrostratFetch() {\n  const ctx = useContext(MacrostratDataProviderContext);\n  if (ctx == null) {\n    throw new Error(\"Missing MacrostratDataProvider\");\n  }\n  return ctx.getState().fetch;\n}\n\ntype DataTypeKey =\n  | \"lithologies\"\n  | \"intervals\"\n  | \"columns\"\n  | \"environments\"\n  | \"lithAttributes\"\n  | \"timescales\"\n  | \"refs\"\n  | \"strat_names\";\n\nconst dataTypeMapping = {\n  lithologies: (store) => store.getLithologies,\n  lithAttributes: (store) => store.getLithAttributes,\n  timescales: (store) => store.getTimescales,\n  intervals: (store) => store.getIntervals,\n  columns: (store) => store.getColumns,\n  environments: (store) => store.getEnvironments,\n  refs: (store) => store.getRefs,\n  strat_names: (store) => store.getStratNames,\n};\n\nexport function useMacrostratDefs(\n  dataType: string,\n  ...args: any[]\n): Map<number, any> | null {\n  if (dataType == \"columns\") {\n    throw new Error(\"Columns are not provided as a map\");\n  }\n  const result = useMacrostratStore((state) => state[dataType]);\n  const operator = useMacrostratStore(dataTypeMapping[dataType]);\n  useEffect(() => {\n    if (result != null) return;\n    operator(...args);\n  }, [result, operator, ...args]);\n  return result;\n}\n\nexport function useMacrostratColumns(\n  projectID: ColumnProjectScope,\n  inProcess: boolean,\n) {\n  const getColumns = useMacrostratStore((s) => s.getColumns);\n  const columnsMap = useMacrostratStore((s) => s.columnFootprints);\n  const key = columnScopeKey(projectID);\n  const colData = columnsMap?.get(key);\n  useEffect(() => {\n    // Refetch if the columns are not available, or if we have requested inProcess columns where we didn't before\n    if (colData == null || (inProcess && !colData.inProcess)) {\n      getColumns(projectID, inProcess);\n    }\n    // If we've already fetched the columns there's nothing to do...\n  }, [colData, inProcess, getColumns, key]);\n\n  return useMemo(() => {\n    if (colData == null) return null;\n    const columns = colData.columns;\n    if (inProcess || !colData.inProcess) return columns;\n    // The cached set includes 'in process' columns but this caller doesn't want\n    // them. `columns` is an array of features, so filter it and return a new\n    // array — the previous version assigned to `columns.features`, which is\n    // undefined on an array, so it both did nothing and mutated the cache.\n    return columns.filter((d) => d.properties.status !== \"in process\");\n  }, [colData, inProcess]);\n}\n\nexport function useMacrostratColumnInfo(\n  columnID: number,\n): ColumnGeoJSONRecord[\"properties\"] | null {\n  /** Get basic info for a column, without automatically fetching it (assumes the overall set of relevant columns has already been fetched) */\n  const columnsMap = useMacrostratStore((s) => s.columnFootprints);\n  return useMemo(() => {\n    for (const colData of columnsMap.values()) {\n      const col = colData.columns.find((d) => d.properties.col_id === columnID);\n      if (col != null) return col.properties;\n    }\n    return null;\n  }, [columnsMap, columnID]);\n}\n\nexport function useMacrostratData(dataType: DataTypeKey, ...args: any[]): any {\n  const selector = dataTypeMapping[dataType];\n  const operator = useMacrostratStore(selector);\n\n  const [value, setValue] = useState(null);\n\n  useEffect(() => {\n    try {\n      operator(...args).then(setValue);\n    } catch (e) {\n      console.error(e);\n    }\n  }, [operator, ...args]);\n\n  return value;\n}\n\n/** By default, we provide a store linked to the production API */\nconst MacrostratDataProviderContext = createContext(createMacrostratStore());\n\nexport function MacrostratDataProvider(props: MacrostratDataProviderProps) {\n  const {\n    baseURL = \"https://macrostrat.org/api/v2\",\n    store: _initStore,\n    children,\n  } = props;\n\n  const store = useRef(_initStore ?? createMacrostratStore(baseURL));\n\n  return h(MacrostratDataProviderContext.Provider, { value: store.current }, [\n    h(_StoreAPIProvider, { children }),\n  ]);\n}\n\nfunction _StoreAPIProvider({ children }) {\n  const baseURL = useMacrostratStore((s) => s.baseURL);\n  return h(MacrostratAPIProvider, { baseURL }, [children]);\n}\n\n/** Legacy API provider so useAPIResult can work */\n\ntype APIProviderProps = {\n  children: ReactNode;\n  useDev?: boolean;\n  baseURL?: string;\n};\n\nexport function MacrostratAPIProvider({\n  children,\n  useDev = false,\n  baseURL,\n}: APIProviderProps) {\n  baseURL ??= useDev\n    ? \"https://dev.macrostrat.org/api/v2\"\n    : \"https://macrostrat.org/api/v2\";\n\n  return h(\n    APIProvider,\n    {\n      baseURL,\n      unwrapResponse: (res) => res.success.data,\n    },\n    children,\n  );\n}\n\nexport function useLithologies() {\n  const getLithologies = useMacrostratStore((s) => s.getLithologies);\n  const lithologies = useMacrostratStore((s) => s.lithologies);\n  useEffect(() => {\n    if (lithologies == null) getLithologies();\n  }, [lithologies, getLithologies]);\n  return lithologies;\n}\n\nexport function useEnvironments() {\n  const getEnvironments = useMacrostratStore((s) => s.getEnvironments);\n  const environments = useMacrostratStore((s) => s.environments);\n  useEffect(() => {\n    if (environments == null) getEnvironments();\n  }, [environments, getEnvironments]);\n  return environments;\n}\n\nexport function useIntervals() {\n  const getIntervals = useMacrostratStore((s) => s.getIntervals);\n  const intervals = useMacrostratStore((s) => s.intervals);\n  useEffect(() => {\n    if (intervals == null) getIntervals();\n  }, [getIntervals]);\n  return intervals;\n}\n\nexport function useLithAttributes() {\n  const getLithAttributes = useMacrostratStore((s) => s.getLithAttributes);\n  const lithAttributes = useMacrostratStore((s) => s.lithAttributes);\n  useEffect(() => {\n    if (lithAttributes == null) getLithAttributes(null);\n  }, [lithAttributes, getLithAttributes]);\n  return lithAttributes;\n}\n\nexport function useTimescales() {\n  const getTimescales = useMacrostratStore((s) => s.getTimescales);\n  const timescales = useMacrostratStore((s) => s.timescales);\n  useEffect(() => {\n    if (timescales == null) getTimescales(null);\n  }, [timescales, getTimescales]);\n  return timescales;\n}\n"],"names":["createStore","baseFetch","fetchLithAttributes","fetchTimescales","fetch","fetchRefs","fetchAllColumns","fetchLithologies","fetchEnvironments","fetchIntervals","fetchStratNames","useMemo","useContext","useStore","useEffect","useState","createContext","useRef","h","APIProvider"],"mappings":";;;;;;;;;;;;AAwGA,MAAM,qCAAqB,IAAA;AAEpB,SAAS,sBACd,UAAkB,iCAClB;AAEA,MAAI,eAAe,IAAI,OAAO,GAAG;AAC/B,WAAO,eAAe,IAAI,OAAO;AAAA,EACnC;AAEA,SAAOA,QAAAA,YAA6B,CAAC,KAAK,QAAyB;AACjE,WAAO;AAAA,MACL;AAAA,MACA,sCAAsB,IAAA;AAAA,MACtB,MAAM,MAAM,KAAa,SAAuB;AAE9C,YAAI,OAAO;AACX,YAAI,EAAE,IAAI,WAAW,SAAS,KAAK,IAAI,WAAW,UAAU,IAAI;AAC9D,iBAAO,UAAU;AAAA,QACnB;AAOA,cAAM,EAAE,iBAAA,IAAqB,IAAA;AAC7B,cAAM,UAAU,iBAAiB,IAAI,IAAI;AACzC,YAAI,WAAW,MAAM;AACnB,gBAAM,MAAM,MAAM;AAClB,iBAAO,KAAK,WAAW;AAAA,QACzB;AAIA,cAAM,UAAUC,oBAAAA,QAAU,MAAM,OAAO;AACvC,yBAAiB,IAAI,MAAM,OAAO;AAClC,YAAI;AACF,gBAAM,MAAM,MAAM;AAClB,iBAAO,KAAK,WAAW;AAAA,QACzB,UA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