{"version":3,"file":"app-frame.cjs","sources":["../src/app-frame.ts"],"sourcesContent":["import { isOpenRequest, isTransferableRef, isTransferableSession, readContentHints, systemOpenUrl, type ContentHints, type ContentOpenTarget, type OpenRequest, type TransferableContentRef, type TransferableSessionContext } from './content'\nexport interface AppFrameMessage<T extends string = string, P = unknown> {\n  protocol: 'buckyos.app-frame'; version: 1; type: T; id?: string; replyTo?: string; payload: P\n}\nexport interface FrameInit {\n  nonce: string\n  windowId: string\n  formFactor: 'desktop' | 'mobile'\n  theme: { mode: 'light' | 'dark'; accent?: string }\n  locale: string\n  launch?: OpenRequest\n  shellCapabilities: string[]\n}\nexport type CloseDecision = 'allow' | 'deny' | 'pending'\nconst envelope = (type: string, payload: unknown, extra: { id?: string; replyTo?: string } = {}): AppFrameMessage =>\n  ({ protocol: 'buckyos.app-frame', version: 1, type, payload, ...extra })\nconst isMessage = (value: unknown): value is AppFrameMessage => {\n  if (!value || typeof value !== 'object') return false\n  const v = value as AppFrameMessage\n  return v.protocol === 'buckyos.app-frame' && v.version === 1 && typeof v.type === 'string' && !!v.payload && typeof v.payload === 'object'\n}\nexport class AppFrameHost {\n  ready = false\n  capabilities: string[] = []\n  private pending = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout>; type: string }>()\n  private listener = (event: MessageEvent) => this.receive(event)\n  private opens: number[] = []\n  constructor(private options: {\n    target: () => Window | null; origin: string; init: FrameInit\n    onReady?: () => void\n    onTitle?: (title: string, dirty: boolean) => void\n    onRequestClose?: () => void\n    onContentOpen?: (request: OpenRequest, target: ContentOpenTarget, options: { newWindow: boolean; hints: ContentHints }) => void\n  }) { window.addEventListener('message', this.listener) }\n  private focused?: boolean\n  private receive(event: MessageEvent): void {\n    if (event.source !== this.options.target() || event.origin !== this.options.origin || !isMessage(event.data)) return\n    const m = event.data\n    const p = m.payload as Record<string, unknown>\n    if (m.type === 'frame.hello') {\n      if (p.nonce !== this.options.init.nonce || !Array.isArray(p.appCapabilities)) return\n      this.ready = true\n      this.capabilities = p.appCapabilities.filter((c): c is string => typeof c === 'string')\n      this.send('frame.init', this.options.init)\n      if (this.focused !== undefined) this.send('frame.focusChanged', { focused: this.focused })\n      this.options.onReady?.()\n      return\n    }\n    if (!this.ready) return\n    if (m.replyTo) {\n      const pending = this.pending.get(m.replyTo)\n      if (pending && m.type === pending.type + 'Result') {\n        clearTimeout(pending.timer); this.pending.delete(m.replyTo); pending.resolve(m.payload)\n      }\n      return\n    }\n    if (m.type === 'window.setTitle' && typeof p.title === 'string') this.options.onTitle?.(p.title.slice(0, 256), p.dirty === true)\n    if (m.type === 'window.requestClose') this.options.onRequestClose?.()\n    if (m.type === 'content.open' && (p.target === 'default' || p.target === 'preview' || p.target === 'chooser')) {\n      const request = { ...(p.request as object), requestId: crypto.randomUUID() }\n      if (!isOpenRequest(request)) return\n      this.opens = this.opens.filter(t => t > Date.now() - 10000)\n      if (this.opens.length >= 5) return\n      this.opens.push(Date.now())\n      this.options.onContentOpen?.(request, p.target, { newWindow: p.newWindow === true, hints: readContentHints(p.hints) })\n    }\n  }\n  update(init: Partial<FrameInit>): void { this.options.init = { ...this.options.init, ...init } }\n  /** Reports whether the App's window is the focused one; only a change is sent. */\n  setFocused(focused: boolean): void {\n    if (this.focused === focused) return\n    this.focused = focused\n    this.send('frame.focusChanged', { focused })\n  }\n  send(type: string, payload: unknown): void {\n    if (this.ready) this.options.target()?.postMessage(envelope(type, payload), this.options.origin)\n  }\n  request(type: string, payload: unknown, timeout = 3000): Promise<unknown> {\n    if (!this.ready) return Promise.reject(new Error('App frame is not ready'))\n    const id = crypto.randomUUID()\n    return new Promise((resolve, reject) => {\n      const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('App frame timed out')) }, timeout)\n      this.pending.set(id, { resolve, reject, timer, type })\n      this.options.target()?.postMessage(envelope(type, payload, { id }), this.options.origin)\n    })\n  }\n  async open(request: OpenRequest): Promise<{ accepted: boolean; fallback?: 'preview' }> {\n    if (!this.capabilities.includes('open')) return { accepted: false }\n    return await this.request('frame.open', { request }) as { accepted: boolean; fallback?: 'preview' }\n  }\n  async beforeClose(reason: 'user' | 'logout' | 'shell' = 'user'): Promise<CloseDecision> {\n    if (!this.ready || !this.capabilities.includes('beforeClose')) return 'allow'\n    const r = await this.request('frame.beforeClose', { reason }) as { decision?: CloseDecision }\n    return r.decision === 'allow' || r.decision === 'pending' ? r.decision : 'deny'\n  }\n  async back(): Promise<boolean> {\n    if (!this.capabilities.includes('back')) return false\n    return (await this.request('frame.back', {}) as { handled?: boolean }).handled === true\n  }\n  dispose(): void {\n    window.removeEventListener('message', this.listener)\n    this.pending.forEach(p => { clearTimeout(p.timer); p.reject(new Error('App frame disposed')) })\n    this.pending.clear(); this.ready = false\n  }\n}\n/**\n * Origin of the window embedding this page, when `accept` admits it. `location.ancestorOrigins` names the real\n * parent even after the frame navigated through other pages (a sign-in round trip); the referrer is the fallback.\n */\nexport function embedderOrigin(accept: (origin: string) => boolean): string | null {\n  if (window.parent === window) return null\n  const candidates = [window.location.ancestorOrigins?.[0], document.referrer]\n  for (const candidate of candidates) {\n    if (!candidate) continue\n    try {\n      const origin = new URL(candidate).origin\n      if (accept(origin)) return origin\n    } catch {}\n  }\n  return null\n}\nexport const originInZone = (origin: string, zoneHost: string): boolean => {\n  try {\n    const url = new URL(origin)\n    return url.protocol === window.location.protocol && (url.hostname === zoneHost || url.hostname.endsWith(`.${zoneHost}`))\n  } catch { return false }\n}\nexport class AppFrameClient {\n  init?: FrameInit\n  private title?: string\n  private focused?: boolean\n  private helloTimer?: ReturnType<typeof setInterval>\n  private helloDeadline?: ReturnType<typeof setTimeout>\n  private readonly nonce: string | null\n  private readonly origin: string\n  private readonly listener = (event: MessageEvent) => { void this.receive(event) }\n  constructor(private options: {\n    shellOrigin: string\n    /** The Zone's system entry (its root origin): where content is opened when this page is not embedded in the shell. */\n    systemOrigin?: string\n    /** This App's id, so the system does not offer the content back to it. */\n    appId?: string\n    onInit?: (init: FrameInit) => void\n    onOpen?: (request: OpenRequest) => Promise<{ accepted: boolean; fallback?: 'preview' }> | { accepted: boolean; fallback?: 'preview' }\n    onBeforeClose?: (reason: 'user' | 'logout' | 'shell') => Promise<CloseDecision> | CloseDecision\n    onBack?: () => Promise<boolean> | boolean\n    onTheme?: (theme: FrameInit['theme']) => void\n    onLocale?: (locale: string) => void\n    onFocus?: (focused: boolean) => void\n  }) {\n    this.origin = new URL(options.shellOrigin).origin\n    this.nonce = new URLSearchParams(window.location.hash.slice(1)).get('bfp')\n    window.addEventListener('message', this.listener)\n    if (window.parent !== window && this.nonce) {\n      const hello = () => window.parent.postMessage(envelope('frame.hello', { nonce: this.nonce, appCapabilities: [\n        ...options.onOpen ? ['open'] : [], ...options.onBeforeClose ? ['beforeClose'] : [], ...options.onBack ? ['back'] : [],\n      ] }), this.origin)\n      hello()\n      this.helloTimer = setInterval(hello, 250)\n      this.helloDeadline = setTimeout(() => clearInterval(this.helloTimer), 1500)\n    }\n  }\n  private async receive(event: MessageEvent): Promise<void> {\n    if (event.source !== window.parent || event.origin !== this.origin || !isMessage(event.data)) return\n    const m = event.data\n    const p = m.payload as Record<string, unknown>\n    if (m.type === 'frame.init') {\n      if (!this.nonce || p.nonce !== this.nonce || typeof p.locale !== 'string' || !p.theme || typeof p.windowId !== 'string' || p.launch && !isOpenRequest(p.launch)) return\n      clearInterval(this.helloTimer); clearTimeout(this.helloDeadline)\n      this.init = p as unknown as FrameInit\n      this.title = undefined; this.focused = undefined\n      this.options.onInit?.(this.init)\n      return\n    }\n    if (!this.init) return\n    const reply = (payload: unknown) => window.parent.postMessage(envelope(m.type + 'Result', payload, { replyTo: m.id }), this.origin)\n    try {\n      if (m.type === 'frame.open' && isOpenRequest(p.request)) reply(await this.options.onOpen?.(p.request) ?? { accepted: false })\n      if (m.type === 'frame.beforeClose') reply({ decision: await this.options.onBeforeClose?.(p.reason as 'user') ?? 'allow' })\n      if (m.type === 'frame.back') reply({ handled: await this.options.onBack?.() ?? false })\n      if (m.type === 'frame.themeChanged' && (p.mode === 'dark' || p.mode === 'light')) this.options.onTheme?.(p as FrameInit['theme'])\n      if (m.type === 'frame.localeChanged' && typeof p.locale === 'string') this.options.onLocale?.(p.locale)\n      if (m.type === 'frame.focusChanged' && this.focused !== (p.focused === true)) { this.focused = p.focused === true; this.options.onFocus?.(this.focused) }\n    } catch {\n      if (m.type === 'frame.open') reply({ accepted: false, fallback: 'preview' })\n      if (m.type === 'frame.beforeClose') reply({ decision: 'deny' })\n    }\n  }\n  send(type: string, payload: unknown): void {\n    if (this.init) window.parent.postMessage(envelope(type, payload), this.origin)\n  }\n  setTitle(title: string, dirty = false): void {\n    const key = JSON.stringify([title, dirty])\n    if (!this.init || key === this.title) return\n    this.title = key\n    this.send('window.setTitle', { title, dirty })\n  }\n  requestClose(): void { this.send('window.requestClose', {}) }\n  /**\n   * Asks the system to open content: with its default app, in Preview, or by letting the user choose (`chooser`).\n   * Embedded in the shell the request goes over the frame; in a standalone tab it opens the Zone's system entry\n   * (`systemOrigin`) in a new tab. Returns false when neither is available.\n   */\n  openContent(request: Omit<OpenRequest, 'requestId'>, target: ContentOpenTarget = 'default', options: { newWindow?: boolean; hints?: ContentHints } = {}): boolean {\n    const hints = options.hints ?? {}\n    if (this.init) { this.send('content.open', { request, target, newWindow: options.newWindow === true, hints }); return true }\n    if (!this.options.systemOrigin) return false\n    window.open(systemOpenUrl(this.options.systemOrigin, { request, target, hints, from: this.options.appId }), '_blank', 'noopener')\n    return true\n  }\n  dispose(): void { clearInterval(this.helloTimer); clearTimeout(this.helloDeadline); window.removeEventListener('message', this.listener) }\n}\n\n/**\n * Preview embed protocol (`buckyos.preview-embed` v1): an App shows the system Preview component inside its own UI.\n * The App frames `<systemOrigin>/embed/preview` (component only, no shell) and hands it a content reference; the\n * system page reads the content with its own Zone-root session, so no token crosses origins. Open With goes back\n * through the App to the shell (`AppFrameClient.openContent(…, 'chooser')`).\n */\nexport type PreviewEmbedSource = TransferableContentRef | { kind: 'blob'; blob: Blob; name: string }\nexport interface PreviewEmbedInit {\n  nonce: string\n  source: PreviewEmbedSource\n  session?: TransferableSessionContext\n  theme: 'light' | 'dark'\n  locale: string\n}\nexport interface PreviewEmbedState {\n  status: 'loading' | 'ready' | 'error'\n  /** Preview error kind (`unsupported`, `not-found`, `permission-denied`, `timeout`, `error`, …) and code. */\n  error?: { kind: string; code: string }\n  title?: string\n  mediaType?: string\n}\nexport interface PreviewEmbedOpenWith { request: Omit<OpenRequest, 'requestId'>; hints: ContentHints }\nconst PREVIEW_EMBED = 'buckyos.preview-embed'\nconst embedEnvelope = (type: string, payload: unknown) => ({ protocol: PREVIEW_EMBED, version: 1, type, payload })\nconst isEmbedMessage = (value: unknown): value is { type: string; payload: Record<string, unknown> } => {\n  const v = value as { protocol?: unknown; version?: unknown; type?: unknown; payload?: unknown } | null\n  return !!v && v.protocol === PREVIEW_EMBED && v.version === 1 && typeof v.type === 'string' && !!v.payload && typeof v.payload === 'object'\n}\nconst isEmbedSource = (value: unknown): value is PreviewEmbedSource =>\n  isTransferableRef(value) || (!!value && typeof value === 'object' && (value as { kind?: unknown }).kind === 'blob' &&\n    typeof Blob !== 'undefined' && (value as { blob?: unknown }).blob instanceof Blob && typeof (value as { name?: unknown }).name === 'string')\nexport const PREVIEW_EMBED_PATH = '/embed/preview'\n\n/** App side: owns the iframe that shows the system Preview. */\nexport class PreviewEmbed {\n  readonly url: string\n  private readonly nonce = crypto.randomUUID()\n  private readonly origin: string\n  private readonly listener = (event: MessageEvent) => this.receive(event)\n  private init: Omit<PreviewEmbedInit, 'nonce'>\n  constructor(private options: {\n    systemOrigin: string\n    frame: () => HTMLIFrameElement | null\n    init: Omit<PreviewEmbedInit, 'nonce'>\n    onState?: (state: PreviewEmbedState) => void\n    onOpenWith?: (open: PreviewEmbedOpenWith) => void\n    onExit?: () => void\n  }) {\n    this.origin = new URL(options.systemOrigin).origin\n    this.init = options.init\n    this.url = `${this.origin}${PREVIEW_EMBED_PATH}#bpe=${this.nonce}&po=${encodeURIComponent(window.location.origin)}`\n    window.addEventListener('message', this.listener)\n  }\n  private post(type: string, payload: unknown): void {\n    this.options.frame()?.contentWindow?.postMessage(embedEnvelope(type, payload), this.origin)\n  }\n  private receive(event: MessageEvent): void {\n    if (event.origin !== this.origin || event.source !== this.options.frame()?.contentWindow || !isEmbedMessage(event.data)) return\n    const { type, payload: p } = event.data\n    if (type === 'embed.hello') { if (p.nonce === this.nonce) this.post('embed.init', { ...this.init, nonce: this.nonce }); return }\n    if (type === 'embed.state' && (p.status === 'loading' || p.status === 'ready' || p.status === 'error')) {\n      const error = p.error as { kind?: unknown; code?: unknown } | undefined\n      this.options.onState?.({ status: p.status,\n        error: error && typeof error.kind === 'string' && typeof error.code === 'string' ? { kind: error.kind, code: error.code } : undefined,\n        title: typeof p.title === 'string' ? p.title.slice(0, 256) : undefined, mediaType: typeof p.mediaType === 'string' ? p.mediaType.slice(0, 128) : undefined })\n    }\n    if (type === 'embed.openWith') {\n      const request = p.request as Omit<OpenRequest, 'requestId'> | undefined\n      if (request && isTransferableRef(request.source) && (request.session === undefined || isTransferableSession(request.session))) {\n        this.options.onOpenWith?.({ request: { source: request.source, session: request.session }, hints: readContentHints(p.hints) })\n      }\n    }\n    if (type === 'embed.exit') this.options.onExit?.()\n  }\n  update(patch: Partial<Pick<PreviewEmbedInit, 'theme' | 'locale'>>): void {\n    this.init = { ...this.init, ...patch }\n    this.post('embed.update', patch)\n  }\n  dispose(): void { window.removeEventListener('message', this.listener) }\n}\n\n/** System side: the component-only page at `PREVIEW_EMBED_PATH`. Accepts one embedding App whose origin `accept` admits. */\nexport class PreviewEmbedHost {\n  readonly parentOrigin: string | null\n  private readonly nonce: string | null\n  private ready = false\n  private readonly hello?: ReturnType<typeof setInterval>\n  private readonly listener = (event: MessageEvent) => this.receive(event)\n  constructor(private options: {\n    accept: (origin: string) => boolean\n    onInit: (init: PreviewEmbedInit) => void\n    onUpdate?: (patch: Partial<Pick<PreviewEmbedInit, 'theme' | 'locale'>>) => void\n  }) {\n    const params = new URLSearchParams(window.location.hash.slice(1))\n    this.nonce = params.get('bpe')\n    let parentOrigin: string | null = null\n    try { parentOrigin = new URL(params.get('po') ?? '').origin } catch {}\n    this.parentOrigin = window.parent !== window && this.nonce && parentOrigin && options.accept(parentOrigin) ? parentOrigin : null\n    if (!this.parentOrigin) return\n    window.addEventListener('message', this.listener)\n    const hello = () => window.parent.postMessage(embedEnvelope('embed.hello', { nonce: this.nonce }), this.parentOrigin!)\n    hello()\n    this.hello = setInterval(() => { if (!this.ready) hello() }, 250)\n  }\n  private receive(event: MessageEvent): void {\n    if (event.source !== window.parent || event.origin !== this.parentOrigin || !isEmbedMessage(event.data)) return\n    const { type, payload: p } = event.data\n    if (type === 'embed.init') {\n      if (p.nonce !== this.nonce || !isEmbedSource(p.source) || (p.session !== undefined && !isTransferableSession(p.session)) || typeof p.locale !== 'string') return\n      this.ready = true; clearInterval(this.hello)\n      this.options.onInit({ nonce: String(p.nonce), source: p.source, session: p.session as TransferableSessionContext | undefined, theme: p.theme === 'dark' ? 'dark' : 'light', locale: p.locale })\n      return\n    }\n    if (type === 'embed.update' && this.ready) {\n      const patch: Partial<Pick<PreviewEmbedInit, 'theme' | 'locale'>> = {}\n      if (p.theme === 'dark' || p.theme === 'light') patch.theme = p.theme\n      if (typeof p.locale === 'string') patch.locale = p.locale\n      this.options.onUpdate?.(patch)\n    }\n  }\n  private post(type: string, payload: unknown): void {\n    if (this.ready && this.parentOrigin) window.parent.postMessage(embedEnvelope(type, payload), this.parentOrigin)\n  }\n  state(state: PreviewEmbedState): void { this.post('embed.state', state) }\n  openWith(open: PreviewEmbedOpenWith): void { this.post('embed.openWith', open) }\n  exit(): void { this.post('embed.exit', {}) }\n  dispose(): void { clearInterval(this.hello); window.removeEventListener('message', this.listener) }\n}\n"],"names":["envelope","type","payload","extra","protocol","version","isMessage","value","v","PREVIEW_EMBED","embedEnvelope","isEmbedMessage","PREVIEW_EMBED_PATH","constructor","options","this","listener","event","receive","origin","URL","shellOrigin","nonce","URLSearchParams","window","location","hash","slice","get","addEventListener","parent","hello","postMessage","appCapabilities","onOpen","onBeforeClose","onBack","helloTimer","setInterval","helloDeadline","setTimeout","clearInterval","source","data","m","p","locale","theme","windowId","launch","isOpenRequest","clearTimeout","init","title","focused","_b","_a","onInit","call","reply","replyTo","id","request","_d","_c","accepted","decision","_f","_e","reason","handled","_h","_g","mode","_j","_i","onTheme","_l","_k","onLocale","_n","_m","onFocus","fallback","send","setTitle","dirty","key","JSON","stringify","requestClose","openContent","target","hints","newWindow","systemOrigin","open","systemOpenUrl","from","appId","dispose","removeEventListener","ready","capabilities","pending","Map","opens","Array","isArray","filter","c","onReady","timer","delete","resolve","onTitle","onRequestClose","requestId","crypto","randomUUID","t","Date","now","length","push","onContentOpen","readContentHints","update","setFocused","timeout","Promise","reject","Error","set","includes","beforeClose","r","back","forEach","clear","url","encodeURIComponent","post","frame","contentWindow","status","error","onState","kind","code","mediaType","isTransferableRef","session","isTransferableSession","onOpenWith","onExit","patch","params","parentOrigin","accept","Blob","blob","name","String","onUpdate","state","openWith","exit","candidates","ancestorOrigins","document","referrer","candidate","zoneHost","hostname","endsWith"],"mappings":"uJAcA,MAAMA,EAAW,CAACC,EAAcC,EAAkBC,EAA2C,CAAA,KAAA,CACxFC,SAAU,oBAAqBC,QAAS,EAAGJ,OAAMC,aAAYC,IAC5DG,EAAaC,IACb,IAACA,GAA0B,iBAAVA,EAA2B,OAAA,EAChD,MAAMC,EAAID,EACV,MAAsB,sBAAfC,EAAEJ,UAAkD,IAAdI,EAAEH,SAAmC,iBAAXG,EAAEP,QAAuBO,EAAEN,SAAgC,iBAAdM,EAAEN,OAAY,EAwNpI,MAAMO,EAAgB,wBAChBC,EAAgB,CAACT,EAAcC,KAAsB,CAAEE,SAAUK,EAAeJ,QAAS,EAAGJ,OAAMC,YAClGS,EAAkBJ,IACtB,MAAMC,EAAID,EACV,QAASC,GAAKA,EAAEJ,WAAaK,GAA+B,IAAdD,EAA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