buckyos 0.7.185 → 0.7.187

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -675,7 +675,7 @@ const setPropCommand: CommandDefinition = {
675
675
 
676
676
  const infoCommand: CommandDefinition = {
677
677
  verb: 'info',
678
- summary: 'Workspace info: versions, capabilities of the caller, usage, hosted execution configuration',
678
+ summary: 'Workspace info: versions, capabilities of the caller, usage, where wish runs execute by default',
679
679
  options: [WORKSPACE_OPTION],
680
680
  inputSchema: workspaceInput({}),
681
681
  outputSchema: OBJECT_OUTPUT,
@@ -44,6 +44,34 @@ function desired(verb: string, summary: string, enabled: boolean): CommandDefini
44
44
  }
45
45
  }
46
46
 
47
+ /** An online item is what a package only declares: each node downloads it from its upstream once, when the package is
48
+ * installed. A download that failed stays failed until it is asked for again, which is what this does. */
49
+ function download(): CommandDefinition {
50
+ return {
51
+ verb: 'download',
52
+ summary: 'Ask the nodes to download an online item of a package again: after a failure, or to replace what is there',
53
+ positionals: [
54
+ { name: 'id', description: 'Package id, e.g. ext-core' },
55
+ { name: 'item', description: 'Online item id, e.g. chromium (see `online` in ext-tools status)' },
56
+ ],
57
+ options: [{ name: 'node', description: 'Only this node; without it every node that has the item', type: 'string' as const }],
58
+ inputSchema: {
59
+ type: 'object',
60
+ properties: { id: ID, item: ID, node: { type: 'string', minLength: 1 } },
61
+ required: ['id', 'item'],
62
+ additionalProperties: false,
63
+ },
64
+ outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: { mode: 'fixed', level: 'write' },
65
+ asyncMode: 'sync', requiresSession: true,
66
+ handler: (ctx, input) => {
67
+ for (const name of ['id', 'item']) {
68
+ if (typeof input[name] !== 'string' || !input[name]) throw new UsageError('MISSING_ARGUMENT', `a package id and an online item id are required`)
69
+ }
70
+ return call(ctx, 'ext_tools.download', { id: input.id, item: input.item, ...(typeof input.node === 'string' ? { node: input.node } : {}) })
71
+ },
72
+ }
73
+ }
74
+
47
75
  /** The Zone's extension packages. The administrator says what the Zone should have; each node's reconciler gets there. */
48
76
  export function createExtToolsModule(): CommandModule {
49
77
  return {
@@ -51,9 +79,10 @@ export function createExtToolsModule(): CommandModule {
51
79
  summary: 'Manage the extension tool packages every Agent of the Zone shares',
52
80
  commands: [
53
81
  read('list', 'The packages published in the Repo, and what each provides', 'ext_tools.catalog'),
54
- read('status', 'Package by node: what is asked for and where each node got to', 'ext_tools.status'),
82
+ read('status', 'Package by node: what is asked for, where each node got to, and the online items it downloaded or still waits for', 'ext_tools.status'),
55
83
  desired('enable', 'Enable or upgrade a package, with the packages it requires', true),
56
84
  desired('disable', 'Disable a package; refused while an enabled package requires it', false),
85
+ download(),
57
86
  {
58
87
  verb: 'import',
59
88
  summary: 'Put an already built .pikg (an official release asset) into the Repo unchanged',
@@ -579,17 +579,113 @@ export function extToolsPlatformOfKey(key: string): ExtToolsPlatform | undefined
579
579
  return EXT_TOOLS_PLATFORMS.find((platform) => platform.key === key)
580
580
  }
581
581
 
582
+ /** Where one platform gets an online item: the upstream's own archive, and what to do with it once unpacked. */
583
+ export interface ExtToolsOnlineSource {
584
+ url: string
585
+ sha256: string
586
+ size_bytes: number
587
+ format: string
588
+ into?: string
589
+ rename?: Array<[string, string]>
590
+ overlay?: string
591
+ }
592
+
593
+ /** Something a package only declares: a node downloads it from the upstream to `tools/online/<id>/` once the package is
594
+ * installed. A platform without an entry has no such item. */
595
+ export interface ExtToolsOnlineItem {
596
+ id: string
597
+ version: string
598
+ desc?: string
599
+ license?: string
600
+ auto?: boolean
601
+ platforms: Record<string, ExtToolsOnlineSource>
602
+ }
603
+
582
604
  export interface ExtToolsManifest {
583
605
  schema: string
584
606
  id: string
585
607
  version: string
586
608
  requires: Array<{ id: string; version: string }>
587
609
  conflicts: string[]
588
- provides: Array<{ command: string; version_probe: string; smoke?: string }>
610
+ provides: Array<{ command: string; version_probe: string; smoke?: string; needs?: string[] }>
589
611
  platforms: string[]
590
612
  size_bytes?: Record<string, number>
591
613
  license?: string
592
614
  desc?: string
615
+ online?: ExtToolsOnlineItem[]
616
+ }
617
+
618
+ const EXT_TOOLS_VERSION = /^[A-Za-z0-9._+-]+$/
619
+ export const EXT_TOOLS_ONLINE_FORMATS = ['zip', 'tar.gz']
620
+
621
+ function unknownKeys(value: Record<string, unknown>, allowed: string[]): string[] {
622
+ return Object.keys(value).filter((key) => !allowed.includes(key))
623
+ }
624
+
625
+ function isHttpsUrl(value: unknown): boolean {
626
+ if (typeof value !== 'string') return false
627
+ try {
628
+ const url = new URL(value)
629
+ return url.protocol === 'https:' && url.hostname !== ''
630
+ } catch {
631
+ return false
632
+ }
633
+ }
634
+
635
+ /** What is wrong with one platform's source of online item `item` (Rust: `ExtToolsOnlineSource::problem`). */
636
+ function extToolsOnlineSourceErrors(item: string, raw: unknown): string[] {
637
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return ['must be an object']
638
+ const source = raw as Record<string, unknown>
639
+ const errors = unknownKeys(source, ['url', 'sha256', 'size_bytes', 'format', 'into', 'rename', 'overlay']).map((key) => `${key} is not a field`)
640
+ if (!isHttpsUrl(source.url)) errors.push(`url ${JSON.stringify(source.url)} must be an https address`)
641
+ if (typeof source.sha256 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(source.sha256)) errors.push('sha256 must be 64 hex digits')
642
+ if (!Number.isSafeInteger(source.size_bytes) || (source.size_bytes as number) <= 0) errors.push('size_bytes must be the size of the archive')
643
+ if (typeof source.format !== 'string' || !EXT_TOOLS_ONLINE_FORMATS.includes(source.format)) errors.push(`format ${JSON.stringify(source.format)} must be zip or tar.gz`)
644
+ if (source.into !== undefined && (typeof source.into !== 'string' || !isSafeRelativePath(source.into))) errors.push('into must be a relative path inside the item')
645
+ const pairs = source.rename === undefined ? [] : source.rename
646
+ const renamed = Array.isArray(pairs) && pairs.every((pair) =>
647
+ Array.isArray(pair) && pair.length === 2 && pair.every((path) => typeof path === 'string' && isSafeRelativePath(path)) && pair[0] !== pair[1]
648
+ )
649
+ if (!renamed) errors.push('rename must be [from, to] pairs of relative paths inside the item')
650
+ const root = `online/${item}`
651
+ const overlay = source.overlay
652
+ if (overlay !== undefined && !(typeof overlay === 'string' && isSafeRelativePath(overlay) && (overlay === root || overlay.startsWith(`${root}/`)))) {
653
+ errors.push(`overlay must be ${root} or a directory below it`)
654
+ }
655
+ return errors
656
+ }
657
+
658
+ /** The `online` list of a manifest (Rust: `ExtToolsManifest::validate`), and the ids it declares. */
659
+ function extToolsOnlineErrors(manifest: Record<string, unknown>): { errors: string[]; items: Set<string> } {
660
+ const errors: string[] = []
661
+ const items = new Set<string>()
662
+ if (manifest.online === undefined) return { errors, items }
663
+ if (!Array.isArray(manifest.online)) return { errors: ['online must be a list of items'], items }
664
+ const platforms = Array.isArray(manifest.platforms) ? manifest.platforms : []
665
+ for (const raw of manifest.online) {
666
+ const item = (raw ?? {}) as Record<string, unknown>
667
+ const id = item.id
668
+ if (typeof id !== 'string' || !EXT_TOOLS_ID.test(id)) {
669
+ errors.push(`online: id ${JSON.stringify(id)} must be lowercase letters, digits and -`)
670
+ continue
671
+ }
672
+ if (items.has(id)) errors.push(`online: ${id} is listed twice`)
673
+ items.add(id)
674
+ for (const key of unknownKeys(item, ['id', 'version', 'desc', 'license', 'auto', 'platforms'])) errors.push(`online ${id}: ${key} is not a field`)
675
+ if (typeof item.version !== 'string' || !EXT_TOOLS_VERSION.test(item.version)) errors.push(`online ${id}: version must be letters, digits and ._+-`)
676
+ for (const text of ['desc', 'license']) if (item[text] !== undefined && typeof item[text] !== 'string') errors.push(`online ${id}: ${text} must be a string`)
677
+ if (item.auto !== undefined && typeof item.auto !== 'boolean') errors.push(`online ${id}: auto must be true or false`)
678
+ const sources = item.platforms
679
+ if (!sources || typeof sources !== 'object' || Array.isArray(sources) || Object.keys(sources).length === 0) {
680
+ errors.push(`online ${id}: platforms must not be empty`)
681
+ continue
682
+ }
683
+ for (const [platform, source] of Object.entries(sources)) {
684
+ if (!platforms.includes(platform)) errors.push(`online ${id}: ${platform} is not a platform of the package`)
685
+ for (const problem of extToolsOnlineSourceErrors(id, source)) errors.push(`online ${id} on ${platform}: ${problem}`)
686
+ }
687
+ }
688
+ return { errors, items }
593
689
  }
594
690
 
595
691
  /** The manifest's own rules (`buckyos.ext_tools/1`, doc/pikg/format.md §5), each problem one line. */
@@ -597,12 +693,14 @@ export function extToolsManifestErrors(value: unknown): string[] {
597
693
  if (!value || typeof value !== 'object' || Array.isArray(value)) return ['must be a JSON object']
598
694
  const manifest = value as Record<string, unknown>
599
695
  const errors: string[] = []
600
- const allowed = ['schema', 'id', 'version', 'requires', 'conflicts', 'provides', 'platforms', 'size_bytes', 'license', 'desc']
696
+ const allowed = ['schema', 'id', 'version', 'requires', 'conflicts', 'provides', 'platforms', 'size_bytes', 'license', 'desc', 'online']
601
697
  for (const key of Object.keys(manifest)) if (!allowed.includes(key)) errors.push(`${key} is not a field of the manifest`)
602
698
  if (manifest.schema !== EXT_TOOLS_MANIFEST_SCHEMA) errors.push(`schema must be ${EXT_TOOLS_MANIFEST_SCHEMA}`)
603
699
  if (typeof manifest.id !== 'string' || !EXT_TOOLS_ID.test(manifest.id)) errors.push('id must be lowercase letters, digits and -')
604
- if (typeof manifest.version !== 'string' || !/^[A-Za-z0-9._+-]+$/.test(manifest.version)) errors.push('version must be letters, digits and ._+-')
700
+ if (typeof manifest.version !== 'string' || !EXT_TOOLS_VERSION.test(manifest.version)) errors.push('version must be letters, digits and ._+-')
605
701
  if (!Array.isArray(manifest.provides) || manifest.provides.length === 0) errors.push('provides must not be empty')
702
+ const online = extToolsOnlineErrors(manifest)
703
+ errors.push(...online.errors)
606
704
  const commands = new Set<string>()
607
705
  for (const raw of Array.isArray(manifest.provides) ? manifest.provides : []) {
608
706
  const entry = (raw ?? {}) as Record<string, unknown>
@@ -614,11 +712,19 @@ export function extToolsManifestErrors(value: unknown): string[] {
614
712
  if (commands.has(command)) errors.push(`provides: command ${command} is listed twice`)
615
713
  if (EXT_TOOLS_RESERVED_COMMANDS.includes(command)) errors.push(`provides: ${command} is a standard command and cannot be provided by a package`)
616
714
  commands.add(command)
715
+ for (const key of unknownKeys(entry, ['command', 'version_probe', 'smoke', 'needs'])) errors.push(`provides: ${key} is not a field of ${command}`)
617
716
  if (typeof entry.version_probe !== 'string' || !entry.version_probe.trim()) errors.push(`provides: ${command} has no version_probe`)
618
717
  const smoke = entry.smoke
619
718
  if (smoke !== undefined && (typeof smoke !== 'string' || !isSafeRelativePath(smoke))) {
620
719
  errors.push(`provides: the smoke of ${command} must be a relative path inside the payload`)
621
720
  }
721
+ const needs = entry.needs === undefined ? [] : entry.needs
722
+ if (!Array.isArray(needs) || !needs.every((need) => typeof need === 'string')) {
723
+ errors.push(`provides: the needs of ${command} must list online items by id`)
724
+ continue
725
+ }
726
+ for (const need of needs as string[]) if (!online.items.has(need)) errors.push(`provides: ${command} needs ${need}, which is not an online item of the package`)
727
+ if (new Set(needs).size !== needs.length) errors.push(`provides: ${command} needs an online item twice`)
622
728
  }
623
729
  if (!Array.isArray(manifest.platforms) || manifest.platforms.length === 0) errors.push('platforms must not be empty')
624
730
  for (const platform of Array.isArray(manifest.platforms) ? manifest.platforms : []) {
@@ -669,12 +775,19 @@ export function extToolsPayloadErrors(manifest: ExtToolsManifest, platform: stri
669
775
  const errors: string[] = []
670
776
  const windows = platform.startsWith('windows-')
671
777
  const suffixes = windows ? EXT_TOOLS_WINDOWS_SUFFIXES : ['']
778
+ const online = manifest.online ?? []
672
779
  for (const path of [...tree.files.keys(), ...tree.directories]) {
673
780
  const [top, second] = path.split('/')
674
781
  const isTop = !path.includes('/')
675
- const known = top === EXT_TOOLS_MANIFEST_FILE && isTop || top === 'bin' || top === 'smoke' || top === 'store'
676
- if (!known) errors.push(`${path}: a package only holds ${EXT_TOOLS_MANIFEST_FILE}, bin/, smoke/ and store/${manifest.id}/`)
782
+ const known = top === EXT_TOOLS_MANIFEST_FILE && isTop || top === 'bin' || top === 'smoke' || top === 'store' || top === 'online'
783
+ if (!known) errors.push(`${path}: a package only holds ${EXT_TOOLS_MANIFEST_FILE}, bin/, smoke/, store/${manifest.id}/ and online/<item>/`)
677
784
  if (top === 'store' && second !== undefined && second !== manifest.id) errors.push(`${path}: a package only writes store/${manifest.id}/`)
785
+ if (top === 'online' && second !== undefined && !online.some((item) => item.id === second)) errors.push(`${path}: not an online item of the package`)
786
+ }
787
+ for (const item of online) {
788
+ const overlay = item.platforms[platform]?.overlay
789
+ const present = overlay !== undefined && (tree.directories.has(overlay) || [...tree.files.keys()].some((path) => path.startsWith(`${overlay}/`)))
790
+ if (overlay !== undefined && !present) errors.push(`${overlay}: the overlay of online item ${item.id} is missing`)
678
791
  }
679
792
  const declared = new Set(manifest.provides.map((provided) => provided.command))
680
793
  for (const provided of manifest.provides) {
package/cli/version.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Generated by scripts/generate-cli-version.mjs. Do not edit.
2
- export const PACKAGE_VERSION = '0.7.185'
2
+ export const PACKAGE_VERSION = '0.7.187'
3
3
  export const TOOL_VERSION = PACKAGE_VERSION
4
4
  export const SDK_VERSION = PACKAGE_VERSION
5
5
  export const PROTOCOL_VERSION = '1'
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./content.cjs");require("./content_mime-dc80d960.js");const t=t=>e.SYSTEM_DIALOG_ERROR_CODES.includes(t)?t:"protocol",i=(e,t,i={})=>({protocol:"buckyos.app-frame",version:1,type:e,payload:t,...i}),o=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"buckyos.app-frame"===t.protocol&&1===t.version&&"string"==typeof t.type&&!!t.payload&&"object"==typeof t.payload};const n="buckyos.preview-embed",s=(e,t,i=n)=>({protocol:i,version:1,type:e,payload:t}),r=(e,t=n)=>{const i=e;return!!i&&i.protocol===t&&1===i.version&&"string"==typeof i.type&&!!i.payload&&"object"==typeof i.payload},a="/embed/preview";const l="buckyos.sysdlg-embed",d="/embed/sysdlg/select";let c=!1;function p(i,o,n={}){var a,p;if(null==(a=n.signal)?void 0:a.aborted)return Promise.reject(new e.SystemDialogError("closed"));if(c)return Promise.reject(new e.SystemDialogError("busy"));c=!0;const h=new URL(i).origin,u=n.locale??navigator.language??"en",m=n.theme??((null==(p=window.matchMedia)?void 0:p.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"),g=u.toLowerCase().startsWith("zh");return new Promise(((i,a)=>{var p;const y=document.body,f=document.documentElement,w=document.activeElement instanceof HTMLElement?document.activeElement:null,b={x:window.scrollX,y:window.scrollY},v={body:y.getAttribute("style"),html:f.getAttribute("style")},E=Array.from(y.children).filter((e=>e instanceof HTMLElement)).map((e=>({el:e,inert:e.inert,hidden:e.getAttribute("aria-hidden")}))),T=document.createElement("div");let L;T.setAttribute("data-buckyos-sysdlg","select"),T.setAttribute("role","dialog"),T.setAttribute("aria-modal","true"),T.setAttribute("aria-label",g?"文件选择器":"File picker"),T.style.cssText="position:fixed;inset:0;height:100vh;height:100dvh;z-index:2147483647;background:rgba(0,0,0,.32);display:flex;align-items:center;justify-content:center";let k,x="",C=!1;const O=e=>{T.contains(e.target)||(e.stopPropagation(),e.preventDefault())},A=["keydown","pointerdown","mousedown","touchstart","wheel"],S=()=>{var e;return!C&&(C=!0,c=!1,clearTimeout(k),window.removeEventListener("message",M),null==(e=n.signal)||e.removeEventListener("abort",R),"inert"in HTMLElement.prototype||A.forEach((e=>document.removeEventListener(e,O,!0))),T.remove(),E.forEach((({el:e,inert:t,hidden:i})=>{e.inert=t,null===i?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",i)})),null===v.body?y.removeAttribute("style"):y.setAttribute("style",v.body),null===v.html?f.removeAttribute("style"):f.setAttribute("style",v.html),window.scrollTo(b.x,b.y),null==w||w.focus({preventScroll:!0}),!0)},D=t=>{S()&&a(new e.SystemDialogError(t))},R=()=>D("closed"),I=()=>{null==L||L.remove(),L=void 0;const e=document.createElement("div");e.setAttribute("role","alert"),e.style.cssText=`max-width:22rem;margin:1rem;padding:1.25rem;border-radius:16px;font:14px/1.6 system-ui,sans-serif;background:${"dark"===m?"#1f2329":"#fff"};color:${"dark"===m?"#f2f3f5":"#1f2329"};box-shadow:0 24px 64px rgba(0,0,0,.24)`;const t=document.createElement("p");t.style.margin="0 0 1rem",t.textContent=g?"无法加载文件选择器":"Unable to load the file picker";const i=document.createElement("div");i.style.cssText="display:flex;gap:.5rem;justify-content:flex-end";const o=(e,t)=>{const o=document.createElement("button");return o.type="button",o.textContent=e,o.style.cssText="min-height:2.25rem;padding:0 1rem;font:inherit;border-radius:999px;border:1px solid currentColor;background:transparent;color:inherit;cursor:pointer",o.addEventListener("click",t),i.append(o),o};o(g?"取消":"Cancel",(()=>D("load_failed")));const n=o(g?"重试":"Retry",(()=>{e.remove(),U()}));e.append(t,i),T.append(e),n.focus()},U=()=>{x=crypto.randomUUID(),L=document.createElement("iframe"),L.title=g?"文件选择器":"File picker",L.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;color-scheme:normal",L.setAttribute("allowtransparency","true"),L.addEventListener("error",I),L.src=`${h}${d}#bse=${x}&po=${encodeURIComponent(window.location.origin)}`,T.append(L),k=setTimeout(I,1e4)},M=n=>{var a;if(!L||n.origin!==h||n.source!==L.contentWindow||!r(n.data,l))return;const{type:d,payload:c}=n.data;if("embed.hello"===d){if(c.nonce!==x)return;clearTimeout(k),null==(a=L.contentWindow)||a.postMessage(s("embed.init",{nonce:x,params:o,theme:m,locale:u},l),h),L.focus()}if("embed.error"===d&&D(t(c.code)),"embed.result"===d){const t=e.readSelectDialogResult(c.result,{allowLocal:!0===o.allowLocal});t?(e=>{S()&&i(e)})(t):D("protocol")}};window.addEventListener("message",M),null==(p=n.signal)||p.addEventListener("abort",R,{once:!0}),"inert"in HTMLElement.prototype?E.forEach((({el:e})=>{e.inert=!0})):(E.forEach((({el:e})=>e.setAttribute("aria-hidden","true"))),A.forEach((e=>document.addEventListener(e,O,!0)))),f.style.overflow="hidden",y.style.position="fixed",y.style.top=-b.y+"px",y.style.left=-b.x+"px",y.style.right="0",y.style.overflow="hidden",y.append(T),U()}))}exports.AppFrameClient=class{constructor(e){if(this.options=e,this.listener=e=>{this.receive(e)},this.dialogs=new Map,this.origin=new URL(e.shellOrigin).origin,this.nonce=new URLSearchParams(window.location.hash.slice(1)).get("bfp"),window.addEventListener("message",this.listener),window.parent!==window&&this.nonce){const t=()=>window.parent.postMessage(i("frame.hello",{nonce:this.nonce,appCapabilities:[...e.onOpen?["open"]:[],...e.onBeforeClose?["beforeClose"]:[],...e.onBack?["back"]:[]]}),this.origin);t(),this.helloTimer=setInterval(t,250),this.helloDeadline=setTimeout((()=>clearInterval(this.helloTimer)),1500)}}async receive(n){var s,r,a,l,d,c,p,h,u,m,g,y,f,w;if(n.source!==window.parent||n.origin!==this.origin||!o(n.data))return;const b=n.data,v=b.payload;if("frame.init"===b.type){if(!this.nonce||v.nonce!==this.nonce||"string"!=typeof v.locale||!v.theme||"string"!=typeof v.windowId||v.launch&&!e.isOpenRequest(v.launch))return;return clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),this.init=v,this.title=void 0,this.focused=void 0,void(null==(r=(s=this.options).onInit)||r.call(s,this.init))}if(!this.init)return;if("sysdlg.openResult"===b.type){const i=b.replyTo?this.dialogs.get(b.replyTo):void 0;if(!i)return;if(this.dialogs.delete(b.replyTo),!0!==v.ok)return i.reject(new e.SystemDialogError(t(v.code)));const o=e.readSelectDialogResult(v.result,{allowLocal:i.allowLocal});return void(o?i.resolve(o):i.reject(new e.SystemDialogError("protocol")))}const E=e=>window.parent.postMessage(i(b.type+"Result",e,{replyTo:b.id}),this.origin);try{"frame.open"===b.type&&e.isOpenRequest(v.request)&&E(await(null==(l=(a=this.options).onOpen)?void 0:l.call(a,v.request))??{accepted:!1}),"frame.beforeClose"===b.type&&E({decision:await(null==(c=(d=this.options).onBeforeClose)?void 0:c.call(d,v.reason))??"allow"}),"frame.back"===b.type&&E({handled:await(null==(h=(p=this.options).onBack)?void 0:h.call(p))??!1}),"frame.themeChanged"!==b.type||"dark"!==v.mode&&"light"!==v.mode||null==(m=(u=this.options).onTheme)||m.call(u,v),"frame.localeChanged"===b.type&&"string"==typeof v.locale&&(null==(y=(g=this.options).onLocale)||y.call(g,v.locale)),"frame.focusChanged"===b.type&&this.focused!==(!0===v.focused)&&(this.focused=!0===v.focused,null==(w=(f=this.options).onFocus)||w.call(f,this.focused))}catch{"frame.open"===b.type&&E({accepted:!1,fallback:"preview"}),"frame.beforeClose"===b.type&&E({decision:"deny"})}}send(e,t){this.init&&window.parent.postMessage(i(e,t),this.origin)}setTitle(e,t=!1){const i=JSON.stringify([e,t]);this.init&&i!==this.title&&(this.title=i,this.send("window.setTitle",{title:e,dirty:t}))}requestClose(){this.send("window.requestClose",{})}openContent(t,i="default",o={}){const n=o.hints??{};return this.init?(this.send("content.open",{request:t,target:i,newWindow:!0===o.newWindow,hints:n}),!0):!!this.options.systemOrigin&&(window.open(e.systemOpenUrl(this.options.systemOrigin,{request:t,target:i,hints:n,from:this.options.appId}),"_blank","noopener"),!0)}selectContent(t={},o={}){var n,s;if(this.init){if(!this.init.shellCapabilities.includes(e.SELECT_DIALOG_PATH))return Promise.reject(new e.SystemDialogError("unsupported"));if(this.dialogs.size)return Promise.reject(new e.SystemDialogError("busy"));const o=crypto.randomUUID();return new Promise(((n,s)=>{this.dialogs.set(o,{resolve:n,reject:s,allowLocal:!0===t.allowLocal}),window.parent.postMessage(i("sysdlg.open",{path:e.SELECT_DIALOG_PATH,params:t},{id:o}),this.origin)}))}if(!this.options.systemOrigin)return Promise.reject(new e.SystemDialogError("unsupported"));const r=this.embedAbort=new AbortController;return null==(n=o.signal)||n.addEventListener("abort",(()=>r.abort()),{once:!0}),(null==(s=o.signal)?void 0:s.aborted)&&r.abort(),p(this.options.systemOrigin,t,{...o,signal:r.signal})}dispose(){var t;clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),window.removeEventListener("message",this.listener),this.dialogs.forEach((t=>t.reject(new e.SystemDialogError("closed")))),this.dialogs.clear(),null==(t=this.embedAbort)||t.abort()}},exports.AppFrameHost=class{constructor(e){this.options=e,this.ready=!1,this.capabilities=[],this.pending=new Map,this.listener=e=>this.receive(e),this.opens=[],this.dialogOpen=!1,window.addEventListener("message",this.listener)}async systemDialog(t,o,n){const s=e=>{var o;this.ready&&(null==(o=this.options.target())||o.postMessage(i("sysdlg.openResult",e,{replyTo:t}),this.options.origin))};if(!this.options.onSystemDialog||"string"!=typeof o)return s({ok:!1,code:"unsupported"});if(this.dialogOpen)return s({ok:!1,code:"busy"});this.dialogOpen=!0;try{s(await this.options.onSystemDialog(o,n))}catch(r){s({ok:!1,code:r instanceof e.SystemDialogError?r.code:"closed"})}finally{this.dialogOpen=!1}}receive(t){var i,n,s,r,a,l,d,c;if(t.source!==this.options.target()||t.origin!==this.options.origin||!o(t.data))return;const p=t.data,h=p.payload;if("frame.hello"===p.type){if(h.nonce!==this.options.init.nonce||!Array.isArray(h.appCapabilities))return;return this.ready=!0,this.capabilities=h.appCapabilities.filter((e=>"string"==typeof e)),this.send("frame.init",this.options.init),void 0!==this.focused&&this.send("frame.focusChanged",{focused:this.focused}),void(null==(n=(i=this.options).onReady)||n.call(i))}if(this.ready)if(p.replyTo){const e=this.pending.get(p.replyTo);e&&p.type===e.type+"Result"&&(clearTimeout(e.timer),this.pending.delete(p.replyTo),e.resolve(p.payload))}else if("window.setTitle"===p.type&&"string"==typeof h.title&&(null==(r=(s=this.options).onTitle)||r.call(s,h.title.slice(0,256),!0===h.dirty)),"window.requestClose"===p.type&&(null==(l=(a=this.options).onRequestClose)||l.call(a)),"sysdlg.open"===p.type&&"string"==typeof p.id&&this.systemDialog(p.id,h.path,h.params),"content.open"===p.type&&("default"===h.target||"preview"===h.target||"chooser"===h.target)){const t={...h.request,requestId:crypto.randomUUID()};if(!e.isOpenRequest(t))return;if(this.opens=this.opens.filter((e=>e>Date.now()-1e4)),this.opens.length>=5)return;this.opens.push(Date.now()),null==(c=(d=this.options).onContentOpen)||c.call(d,t,h.target,{newWindow:!0===h.newWindow,hints:e.readContentHints(h.hints)})}}update(e){this.options.init={...this.options.init,...e}}setFocused(e){this.focused!==e&&(this.focused=e,this.send("frame.focusChanged",{focused:e}))}send(e,t){var o;this.ready&&(null==(o=this.options.target())||o.postMessage(i(e,t),this.options.origin))}request(e,t,o=3e3){if(!this.ready)return Promise.reject(new Error("App frame is not ready"));const n=crypto.randomUUID();return new Promise(((s,r)=>{var a;const l=setTimeout((()=>{this.pending.delete(n),r(new Error("App frame timed out"))}),o);this.pending.set(n,{resolve:s,reject:r,timer:l,type:e}),null==(a=this.options.target())||a.postMessage(i(e,t,{id:n}),this.options.origin)}))}async open(e){return this.capabilities.includes("open")?await this.request("frame.open",{request:e}):{accepted:!1}}async beforeClose(e="user"){if(!this.ready||!this.capabilities.includes("beforeClose"))return"allow";const t=await this.request("frame.beforeClose",{reason:e});return"allow"===t.decision||"pending"===t.decision?t.decision:"deny"}async back(){return!!this.capabilities.includes("back")&&!0===(await this.request("frame.back",{})).handled}dispose(){window.removeEventListener("message",this.listener),this.pending.forEach((e=>{clearTimeout(e.timer),e.reject(new Error("App frame disposed"))})),this.pending.clear(),this.ready=!1}},exports.PREVIEW_EMBED_PATH=a,exports.PreviewEmbed=class{constructor(e){this.options=e,this.nonce=crypto.randomUUID(),this.listener=e=>this.receive(e),this.ready=!1,this.origin=new URL(e.systemOrigin).origin,this.init=e.init,this.url=`${this.origin}${a}#bpe=${this.nonce}&po=${encodeURIComponent(window.location.origin)}`,window.addEventListener("message",this.listener)}post(e,t){var i,o;null==(o=null==(i=this.options.frame())?void 0:i.contentWindow)||o.postMessage(s(e,t),this.origin)}receive(t){var i,o,n,s,a,l,d;if(t.origin!==this.origin||t.source!==(null==(i=this.options.frame())?void 0:i.contentWindow)||!r(t.data))return;const{type:c,payload:p}=t.data;if("embed.hello"!==c){if("embed.state"===c&&("loading"===p.status||"ready"===p.status||"error"===p.status)){const e=p.error;null==(n=(o=this.options).onState)||n.call(o,{status:p.status,error:e&&"string"==typeof e.kind&&"string"==typeof e.code?{kind:e.kind,code:e.code}:void 0,title:"string"==typeof p.title?p.title.slice(0,256):void 0,mediaType:"string"==typeof p.mediaType?p.mediaType.slice(0,128):void 0})}if("embed.openWith"===c){const t=p.request;t&&e.isTransferableRef(t.source)&&(void 0===t.session||e.isTransferableSession(t.session))&&(null==(a=(s=this.options).onOpenWith)||a.call(s,{request:{source:t.source,session:t.session},hints:e.readContentHints(p.hints)}))}"embed.exit"===c&&(null==(d=(l=this.options).onExit)||d.call(l))}else p.nonce===this.nonce&&(this.ready=!0,this.post("embed.init",{...this.init,nonce:this.nonce}))}update(e){this.init={...this.init,...e},this.ready&&this.post("embed.update",e)}dispose(){window.removeEventListener("message",this.listener)}},exports.PreviewEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bpe");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const o=()=>window.parent.postMessage(s("embed.hello",{nonce:this.nonce}),this.parentOrigin);o(),this.hello=setInterval((()=>{this.ready||o()}),250)}receive(t){var i,o;if(t.source!==window.parent||t.origin!==this.parentOrigin||!r(t.data))return;const{type:n,payload:s}=t.data;if("embed.init"===n){if(s.nonce!==this.nonce||(a=s.source,!(e.isTransferableRef(a)||a&&"object"==typeof a&&"blob"===a.kind&&"undefined"!=typeof Blob&&a.blob instanceof Blob&&"string"==typeof a.name))||void 0!==s.session&&!e.isTransferableSession(s.session)||"string"!=typeof s.locale)return;return this.ready=!0,clearInterval(this.hello),void this.options.onInit({nonce:String(s.nonce),source:s.source,session:s.session,theme:"dark"===s.theme?"dark":"light",locale:s.locale})}var a;if("embed.update"===n&&this.ready){const e={};"dark"!==s.theme&&"light"!==s.theme||(e.theme=s.theme),"string"==typeof s.locale&&(e.locale=s.locale),null==(o=(i=this.options).onUpdate)||o.call(i,e)}}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(s(e,t),this.parentOrigin)}state(e){this.post("embed.state",e)}openWith(e){this.post("embed.openWith",e)}exit(){this.post("embed.exit",{})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.SELECT_EMBED_PATH=d,exports.SelectEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bse");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const o=()=>window.parent.postMessage(s("embed.hello",{nonce:this.nonce},l),this.parentOrigin);o(),this.hello=setInterval((()=>{this.ready||o()}),250)}receive(e){if(e.source!==window.parent||e.origin!==this.parentOrigin||!r(e.data,l))return;const{type:t,payload:i}=e.data;"embed.init"!==t||this.ready||i.nonce!==this.nonce||"string"!=typeof i.locale||(this.ready=!0,clearInterval(this.hello),this.options.onInit({nonce:String(i.nonce),params:i.params,theme:"dark"===i.theme?"dark":"light",locale:i.locale}))}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(s(e,t,l),this.parentOrigin)}result(e){this.post("embed.result",{result:e})}error(e){this.post("embed.error",{code:e})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.embedderOrigin=function(e){var t;if(window.parent===window)return null;const i=[null==(t=window.location.ancestorOrigins)?void 0:t[0],document.referrer];for(const o of i)if(o)try{const t=new URL(o).origin;if(e(t))return t}catch{}return null},exports.openSelectEmbed=p,exports.originInZone=(e,t)=>{try{const i=new URL(e);return i.protocol===window.location.protocol&&(i.hostname===t||i.hostname.endsWith(`.${t}`))}catch{return!1}};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./content.cjs");require("./content_mime-dc80d960.js");const t=t=>e.SYSTEM_DIALOG_ERROR_CODES.includes(t)?t:"protocol",i=(e,t,i={})=>({protocol:"buckyos.app-frame",version:1,type:e,payload:t,...i}),n=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"buckyos.app-frame"===t.protocol&&1===t.version&&"string"==typeof t.type&&!!t.payload&&"object"==typeof t.payload};const s="buckyos.preview-embed",o=(e,t,i=s)=>({protocol:i,version:1,type:e,payload:t}),r=(e,t=s)=>{const i=e;return!!i&&i.protocol===t&&1===i.version&&"string"==typeof i.type&&!!i.payload&&"object"==typeof i.payload},a="/embed/preview";const l="buckyos.sysdlg-embed",d="/embed/sysdlg/select";let c=!1;function h(i,n,s={}){var a,h;if(null==(a=s.signal)?void 0:a.aborted)return Promise.reject(new e.SystemDialogError("closed"));if(c)return Promise.reject(new e.SystemDialogError("busy"));c=!0;const p=new URL(i).origin,u=s.locale??navigator.language??"en",m=s.theme??((null==(h=window.matchMedia)?void 0:h.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"),g=u.toLowerCase().startsWith("zh");return new Promise(((i,a)=>{var h;const y=document.body,w=document.documentElement,f=document.activeElement instanceof HTMLElement?document.activeElement:null,b={x:window.scrollX,y:window.scrollY},v={body:y.getAttribute("style"),html:w.getAttribute("style")},E=Array.from(y.children).filter((e=>e instanceof HTMLElement)).map((e=>({el:e,inert:e.inert,hidden:e.getAttribute("aria-hidden")}))),x=document.createElement("div");let T;x.setAttribute("data-buckyos-sysdlg","select"),x.setAttribute("role","dialog"),x.setAttribute("aria-modal","true"),x.setAttribute("aria-label",g?"文件选择器":"File picker"),x.style.cssText="position:fixed;inset:0;height:100vh;height:100dvh;z-index:2147483647;background:rgba(0,0,0,.32);display:flex;align-items:center;justify-content:center";let L,O="",k=!1;const C=e=>{x.contains(e.target)||(e.stopPropagation(),e.preventDefault())},S=["keydown","pointerdown","mousedown","touchstart","wheel"],R=()=>{var e;return!k&&(k=!0,c=!1,clearTimeout(L),window.removeEventListener("message",M),null==(e=s.signal)||e.removeEventListener("abort",I),"inert"in HTMLElement.prototype||S.forEach((e=>document.removeEventListener(e,C,!0))),x.remove(),E.forEach((({el:e,inert:t,hidden:i})=>{e.inert=t,null===i?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",i)})),null===v.body?y.removeAttribute("style"):y.setAttribute("style",v.body),null===v.html?w.removeAttribute("style"):w.setAttribute("style",v.html),window.scrollTo(b.x,b.y),null==f||f.focus({preventScroll:!0}),!0)},A=t=>{R()&&a(new e.SystemDialogError(t))},I=()=>A("closed"),D=()=>{null==T||T.remove(),T=void 0;const e=document.createElement("div");e.setAttribute("role","alert"),e.style.cssText=`max-width:22rem;margin:1rem;padding:1.25rem;border-radius:16px;font:14px/1.6 system-ui,sans-serif;background:${"dark"===m?"#1f2329":"#fff"};color:${"dark"===m?"#f2f3f5":"#1f2329"};box-shadow:0 24px 64px rgba(0,0,0,.24)`;const t=document.createElement("p");t.style.margin="0 0 1rem",t.textContent=g?"无法加载文件选择器":"Unable to load the file picker";const i=document.createElement("div");i.style.cssText="display:flex;gap:.5rem;justify-content:flex-end";const n=(e,t)=>{const n=document.createElement("button");return n.type="button",n.textContent=e,n.style.cssText="min-height:2.25rem;padding:0 1rem;font:inherit;border-radius:999px;border:1px solid currentColor;background:transparent;color:inherit;cursor:pointer",n.addEventListener("click",t),i.append(n),n};n(g?"取消":"Cancel",(()=>A("load_failed")));const s=n(g?"重试":"Retry",(()=>{e.remove(),U()}));e.append(t,i),x.append(e),s.focus()},U=()=>{O=crypto.randomUUID(),T=document.createElement("iframe"),T.title=g?"文件选择器":"File picker",T.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;color-scheme:normal",T.setAttribute("allowtransparency","true"),T.addEventListener("error",D),T.src=`${p}${d}#bse=${O}&po=${encodeURIComponent(window.location.origin)}`,x.append(T),L=setTimeout(D,1e4)},M=s=>{var a;if(!T||s.origin!==p||s.source!==T.contentWindow||!r(s.data,l))return;const{type:d,payload:c}=s.data;if("embed.hello"===d){if(c.nonce!==O)return;clearTimeout(L),null==(a=T.contentWindow)||a.postMessage(o("embed.init",{nonce:O,params:n,theme:m,locale:u},l),p),T.focus()}if("embed.error"===d&&A(t(c.code)),"embed.result"===d){const t=e.readSelectDialogResult(c.result,{allowLocal:!0===n.allowLocal});t?(e=>{R()&&i(e)})(t):A("protocol")}};window.addEventListener("message",M),null==(h=s.signal)||h.addEventListener("abort",I,{once:!0}),"inert"in HTMLElement.prototype?E.forEach((({el:e})=>{e.inert=!0})):(E.forEach((({el:e})=>e.setAttribute("aria-hidden","true"))),S.forEach((e=>document.addEventListener(e,C,!0)))),w.style.overflow="hidden",y.style.position="fixed",y.style.top=-b.y+"px",y.style.left=-b.x+"px",y.style.right="0",y.style.overflow="hidden",y.append(x),U()}))}const p="buckyos.conversation-embed",u="/embed/conversation",m=["invalid_params","not_found","denied"],g=["idle","running","interrupted","paused","answer"];exports.AppFrameClient=class{constructor(e){if(this.options=e,this.listener=e=>{this.receive(e)},this.dialogs=new Map,this.origin=new URL(e.shellOrigin).origin,this.nonce=new URLSearchParams(window.location.hash.slice(1)).get("bfp"),window.addEventListener("message",this.listener),window.parent!==window&&this.nonce){const t=()=>window.parent.postMessage(i("frame.hello",{nonce:this.nonce,appCapabilities:[...e.onOpen?["open"]:[],...e.onBeforeClose?["beforeClose"]:[],...e.onBack?["back"]:[]]}),this.origin);t(),this.helloTimer=setInterval(t,250),this.helloDeadline=setTimeout((()=>clearInterval(this.helloTimer)),1500)}}async receive(s){var o,r,a,l,d,c,h,p,u,m,g,y,w,f;if(s.source!==window.parent||s.origin!==this.origin||!n(s.data))return;const b=s.data,v=b.payload;if("frame.init"===b.type){if(!this.nonce||v.nonce!==this.nonce||"string"!=typeof v.locale||!v.theme||"string"!=typeof v.windowId||v.launch&&!e.isOpenRequest(v.launch))return;return clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),this.init=v,this.title=void 0,this.focused=void 0,void(null==(r=(o=this.options).onInit)||r.call(o,this.init))}if(!this.init)return;if("sysdlg.openResult"===b.type){const i=b.replyTo?this.dialogs.get(b.replyTo):void 0;if(!i)return;if(this.dialogs.delete(b.replyTo),!0!==v.ok)return i.reject(new e.SystemDialogError(t(v.code)));const n=e.readSelectDialogResult(v.result,{allowLocal:i.allowLocal});return void(n?i.resolve(n):i.reject(new e.SystemDialogError("protocol")))}const E=e=>window.parent.postMessage(i(b.type+"Result",e,{replyTo:b.id}),this.origin);try{"frame.open"===b.type&&e.isOpenRequest(v.request)&&E(await(null==(l=(a=this.options).onOpen)?void 0:l.call(a,v.request))??{accepted:!1}),"frame.beforeClose"===b.type&&E({decision:await(null==(c=(d=this.options).onBeforeClose)?void 0:c.call(d,v.reason))??"allow"}),"frame.back"===b.type&&E({handled:await(null==(p=(h=this.options).onBack)?void 0:p.call(h))??!1}),"frame.themeChanged"!==b.type||"dark"!==v.mode&&"light"!==v.mode||null==(m=(u=this.options).onTheme)||m.call(u,v),"frame.localeChanged"===b.type&&"string"==typeof v.locale&&(null==(y=(g=this.options).onLocale)||y.call(g,v.locale)),"frame.focusChanged"===b.type&&this.focused!==(!0===v.focused)&&(this.focused=!0===v.focused,null==(f=(w=this.options).onFocus)||f.call(w,this.focused))}catch{"frame.open"===b.type&&E({accepted:!1,fallback:"preview"}),"frame.beforeClose"===b.type&&E({decision:"deny"})}}send(e,t){this.init&&window.parent.postMessage(i(e,t),this.origin)}setTitle(e,t=!1){const i=JSON.stringify([e,t]);this.init&&i!==this.title&&(this.title=i,this.send("window.setTitle",{title:e,dirty:t}))}requestClose(){this.send("window.requestClose",{})}openContent(t,i="default",n={}){const s=n.hints??{};return this.init?(this.send("content.open",{request:t,target:i,newWindow:!0===n.newWindow,hints:s}),!0):!!this.options.systemOrigin&&(window.open(e.systemOpenUrl(this.options.systemOrigin,{request:t,target:i,hints:s,from:this.options.appId}),"_blank","noopener"),!0)}selectContent(t={},n={}){var s,o;if(this.init){if(!this.init.shellCapabilities.includes(e.SELECT_DIALOG_PATH))return Promise.reject(new e.SystemDialogError("unsupported"));if(this.dialogs.size)return Promise.reject(new e.SystemDialogError("busy"));const n=crypto.randomUUID();return new Promise(((s,o)=>{this.dialogs.set(n,{resolve:s,reject:o,allowLocal:!0===t.allowLocal}),window.parent.postMessage(i("sysdlg.open",{path:e.SELECT_DIALOG_PATH,params:t},{id:n}),this.origin)}))}if(!this.options.systemOrigin)return Promise.reject(new e.SystemDialogError("unsupported"));const r=this.embedAbort=new AbortController;return null==(s=n.signal)||s.addEventListener("abort",(()=>r.abort()),{once:!0}),(null==(o=n.signal)?void 0:o.aborted)&&r.abort(),h(this.options.systemOrigin,t,{...n,signal:r.signal})}dispose(){var t;clearInterval(this.helloTimer),clearTimeout(this.helloDeadline),window.removeEventListener("message",this.listener),this.dialogs.forEach((t=>t.reject(new e.SystemDialogError("closed")))),this.dialogs.clear(),null==(t=this.embedAbort)||t.abort()}},exports.AppFrameHost=class{constructor(e){this.options=e,this.ready=!1,this.capabilities=[],this.pending=new Map,this.listener=e=>this.receive(e),this.opens=[],this.dialogOpen=!1,window.addEventListener("message",this.listener)}async systemDialog(t,n,s){const o=e=>{var n;this.ready&&(null==(n=this.options.target())||n.postMessage(i("sysdlg.openResult",e,{replyTo:t}),this.options.origin))};if(!this.options.onSystemDialog||"string"!=typeof n)return o({ok:!1,code:"unsupported"});if(this.dialogOpen)return o({ok:!1,code:"busy"});this.dialogOpen=!0;try{o(await this.options.onSystemDialog(n,s))}catch(r){o({ok:!1,code:r instanceof e.SystemDialogError?r.code:"closed"})}finally{this.dialogOpen=!1}}receive(t){var i,s,o,r,a,l,d,c;if(t.source!==this.options.target()||t.origin!==this.options.origin||!n(t.data))return;const h=t.data,p=h.payload;if("frame.hello"===h.type){if(p.nonce!==this.options.init.nonce||!Array.isArray(p.appCapabilities))return;return this.ready=!0,this.capabilities=p.appCapabilities.filter((e=>"string"==typeof e)),this.send("frame.init",this.options.init),void 0!==this.focused&&this.send("frame.focusChanged",{focused:this.focused}),void(null==(s=(i=this.options).onReady)||s.call(i))}if(this.ready)if(h.replyTo){const e=this.pending.get(h.replyTo);e&&h.type===e.type+"Result"&&(clearTimeout(e.timer),this.pending.delete(h.replyTo),e.resolve(h.payload))}else if("window.setTitle"===h.type&&"string"==typeof p.title&&(null==(r=(o=this.options).onTitle)||r.call(o,p.title.slice(0,256),!0===p.dirty)),"window.requestClose"===h.type&&(null==(l=(a=this.options).onRequestClose)||l.call(a)),"sysdlg.open"===h.type&&"string"==typeof h.id&&this.systemDialog(h.id,p.path,p.params),"content.open"===h.type&&("default"===p.target||"preview"===p.target||"chooser"===p.target)){const t={...p.request,requestId:crypto.randomUUID()};if(!e.isOpenRequest(t))return;if(this.opens=this.opens.filter((e=>e>Date.now()-1e4)),this.opens.length>=5)return;this.opens.push(Date.now()),null==(c=(d=this.options).onContentOpen)||c.call(d,t,p.target,{newWindow:!0===p.newWindow,hints:e.readContentHints(p.hints)})}}update(e){this.options.init={...this.options.init,...e}}setFocused(e){this.focused!==e&&(this.focused=e,this.send("frame.focusChanged",{focused:e}))}send(e,t){var n;this.ready&&(null==(n=this.options.target())||n.postMessage(i(e,t),this.options.origin))}request(e,t,n=3e3){if(!this.ready)return Promise.reject(new Error("App frame is not ready"));const s=crypto.randomUUID();return new Promise(((o,r)=>{var a;const l=setTimeout((()=>{this.pending.delete(s),r(new Error("App frame timed out"))}),n);this.pending.set(s,{resolve:o,reject:r,timer:l,type:e}),null==(a=this.options.target())||a.postMessage(i(e,t,{id:s}),this.options.origin)}))}async open(e){return this.capabilities.includes("open")?await this.request("frame.open",{request:e}):{accepted:!1}}async beforeClose(e="user"){if(!this.ready||!this.capabilities.includes("beforeClose"))return"allow";const t=await this.request("frame.beforeClose",{reason:e});return"allow"===t.decision||"pending"===t.decision?t.decision:"deny"}async back(){return!!this.capabilities.includes("back")&&!0===(await this.request("frame.back",{})).handled}dispose(){window.removeEventListener("message",this.listener),this.pending.forEach((e=>{clearTimeout(e.timer),e.reject(new Error("App frame disposed"))})),this.pending.clear(),this.ready=!1}},exports.CONVERSATION_EMBED_ERROR_CODES=m,exports.CONVERSATION_EMBED_PATH=u,exports.ConversationEmbed=class{constructor(e){this.options=e,this.nonce=crypto.randomUUID(),this.listener=e=>this.receive(e),this.ready=!1,this.outbox=[],this.origin=new URL(e.systemOrigin).origin,this.init=e.init,this.url=`${this.origin}${u}#bce=${this.nonce}&po=${encodeURIComponent(window.location.origin)}`,window.addEventListener("message",this.listener)}post(e,t){var i,n;null==(n=null==(i=this.options.frame())?void 0:i.contentWindow)||n.postMessage(o(e,t,p),this.origin)}receive(e){var t,i,n,s,o,a,l;if(e.origin!==this.origin||e.source!==(null==(t=this.options.frame())?void 0:t.contentWindow)||!r(e.data,p))return;const{type:d,payload:c}=e.data;if("embed.hello"===d){if(c.nonce!==this.nonce)return;this.ready=!0,this.post("embed.init",{...this.init,nonce:this.nonce});const e=this.outbox;return this.outbox=[],void e.forEach((e=>this.post("embed.send",e)))}"embed.state"!==d||"loading"!==c.status&&"ready"!==c.status&&"error"!==c.status||null==(n=(i=this.options).onState)||n.call(i,{status:c.status,sessionId:"string"==typeof c.sessionId?c.sessionId.slice(0,512):void 0,error:"string"==typeof c.error?c.error.slice(0,128):void 0}),"embed.turn"===d&&g.includes(c.mode)&&(null==(o=(s=this.options).onTurn)||o.call(s,c.mode)),"embed.error"===d&&m.includes(c.code)&&(null==(l=(a=this.options).onError)||l.call(a,c.code))}update(e){this.init={...this.init,...e},this.ready&&this.post("embed.update",e)}send(e){var t;const i={text:e.text,...(null==(t=e.attachments)?void 0:t.length)?{attachments:e.attachments}:{}};this.ready?this.post("embed.send",i):this.outbox.push(i)}dispose(){window.removeEventListener("message",this.listener),this.outbox=[]}},exports.ConversationEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bce");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const n=()=>window.parent.postMessage(o("embed.hello",{nonce:this.nonce},p),this.parentOrigin);n(),this.hello=setInterval((()=>{this.ready||n()}),250)}receive(t){var i,n,s,o;if(t.source!==window.parent||t.origin!==this.parentOrigin||!r(t.data,p))return;const{type:a,payload:l}=t.data;if("embed.init"===a){if(this.ready||l.nonce!==this.nonce||"string"!=typeof l.locale)return;return this.ready=!0,clearInterval(this.hello),void this.options.onInit({nonce:String(l.nonce),target:l.target,theme:"dark"===l.theme?"dark":"light",locale:l.locale,..."string"==typeof l.placeholder?{placeholder:l.placeholder.slice(0,200)}:{}})}if(this.ready){if("embed.update"===a){const e={};"dark"!==l.theme&&"light"!==l.theme||(e.theme=l.theme),"string"==typeof l.locale&&(e.locale=l.locale),null==(n=(i=this.options).onUpdate)||n.call(i,e)}if("embed.send"===a){const t=(t=>"string"!=typeof t.text||t.text.length>65536?null:void 0===t.attachments?{text:t.text}:!Array.isArray(t.attachments)||t.attachments.length>32||!t.attachments.every(e.isTransferableRef)?null:{text:t.text,attachments:t.attachments})(l);t?null==(o=(s=this.options).onSend)||o.call(s,t):this.error("invalid_params")}}}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(o(e,t,p),this.parentOrigin)}state(e){this.post("embed.state",e)}turn(e){this.post("embed.turn",{mode:e})}error(e){this.post("embed.error",{code:e})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.PREVIEW_EMBED_PATH=a,exports.PreviewEmbed=class{constructor(e){this.options=e,this.nonce=crypto.randomUUID(),this.listener=e=>this.receive(e),this.ready=!1,this.origin=new URL(e.systemOrigin).origin,this.init=e.init,this.url=`${this.origin}${a}#bpe=${this.nonce}&po=${encodeURIComponent(window.location.origin)}`,window.addEventListener("message",this.listener)}post(e,t){var i,n;null==(n=null==(i=this.options.frame())?void 0:i.contentWindow)||n.postMessage(o(e,t),this.origin)}receive(t){var i,n,s,o,a,l,d;if(t.origin!==this.origin||t.source!==(null==(i=this.options.frame())?void 0:i.contentWindow)||!r(t.data))return;const{type:c,payload:h}=t.data;if("embed.hello"!==c){if("embed.state"===c&&("loading"===h.status||"ready"===h.status||"error"===h.status)){const e=h.error;null==(s=(n=this.options).onState)||s.call(n,{status:h.status,error:e&&"string"==typeof e.kind&&"string"==typeof e.code?{kind:e.kind,code:e.code}:void 0,title:"string"==typeof h.title?h.title.slice(0,256):void 0,mediaType:"string"==typeof h.mediaType?h.mediaType.slice(0,128):void 0})}if("embed.openWith"===c){const t=h.request;t&&e.isTransferableRef(t.source)&&(void 0===t.session||e.isTransferableSession(t.session))&&(null==(a=(o=this.options).onOpenWith)||a.call(o,{request:{source:t.source,session:t.session},hints:e.readContentHints(h.hints)}))}"embed.exit"===c&&(null==(d=(l=this.options).onExit)||d.call(l))}else h.nonce===this.nonce&&(this.ready=!0,this.post("embed.init",{...this.init,nonce:this.nonce}))}update(e){this.init={...this.init,...e},this.ready&&this.post("embed.update",e)}dispose(){window.removeEventListener("message",this.listener)}},exports.PreviewEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bpe");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const n=()=>window.parent.postMessage(o("embed.hello",{nonce:this.nonce}),this.parentOrigin);n(),this.hello=setInterval((()=>{this.ready||n()}),250)}receive(t){var i,n;if(t.source!==window.parent||t.origin!==this.parentOrigin||!r(t.data))return;const{type:s,payload:o}=t.data;if("embed.init"===s){if(o.nonce!==this.nonce||(a=o.source,!(e.isTransferableRef(a)||a&&"object"==typeof a&&"blob"===a.kind&&"undefined"!=typeof Blob&&a.blob instanceof Blob&&"string"==typeof a.name))||void 0!==o.session&&!e.isTransferableSession(o.session)||"string"!=typeof o.locale)return;return this.ready=!0,clearInterval(this.hello),void this.options.onInit({nonce:String(o.nonce),source:o.source,session:o.session,theme:"dark"===o.theme?"dark":"light",locale:o.locale})}var a;if("embed.update"===s&&this.ready){const e={};"dark"!==o.theme&&"light"!==o.theme||(e.theme=o.theme),"string"==typeof o.locale&&(e.locale=o.locale),null==(n=(i=this.options).onUpdate)||n.call(i,e)}}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(o(e,t),this.parentOrigin)}state(e){this.post("embed.state",e)}openWith(e){this.post("embed.openWith",e)}exit(){this.post("embed.exit",{})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.SELECT_EMBED_PATH=d,exports.SelectEmbedHost=class{constructor(e){this.options=e,this.ready=!1,this.listener=e=>this.receive(e);const t=new URLSearchParams(window.location.hash.slice(1));this.nonce=t.get("bse");let i=null;try{i=new URL(t.get("po")??"").origin}catch{}if(this.parentOrigin=window.parent!==window&&this.nonce&&i&&e.accept(i)?i:null,!this.parentOrigin)return;window.addEventListener("message",this.listener);const n=()=>window.parent.postMessage(o("embed.hello",{nonce:this.nonce},l),this.parentOrigin);n(),this.hello=setInterval((()=>{this.ready||n()}),250)}receive(e){if(e.source!==window.parent||e.origin!==this.parentOrigin||!r(e.data,l))return;const{type:t,payload:i}=e.data;"embed.init"!==t||this.ready||i.nonce!==this.nonce||"string"!=typeof i.locale||(this.ready=!0,clearInterval(this.hello),this.options.onInit({nonce:String(i.nonce),params:i.params,theme:"dark"===i.theme?"dark":"light",locale:i.locale}))}post(e,t){this.ready&&this.parentOrigin&&window.parent.postMessage(o(e,t,l),this.parentOrigin)}result(e){this.post("embed.result",{result:e})}error(e){this.post("embed.error",{code:e})}dispose(){clearInterval(this.hello),window.removeEventListener("message",this.listener)}},exports.embedderOrigin=function(e){var t;if(window.parent===window)return null;const i=[null==(t=window.location.ancestorOrigins)?void 0:t[0],document.referrer];for(const n of i)if(n)try{const t=new URL(n).origin;if(e(t))return t}catch{}return null},exports.openSelectEmbed=h,exports.originInZone=(e,t)=>{try{const i=new URL(e);return i.protocol===window.location.protocol&&(i.hostname===t||i.hostname.endsWith(`.${t}`))}catch{return!1}};
2
2
  //# sourceMappingURL=app-frame.cjs.map