{"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../src/plugins/OpenUI/runtime.tsx"],"sourcesContent":["// The part of the OpenUI renderer that runs the official OpenUI packages. It loads when a reply\n// first shows OpenUI: the component library is large, and of no use to an app whose agent never\n// writes OpenUI.\nimport React, {\n  createContext,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react';\nimport {\n  type ActionEvent,\n  BuiltinActionType,\n  type ComponentRenderer,\n  defineComponent,\n  type ElementNode,\n  type OpenUIError as LangError,\n  type Library,\n  type ParseResult,\n  type PromptOptions,\n  Renderer,\n  type ToolSpec,\n} from '@openuidev/react-lang';\nimport {\n  openuiChatLibrary,\n  openuiChatPromptOptions,\n} from '@openuidev/react-ui/genui-lib';\nimport { z } from 'zod/v4';\n\nimport {\n  type AIUIComponent,\n  AIUIComponentView,\n} from '../AIComponents/GenerativeUI/AIUIComponent';\nimport type { AIUIComponentDefinition } from '../AIComponents/GenerativeUI/AIUIComponentDefinition';\nimport {\n  type AIUIDocument,\n  aiUIDocumentText,\n} from '../AIComponents/GenerativeUI/AIUIDocument';\nimport {\n  aiUILinkOpener,\n  aiUISentence,\n  aiUITypeName,\n  aiUIWords,\n  isRecord,\n  withoutSecretValues,\n} from '../AIComponents/GenerativeUI/AIUIHelpers';\nimport {\n  aiUIMediaSource,\n  type AIUIMediaURL,\n} from '../AIComponents/GenerativeUI/AIUIMedia';\nimport type { AIUIClientToolDefinition } from '../AIComponents/GenerativeUI/AIUITools';\nimport type { OpenUIEngine, OpenUIError } from './OpenUIRenderer';\n\n/** A library of OpenUI components, as `createLibrary` of `@openuidev/react-lang` makes one. */\nexport type OpenUILibrary = Library;\n\n/** The OpenUI type of one of the app's components, named as the library names its own. */\nexport const openUITypeName = aiUITypeName;\n\n/**\n * What an app's component is for, as the agent reads it: what it shows, what each parameter\n * holds, since OpenUI passes them by position and its signatures name only their types, and\n * what its events do, since it reports them itself. As StreamChatOpenUI describes it.\n */\nexport const openUIDescriptionOf = ({\n  description,\n  events,\n  parameters,\n}: AIUIComponentDefinition) =>\n  [\n    description,\n    ...parameters.flatMap(({ description: about, name }) =>\n      about ? [`${name}: ${about}`] : [],\n    ),\n    ...events.map((event) => event.description),\n  ]\n    .filter((note) => note.trim() !== '')\n    .map(aiUISentence)\n    .join(' ');\n\n/** An app's component's parameters as the props of an OpenUI component, in their order. */\nexport const openUIPropsOf = ({ parameters }: AIUIComponentDefinition) =>\n  z.object(\n    Object.fromEntries(\n      parameters.map(({ isRequired, name, type }) => {\n        const schema = z.fromJSONSchema(type as never);\n        return [name, isRequired ? schema : schema.optional()];\n      }),\n    ),\n  );\n\n// The props of the library's components that hold its content, such as a Card's children or a\n// TabItem's content, which the app's components join: the ones that already take TextContent.\nconst contentSlotsOf = (library: Library) => {\n  const { $defs } = library.toJSONSchema() as {\n    $defs?: Record<string, { properties?: Record<string, unknown> }>;\n  };\n  return Object.entries($defs ?? {}).flatMap(([name, schema]) =>\n    Object.entries(schema.properties ?? {})\n      .filter(([, prop]) => JSON.stringify(prop).includes('\"#/$defs/TextContent\"'))\n      .map(([prop]) => `${name}.${prop}`),\n  );\n};\n\ntype ReplyContextValue = {\n  engine: OpenUIEngine;\n  isStreaming: boolean;\n  messageId: string;\n};\n\nconst OpenUIReplyContext = createContext<ReplyContextValue | undefined>(undefined);\n\n// One of the app's components where the agent placed it in a reply's program.\nconst PlacedComponent = ({\n  component,\n  props,\n}: {\n  component: AIUIComponent;\n  props: Record<string, unknown>;\n}) => {\n  const reply = useContext(OpenUIReplyContext);\n  if (!reply) return null;\n  const { engine, isStreaming, messageId } = reply;\n  const { name } = component.definition;\n  // A prop the agent left out is no argument, rather than one of no value.\n  const args = Object.fromEntries(\n    Object.entries(props).filter(([, value]) => value !== undefined && value !== null),\n  );\n  return (\n    <AIUIComponentView\n      args={args}\n      component={component}\n      context={{\n        emit: (event, label, payload = {}) =>\n          void engine.host.send({\n            format: 'openui',\n            label,\n            messageId,\n            name: event,\n            payload: { ...payload, component: name },\n          }),\n        host: engine.host,\n        isStreaming,\n        messageId,\n      }}\n    />\n  );\n};\n\n// The app's components as OpenUI components, each where the library's own content goes. One\n// whose parameters OpenUI can't take, or whose name the library already has, is left out, so it\n// never replaces one of the library's own.\nconst withAppComponents = (\n  library: Library,\n  components: AIUIComponent[],\n  report?: (error: OpenUIError) => void,\n): Library => {\n  const taken = new Set(Object.keys(library.components));\n  const slots = contentSlotsOf(library);\n  const added = components.flatMap((component) => {\n    const name = openUITypeName(component.definition.name);\n    if (taken.has(name)) {\n      report?.({\n        code: 'component-name-taken',\n        component: name,\n        message: `The component ${component.definition.name} is left out of OpenUI: its name ${name} is taken`,\n      });\n      return [];\n    }\n    try {\n      const defined = defineComponent({\n        component: ({ props }) => (\n          <PlacedComponent\n            component={component}\n            props={props as Record<string, unknown>}\n          />\n        ),\n        description: openUIDescriptionOf(component.definition),\n        name,\n        props: openUIPropsOf(component.definition),\n      });\n      taken.add(name);\n      return [{ component: defined, slots }];\n    } catch (error) {\n      report?.({\n        code: 'component-error',\n        component: name,\n        message: `The component ${component.definition.name} can't join OpenUI: ${String(error)}`,\n      });\n      return [];\n    }\n  });\n  if (added.length === 0 || !library.extend) return library;\n  return library.extend({ components: { add: added } });\n};\n\n// Each `src` the agent wrote in a component's props, as `mediaURL` allows it, or left out.\nconst withMediaSources = (value: unknown, mediaURL: AIUIMediaURL): unknown => {\n  if (Array.isArray(value)) return value.map((item) => withMediaSources(item, mediaURL));\n  if (!isRecord(value) || value.type === 'element') return value;\n  return Object.fromEntries(\n    Object.entries(value).map(([key, item]) => [\n      key,\n      key === 'src'\n        ? (aiUIMediaSource(item, mediaURL) ?? '')\n        : withMediaSources(item, mediaURL),\n    ]),\n  );\n};\n\n// The library's components that draw media the agent links to, each loading only what\n// `mediaURL` allows, as it is drawn rather than once it is on the page.\nconst withMediaURL = (library: Library, mediaURL: AIUIMediaURL): Library => {\n  if (!library.extend) return library;\n  const { $defs } = library.toJSONSchema() as { $defs?: Record<string, unknown> };\n  const override = Object.values(library.components)\n    .filter((component) =>\n      JSON.stringify($defs?.[component.name] ?? {}).includes('\"src\"'),\n    )\n    .map((component) => {\n      const Draw = component.component as ComponentRenderer;\n      return defineComponent({\n        component: (({ props, ...rest }) => (\n          <Draw {...rest} props={withMediaSources(props, mediaURL) as typeof props} />\n        )) as ComponentRenderer,\n        description: component.description,\n        name: component.name,\n        props: component.props,\n      });\n    });\n  return override.length ? library.extend({ components: { override } }) : library;\n};\n\nconst librariesByEngine = new WeakMap<OpenUIEngine, Library>();\n\n/** The library a conversation's replies are written with: the renderer's, with the app's components. */\nexport const libraryOf = (engine: OpenUIEngine) => {\n  let library = librariesByEngine.get(engine);\n  if (!library) {\n    library = withMediaURL(\n      withAppComponents(\n        engine.options.library ?? openuiChatLibrary,\n        engine.host.components,\n        (error) => engine.report(error),\n      ),\n      engine.mediaURL,\n    );\n    librariesByEngine.set(engine, library);\n  }\n  return library;\n};\n\n// One of the app's tools as the model's instructions list it, saying whether a Query can run it.\nconst toolSpecOf = ({\n  description,\n  inputSchema,\n  name,\n  readOnly,\n}: AIUIClientToolDefinition): ToolSpec => ({\n  annotations: { readOnlyHint: readOnly === true },\n  description: [\n    description,\n    readOnly\n      ? 'Read-only: use it in Query() or Mutation().'\n      : 'It changes something: use it only in Mutation(), which runs when the person taps.',\n  ]\n    .filter((part) => part && part.trim() !== '')\n    .join(' '),\n  inputSchema: inputSchema ?? { type: 'object' },\n  name,\n  outputSchema: {},\n});\n\n/**\n * The instructions that teach a model to write OpenUI with `library` and `components`, call\n * the app's `tools`, and heed the app's own `instructions`, which come first.\n */\nexport const instructionsFor = (\n  components: AIUIComponent[],\n  {\n    instructions,\n    library,\n    tools = [],\n  }: {\n    instructions?: string;\n    library?: Library;\n    tools?: AIUIClientToolDefinition[];\n  } = {},\n) => {\n  const base: PromptOptions = library ? {} : openuiChatPromptOptions;\n  const options: PromptOptions = {\n    ...base,\n    ...(instructions?.trim()\n      ? { preamble: [instructions.trim(), base.preamble].filter(Boolean).join('\\n\\n') }\n      : {}),\n    ...(tools.length ? { tools: [...(base.tools ?? []), ...tools.map(toolSpecOf)] } : {}),\n  };\n  return withAppComponents(library ?? openuiChatLibrary, components).prompt(options);\n};\n\n/** The fields of a reply's program the person types secrets in, such as a password. */\nexport type OpenUISecrets = {\n  /** The names of its password inputs. */\n  fields: Set<string>;\n  /** The `$variables` they are bound to. */\n  variables: Set<string>;\n};\n\n/** The password inputs of a program as OpenUI read it, and what they are bound to. */\nexport const secretsOf = (parsed: ParseResult | null): OpenUISecrets => {\n  const secrets: OpenUISecrets = { fields: new Set(), variables: new Set() };\n  const visit = (value: unknown) => {\n    if (Array.isArray(value)) return value.forEach(visit);\n    if (!isRecord(value)) return;\n    if (value.type === 'element') {\n      const { props, typeName } = value as unknown as ElementNode;\n      if (typeName === 'Input' && props.type === 'password') {\n        if (typeof props.name === 'string') secrets.fields.add(props.name);\n        const bound = props.value;\n        if (isRecord(bound) && bound.k === 'StateRef' && typeof bound.n === 'string') {\n          secrets.variables.add(bound.n.replace(/^\\$/, ''));\n        }\n      }\n      Object.values(props).forEach(visit);\n    }\n  };\n  visit(parsed?.root);\n  return secrets;\n};\n\nconst isSecretKey = (key: string, secrets: OpenUISecrets) =>\n  secrets.fields.has(key) || secrets.variables.has(key.replace(/^\\$/, ''));\n\n// What the person typed in the program's secret fields, wherever the state holds it.\nconst secretValuesIn = (state: Record<string, unknown>, secrets: OpenUISecrets) => {\n  const values: string[] = [];\n  const take = (item: unknown) => {\n    const value = isRecord(item) && 'value' in item ? item.value : item;\n    if (typeof value === 'string' && value !== '') values.push(value);\n  };\n  for (const [key, item] of Object.entries(state)) {\n    if (isSecretKey(key, secrets)) take(item);\n    else if (isRecord(item)) {\n      for (const [field, entry] of Object.entries(item)) {\n        if (isSecretKey(field, secrets)) take(entry);\n      }\n    }\n  }\n  return values;\n};\n\n/**\n * A program's state or a form's values without what the person typed in its secret fields,\n * such as a password, which neither reaches the agent nor is kept: the fields are left out, and\n * their values are taken out of anything else that holds them.\n */\nexport const withoutSecrets = (\n  state: Record<string, unknown>,\n  secrets: OpenUISecrets,\n): Record<string, unknown> => {\n  const values = secretValuesIn(state, secrets);\n  const kept = Object.fromEntries(\n    Object.entries(state).flatMap(([key, item]) => {\n      if (isSecretKey(key, secrets)) return [];\n      if (!isRecord(item) || 'value' in item) return [[key, item]];\n      return [\n        [\n          key,\n          Object.fromEntries(\n            Object.entries(item).filter(([field]) => !isSecretKey(field, secrets)),\n          ),\n        ],\n      ];\n    }),\n  );\n  return withoutSecretValues(kept, values);\n};\n\n// The words on the control the person last pressed in a reply's UI, which their message says.\ntype Pressed = { at: number; words: string };\n\nconst PRESSABLE = 'button:not([role=\"tab\"]):not([role=\"option\"]), [role=\"button\"]';\n\n/** Whether a click on the reply's UI was on a control, such as a button, with words or without. */\nconst isControl = (target: EventTarget | null) =>\n  !!(target as Element | null)?.closest?.(PRESSABLE);\n\n/** What the person pressed, from a click on the reply's UI, or nothing for what isn't a control. */\nexport const pressedOf = (target: EventTarget | null): Pressed | undefined => {\n  const control = (target as Element | null)?.closest?.(PRESSABLE);\n  const words = control?.textContent?.replace(/\\s+/g, ' ').trim();\n  return words ? { at: Date.now(), words } : undefined;\n};\n\n// How long after a press an action still takes its words: one that waits for a Mutation first\n// can take a while.\nconst PRESS_LASTS_MS = 30_000;\n\n/**\n * What the person did, as the action that tells the agent, in StreamChatOpenUI's shape: a\n * button or follow-up continues the conversation with the words of the control they pressed as\n * the label, as they saw them, and carries the step's message for the agent, its `context`, any\n * other params, and the values of the form it belongs to, never what they typed in a secret\n * field. A link opens the way the host allows instead, and an action the library defines but\n * OpenUI doesn't is left out and reported, as the agent has nothing to do with it.\n */\nexport const actOn = (\n  engine: OpenUIEngine,\n  messageId: string,\n  event: ActionEvent,\n  {\n    pressed,\n    secrets,\n    state,\n  }: {\n    pressed?: Pressed;\n    secrets?: OpenUISecrets;\n    /**\n     * The program's whole state, as OpenUI last gave it. A form's own values leave out the\n     * `$variables` its fields are bound to, such as a password's, which can still be in the\n     * action's context or message.\n     */\n    state?: Record<string, unknown>;\n  } = {},\n) => {\n  if (event.type === BuiltinActionType.OpenUrl) {\n    const { url } = event.params;\n    if (typeof url === 'string') engine.host.open(url);\n    return;\n  }\n  if (event.type !== BuiltinActionType.ContinueConversation) {\n    engine.report(\n      {\n        code: 'unknown-action',\n        message: `The action ${event.type} isn't one the agent can take, so it isn't sent`,\n      },\n      messageId,\n    );\n    return;\n  }\n  const hidden = secrets ?? { fields: new Set<string>(), variables: new Set<string>() };\n  const typed = secretValuesIn({ ...state, ...event.formState }, hidden);\n  const { context, ...params } = withoutSecretValues(event.params, typed);\n  const values =\n    event.formName && event.formState ? withoutSecrets(event.formState, hidden) : {};\n  // The agent's own words for what the person did, which may not be what they saw.\n  const message = withoutSecretValues(event.humanFriendlyMessage ?? '', typed).trim();\n  const label =\n    pressed && Date.now() - pressed.at < PRESS_LASTS_MS\n      ? pressed.words\n      : aiUIWords(event.formName || event.type);\n  void engine.host.send({\n    format: 'openui',\n    label,\n    messageId,\n    name: event.type,\n    payload: {\n      ...(context === undefined ? {} : { context }),\n      ...(message && message !== label ? { message } : {}),\n      ...(Object.keys(params).length ? { params } : {}),\n      ...(event.formName ? { form: event.formName } : {}),\n      ...(Object.keys(values).length ? { values } : {}),\n    },\n  });\n};\n\n// How often a Query may ask one of the app's tools for the same thing: an agent's program can\n// ask for a refresh every fraction of a second.\nconst QUERY_REFRESH_MS = 5_000;\n\ntype Asked = { at: number; output: Promise<unknown> };\n\n/**\n * How long after the person presses a control in a reply's UI the tools it runs count as theirs:\n * as long as a browser's activation lasts, so a Mutation the press runs after another still can.\n */\nexport const TOOL_PRESS_MS = 5_000;\n\n/**\n * The host's tools as a program's Query() and Mutation() run them: one that changes something\n * runs only while `isActing`, just after the person pressed a control in this reply's UI, and\n * the same question asked again within a few seconds, as a Query refreshing on its own does,\n * gets the answer it got. A press elsewhere on the page, such as sending a message, doesn't\n * count, as the browser's own activation would.\n */\nexport const hostToolProvider = (\n  engine: OpenUIEngine,\n  isActing: () => boolean = () => false,\n) => {\n  const asked = new Map<string, Asked>();\n  return Object.fromEntries(\n    engine.host.toolNames.map((name) => [\n      name,\n      (args: Record<string, unknown>) => {\n        const userInitiated = isActing();\n        if (userInitiated) return engine.host.runTool(name, args, { userInitiated });\n        let key: string;\n        try {\n          key = `${name}\\u0000${JSON.stringify(args)}`;\n        } catch {\n          return engine.host.runTool(name, args);\n        }\n        const last = asked.get(key);\n        if (last && Date.now() - last.at < QUERY_REFRESH_MS) return last.output;\n        const output = engine.host.runTool(name, args);\n        asked.set(key, { at: Date.now(), output });\n        return output;\n      },\n    ]),\n  );\n};\n\nconst errorOf = ({ code, component, message, statementId }: LangError): OpenUIError => ({\n  code,\n  message,\n  ...(component ? { component } : {}),\n  ...(statementId ? { statementId } : {}),\n});\n\n// Each error of a reply once, and only once the reply is written: while it streams, a program\n// is unfinished, and what it lacks is still coming.\nconst reportOnce = (engine: OpenUIEngine, messageId: string, errors: LangError[]) => {\n  let reported = engine.reported.get(messageId);\n  if (!reported) engine.reported.set(messageId, (reported = new Set()));\n  for (const error of errors) {\n    if (error.severity === 'warning') continue;\n    const key = [error.code, error.message, error.statementId].join('\\u0000');\n    if (reported.has(key)) continue;\n    reported.add(key);\n    engine.report(errorOf(error), messageId);\n  }\n};\n\n// Whether a program, as OpenUI read it, draws nothing: no root, such as words that aren't\n// OpenUI at all.\nconst drawsNothing = (parsed: ParseResult | null) =>\n  !!parsed && !parsed.root && !parsed.rootExpression;\n\n/** A reply's UI, following its program as the agent writes it. */\nexport const OpenUIReplyContent = ({\n  document,\n  engine,\n  messageId,\n}: {\n  document: AIUIDocument;\n  engine: OpenUIEngine;\n  messageId: string;\n}) => {\n  const library = libraryOf(engine);\n  const { isStreaming } = document;\n  const program = aiUIDocumentText(document) ?? '';\n  const errors = useRef<LangError[]>([]);\n  const parsed = useRef<ParseResult | null>(null);\n  const reply = useMemo(\n    () => ({ engine, isStreaming, messageId }),\n    [engine, isStreaming, messageId],\n  );\n  // What the person entered, kept by the host, so it survives scrolling and remounts.\n  const [initialState] = useState(() => {\n    const kept = engine.host.state(messageId);\n    return isRecord(kept) ? kept : undefined;\n  });\n  // What the person last pressed, whose words their message says.\n  const pressed = useRef<Pressed | undefined>(undefined);\n  // The program's state as OpenUI last gave it, secrets and all, which never leaves this reply.\n  const state = useRef<Record<string, unknown> | undefined>(initialState);\n  // When the person last pressed a control in this reply's UI, which the tools it runs count as\n  // theirs for a moment.\n  const pressedAt = useRef(-Infinity);\n  // The tools a program's Query() and Mutation() run: the renderer's, else the host's.\n  const toolProvider = useMemo(\n    () =>\n      engine.options.toolProvider ??\n      hostToolProvider(engine, () => Date.now() - pressedAt.current < TOOL_PRESS_MS),\n    [engine],\n  );\n  // Once the reply is written: what is wrong with its program, and whether it draws anything,\n  // as OpenUI last read it.\n  useEffect(() => {\n    if (isStreaming) return;\n    reportOnce(engine, messageId, errors.current);\n    if (drawsNothing(parsed.current)) engine.drewNothing(messageId, program);\n  }, [engine, isStreaming, messageId, program]);\n  const follow = aiUILinkOpener(engine.host);\n  const secrets = () => secretsOf(parsed.current);\n  return (\n    <OpenUIReplyContext.Provider value={reply}>\n      <div\n        className='str-chat__openui'\n        onAuxClickCapture={follow}\n        onClickCapture={(event) => {\n          if (isControl(event.target)) pressedAt.current = Date.now();\n          pressed.current = pressedOf(event.target) ?? pressed.current;\n          follow(event);\n        }}\n      >\n        <Renderer\n          initialState={initialState}\n          isStreaming={isStreaming}\n          library={library}\n          onAction={(event) => {\n            actOn(engine, messageId, event, {\n              pressed: pressed.current,\n              secrets: secrets(),\n              state: state.current,\n            });\n            pressed.current = undefined;\n          }}\n          onError={(found) => {\n            errors.current = found;\n            if (!isStreaming) reportOnce(engine, messageId, found);\n          }}\n          onParseResult={(result) => {\n            parsed.current = result;\n            if (!isStreaming && drawsNothing(result))\n              engine.drewNothing(messageId, program);\n          }}\n          onStateUpdate={(next) => {\n            state.current = next;\n            engine.host.setState(messageId, withoutSecrets(next, secrets()));\n          }}\n          response={program}\n          toolProvider={toolProvider}\n        />\n      </div>\n    </OpenUIReplyContext.Provider>\n  );\n};\n\n/** What the renderer's entry reaches once the runtime loads. */\nexport type OpenUIRuntime = {\n  instructionsFor: typeof instructionsFor;\n  OpenUIReplyContent: typeof OpenUIReplyContent;\n};\n"],"mappings":";;;;;;;;;;;AA0DA,IAAa,iBAAiB;;;;;;AAO9B,IAAa,uBAAuB,EAClC,aACA,QACA,iBAEA;CACE;CACA,GAAG,WAAW,SAAS,EAAE,aAAa,OAAO,WAC3C,QAAQ,CAAC,GAAG,KAAK,IAAI,OAAO,IAAI,CAAC,CACnC;CACA,GAAG,OAAO,KAAK,UAAU,MAAM,WAAW;AAC5C,CAAC,CACE,QAAQ,SAAS,KAAK,KAAK,MAAM,EAAE,CAAC,CACpC,IAAI,YAAY,CAAC,CACjB,KAAK,GAAG;;AAGb,IAAa,iBAAiB,EAAE,iBAC9B,EAAE,OACA,OAAO,YACL,WAAW,KAAK,EAAE,YAAY,MAAM,WAAW;CAC7C,MAAM,SAAS,EAAE,eAAe,IAAa;CAC7C,OAAO,CAAC,MAAM,aAAa,SAAS,OAAO,SAAS,CAAC;AACvD,CAAC,CACH,CACF;AAIF,IAAM,kBAAkB,YAAqB;CAC3C,MAAM,EAAE,UAAU,QAAQ,aAAa;CAGvC,OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,YACjD,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC,CAAC,CACpC,QAAQ,GAAG,UAAU,KAAK,UAAU,IAAI,CAAC,CAAC,SAAS,yBAAuB,CAAC,CAAC,CAC5E,KAAK,CAAC,UAAU,GAAG,KAAK,GAAG,MAAM,CACtC;AACF;AAQA,IAAM,qBAAqB,cAA6C,KAAA,CAAS;AAGjF,IAAM,mBAAmB,EACvB,WACA,YAII;CACJ,MAAM,QAAQ,WAAW,kBAAkB;CAC3C,IAAI,CAAC,OAAO,OAAO;CACn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