@immediately-run/sdk 0.43.1 → 0.45.0

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.
Files changed (157) hide show
  1. package/dist/ambient.d.ts +47 -0
  2. package/dist/auth.cjs +3 -2
  3. package/dist/auth.cjs.map +1 -1
  4. package/dist/auth.js +3 -2
  5. package/dist/auth.js.map +1 -1
  6. package/dist/boot.cjs +3 -2
  7. package/dist/boot.cjs.map +1 -1
  8. package/dist/boot.js +3 -2
  9. package/dist/boot.js.map +1 -1
  10. package/dist/catalog.cjs +3 -2
  11. package/dist/catalog.cjs.map +1 -1
  12. package/dist/catalog.js +3 -2
  13. package/dist/catalog.js.map +1 -1
  14. package/dist/components/MDXComponents.cjs +14 -1
  15. package/dist/components/MDXComponents.cjs.map +1 -1
  16. package/dist/components/MDXComponents.js +14 -1
  17. package/dist/components/MDXComponents.js.map +1 -1
  18. package/dist/components/WikiLink.cjs +19 -17
  19. package/dist/components/WikiLink.cjs.map +1 -1
  20. package/dist/components/WikiLink.js +19 -17
  21. package/dist/components/WikiLink.js.map +1 -1
  22. package/dist/contribute.cjs +2 -1
  23. package/dist/contribute.cjs.map +1 -1
  24. package/dist/contribute.js +2 -1
  25. package/dist/contribute.js.map +1 -1
  26. package/dist/debug.cjs +6 -5
  27. package/dist/debug.cjs.map +1 -1
  28. package/dist/debug.js +12 -5
  29. package/dist/debug.js.map +1 -1
  30. package/dist/diagnostics.cjs +3 -2
  31. package/dist/diagnostics.cjs.map +1 -1
  32. package/dist/diagnostics.js +3 -2
  33. package/dist/diagnostics.js.map +1 -1
  34. package/dist/dnd.cjs +5 -3
  35. package/dist/dnd.cjs.map +1 -1
  36. package/dist/dnd.js +5 -3
  37. package/dist/dnd.js.map +1 -1
  38. package/dist/editor.cjs +3 -1
  39. package/dist/editor.cjs.map +1 -1
  40. package/dist/editor.js +3 -1
  41. package/dist/editor.js.map +1 -1
  42. package/dist/editorContext.cjs +3 -2
  43. package/dist/editorContext.cjs.map +1 -1
  44. package/dist/editorContext.js +3 -2
  45. package/dist/editorContext.js.map +1 -1
  46. package/dist/formFactor.cjs +3 -2
  47. package/dist/formFactor.cjs.map +1 -1
  48. package/dist/formFactor.js +3 -2
  49. package/dist/formFactor.js.map +1 -1
  50. package/dist/generated/protocol.cjs +23 -0
  51. package/dist/generated/protocol.cjs.map +1 -0
  52. package/dist/generated/protocol.d.cts +1 -0
  53. package/dist/generated/protocol.d.ts +1 -0
  54. package/dist/generated/protocol.js +2 -0
  55. package/dist/generated/protocol.js.map +1 -0
  56. package/dist/hooks.cjs +22 -14
  57. package/dist/hooks.cjs.map +1 -1
  58. package/dist/hooks.d.cts +26 -4
  59. package/dist/hooks.d.ts +26 -4
  60. package/dist/hooks.js +23 -15
  61. package/dist/hooks.js.map +1 -1
  62. package/dist/index.cjs +4 -0
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +3 -1
  65. package/dist/index.d.ts +3 -1
  66. package/dist/index.js +2 -0
  67. package/dist/index.js.map +1 -1
  68. package/dist/ipc.cjs +5 -3
  69. package/dist/ipc.cjs.map +1 -1
  70. package/dist/ipc.js +5 -3
  71. package/dist/ipc.js.map +1 -1
  72. package/dist/launch.cjs +5 -3
  73. package/dist/launch.cjs.map +1 -1
  74. package/dist/launch.js +5 -3
  75. package/dist/launch.js.map +1 -1
  76. package/dist/linkSpace.cjs +63 -0
  77. package/dist/linkSpace.cjs.map +1 -0
  78. package/dist/linkSpace.d.cts +44 -0
  79. package/dist/linkSpace.d.ts +44 -0
  80. package/dist/linkSpace.js +37 -0
  81. package/dist/linkSpace.js.map +1 -0
  82. package/dist/llm.cjs +3 -2
  83. package/dist/llm.cjs.map +1 -1
  84. package/dist/llm.js +3 -2
  85. package/dist/llm.js.map +1 -1
  86. package/dist/metadataSource.cjs +53 -0
  87. package/dist/metadataSource.cjs.map +1 -0
  88. package/dist/metadataSource.d.cts +51 -0
  89. package/dist/metadataSource.d.ts +51 -0
  90. package/dist/metadataSource.js +29 -0
  91. package/dist/metadataSource.js.map +1 -0
  92. package/dist/moduleCache.cjs +2 -1
  93. package/dist/moduleCache.cjs.map +1 -1
  94. package/dist/moduleCache.js +2 -1
  95. package/dist/moduleCache.js.map +1 -1
  96. package/dist/mounts.cjs +13 -10
  97. package/dist/mounts.cjs.map +1 -1
  98. package/dist/mounts.js +23 -10
  99. package/dist/mounts.js.map +1 -1
  100. package/dist/netFetch.cjs +4 -2
  101. package/dist/netFetch.cjs.map +1 -1
  102. package/dist/netFetch.js +4 -2
  103. package/dist/netFetch.js.map +1 -1
  104. package/dist/onFsChange.cjs +2 -1
  105. package/dist/onFsChange.cjs.map +1 -1
  106. package/dist/onFsChange.js +2 -1
  107. package/dist/onFsChange.js.map +1 -1
  108. package/dist/protocolSchemes.cjs +46 -0
  109. package/dist/protocolSchemes.cjs.map +1 -0
  110. package/dist/protocolSchemes.d.cts +18 -0
  111. package/dist/protocolSchemes.d.ts +18 -0
  112. package/dist/protocolSchemes.js +37 -0
  113. package/dist/protocolSchemes.js.map +1 -0
  114. package/dist/routing.cjs +2 -1
  115. package/dist/routing.cjs.map +1 -1
  116. package/dist/routing.js +2 -1
  117. package/dist/routing.js.map +1 -1
  118. package/dist/runtime.cjs +4 -2
  119. package/dist/runtime.cjs.map +1 -1
  120. package/dist/runtime.js +4 -2
  121. package/dist/runtime.js.map +1 -1
  122. package/dist/safeContent/renderMdast.cjs +2 -0
  123. package/dist/safeContent/renderMdast.cjs.map +1 -1
  124. package/dist/safeContent/renderMdast.js +2 -0
  125. package/dist/safeContent/renderMdast.js.map +1 -1
  126. package/dist/sandboxTypes.cjs.map +1 -1
  127. package/dist/sandboxTypes.d.cts +40 -6
  128. package/dist/sandboxTypes.d.ts +40 -6
  129. package/dist/secrets.cjs +5 -3
  130. package/dist/secrets.cjs.map +1 -1
  131. package/dist/secrets.js +5 -3
  132. package/dist/secrets.js.map +1 -1
  133. package/dist/tasks.cjs +6 -4
  134. package/dist/tasks.cjs.map +1 -1
  135. package/dist/tasks.js +6 -4
  136. package/dist/tasks.js.map +1 -1
  137. package/dist/theme.cjs +5 -3
  138. package/dist/theme.cjs.map +1 -1
  139. package/dist/theme.js +5 -3
  140. package/dist/theme.js.map +1 -1
  141. package/dist/urlUtils.cjs +3 -4
  142. package/dist/urlUtils.cjs.map +1 -1
  143. package/dist/urlUtils.d.cts +3 -10
  144. package/dist/urlUtils.d.ts +3 -10
  145. package/dist/urlUtils.js +1 -2
  146. package/dist/urlUtils.js.map +1 -1
  147. package/dist/vcs.cjs +5 -3
  148. package/dist/vcs.cjs.map +1 -1
  149. package/dist/vcs.js +5 -3
  150. package/dist/vcs.js.map +1 -1
  151. package/dist/version.cjs +1 -1
  152. package/dist/version.cjs.map +1 -1
  153. package/dist/version.d.cts +1 -1
  154. package/dist/version.d.ts +1 -1
  155. package/dist/version.js +1 -1
  156. package/dist/version.js.map +1 -1
  157. package/package.json +11 -4
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/WikiLink.tsx"],"sourcesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\nimport { splitHash } from '../urlUtils';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/** Collapse `.`/`..`/empty segments into a clean absolute path. */\nconst normalize = (path: string): string => {\n const out: string[] = [];\n for (const seg of path.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') out.pop();\n else out.push(seg);\n }\n return '/' + out.join('/');\n};\n\n/**\n * Resolve a wiki-link target to an absolute sandbox path, or `undefined` when it\n * cannot be resolved (a relative target with no known current file). An\n * **absolute** target (`/…`) is taken verbatim; a **relative** target resolves\n * against the current file's directory. Pure path arithmetic (MARKDOWN_SYNTAX_SPEC\n * §13.2) — it never touches the filesystem or any other file.\n */\nconst resolveWikiTarget = (target: string, currentFile?: string): string | undefined => {\n if (target.startsWith('/')) return normalize(target);\n if (!currentFile) return undefined;\n const dir = currentFile.slice(0, currentFile.lastIndexOf('/'));\n return normalize(`${dir}/${target}`);\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the\n * fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on\n * the **fragment-stripped path**, so a section citation to an existing file resolves\n * (not \"broken\"). The fragment then rides to navigation, where the scroll-after-nav\n * effect ({@link useScrollAfterNavigation}) lands the reader on the section.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):\n * - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is\n * the current file: a same-page {@link Link} that scrolls in place, no route change.\n * - **self** — the resolved path is the current file (no fragment): inert text, no link.\n * - **broken** — no file at the resolved path (and the store has loaded): rendered\n * as marked text, **not** a throw.\n * - **resolved** — routed through {@link Link} (in-app navigation for a same-app\n * href, a plain `<a>` otherwise), carrying any `#fragment`.\n *\n * The check is **optimistic until the metadata store loads** (an empty store never\n * flashes \"broken\"), and a relative target with no ambient render context (MDX\n * rendered outside `<Include>`) routes optimistically. Such an app overrides this\n * component (§11) for precise resolution.\n */\nexport const WikiLink = ({\n target,\n label,\n children,\n ...rest\n}: {\n target?: string;\n label?: ReactNode;\n children?: ReactNode;\n} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): ReactNode => {\n const { filesMetadata } = use(TinkerableContext);\n const renderContext = use(RenderExportedComponentContext);\n const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;\n\n const rawTarget = target ?? '';\n const [pathPart, frag] = splitHash(rawTarget);\n const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : '');\n\n // Defensive: the kernel never emits an empty target, but a hand-written\n // `<WikiLink>` might. Render inert text rather than a link to nowhere.\n if (!rawTarget) {\n return (\n <span className=\"ir-wikilink\" {...rest}>\n {text}\n </span>\n );\n }\n\n // Same-page anchor: a fragment with no path (`[[#sec-8-9]]`). Scroll within the\n // current file — no route change (§13.5). <Link> intercepts a bare `#`-href.\n if (pathPart === '' && frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n\n const resolved = resolveWikiTarget(pathPart, currentFile);\n const files = filesMetadata ?? {};\n const loaded = Object.keys(files).length > 0;\n\n // `resolved === undefined` ⇒ a relative target with no known current file: route\n // it optimistically (can't check existence or self-ness generically).\n if (resolved !== undefined) {\n if (currentFile && resolved === currentFile) {\n // The target IS this file. With a fragment it is a same-page anchor to another\n // of this file's sections; without one it is an inert self-reference.\n if (frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n return (\n <span className=\"ir-wikilink ir-wikilink-self\" data-state=\"self\" {...rest}>\n {text}\n </span>\n );\n }\n // Existence is checked on the FRAGMENT-STRIPPED path (optimistic until loaded).\n const exists = !loaded || resolved in files;\n if (!exists) {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`No file at ${resolved}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n }\n // Resolved cross-file target: route through <Link>, carrying the raw target so its\n // `#fragment` rides through navigation to the scroll-after-nav effect (§13.5).\n return (\n <Link href={rawTarget} className=\"ir-wikilink\" data-state=\"resolved\" {...rest}>\n {text}\n </Link>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoGM;AApGN,mBAA+B;AAC/B,kBAAqB;AACrB,qBAA+C;AAC/C,+BAAkC;AAClC,sBAA0B;AAG1B,MAAM,kBAAkB,CAAC,WAA2B;AAClD,QAAM,OAAO,OAAO,MAAM,OAAO,EAAE,IAAI,KAAK;AAC5C,SAAO,KAAK,QAAQ,YAAY,EAAE,KAAK;AACzC;AAGA,MAAM,YAAY,CAAC,SAAyB;AAC1C,QAAM,MAAgB,CAAC;AACvB,aAAW,OAAO,KAAK,MAAM,GAAG,GAAG;AACjC,QAAI,QAAQ,MAAM,QAAQ,IAAK;AAC/B,QAAI,QAAQ,KAAM,KAAI,IAAI;AAAA,QACrB,KAAI,KAAK,GAAG;AAAA,EACnB;AACA,SAAO,MAAM,IAAI,KAAK,GAAG;AAC3B;AASA,MAAM,oBAAoB,CAAC,QAAgB,gBAA6C;AACtF,MAAI,OAAO,WAAW,GAAG,EAAG,QAAO,UAAU,MAAM;AACnD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,MAAM,YAAY,MAAM,GAAG,YAAY,YAAY,GAAG,CAAC;AAC7D,SAAO,UAAU,GAAG,GAAG,IAAI,MAAM,EAAE;AACrC;AA2CO,MAAM,WAAW,CAAC;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,MAI+E;AAC7E,QAAM,EAA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cesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\nimport { splitHash } from '../urlUtils';\nimport { FS_PREFIX, LinkSpaceContext, resolveLinkTarget } from '../linkSpace';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the\n * fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on\n * the **fragment-stripped path**, so a section citation to an existing file resolves\n * (not \"broken\"). The fragment then rides to navigation, where the scroll-after-nav\n * effect ({@link useScrollAfterNavigation}) lands the reader on the section.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):\n * - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is\n * the current file: a same-page {@link Link} that scrolls in place, no route change.\n * - **self** — the resolved path is the current file (no fragment): inert text, no link.\n * - **broken** — no file at the resolved path (and the store has loaded): rendered\n * as marked text, **not** a throw.\n * - **resolved** — routed through {@link Link} (in-app navigation for a same-app\n * href, a plain `<a>` otherwise), carrying any `#fragment`.\n *\n * The check is **optimistic until the metadata store loads** (an empty store never\n * flashes \"broken\"), and a relative target with no ambient render context (MDX\n * rendered outside `<Include>`) routes optimistically. Such an app overrides this\n * component (§11) for precise resolution.\n */\nexport const WikiLink = ({\n target,\n label,\n children,\n ...rest\n}: {\n target?: string;\n label?: ReactNode;\n children?: ReactNode;\n} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): ReactNode => {\n const { filesMetadata } = use(TinkerableContext);\n const { corpusRoot } = use(LinkSpaceContext);\n const renderContext = use(RenderExportedComponentContext);\n const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;\n\n const rawTarget = target ?? '';\n const [pathPart, frag] = splitHash(rawTarget);\n const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : '');\n\n // Defensive: the kernel never emits an empty target, but a hand-written\n // `<WikiLink>` might. Render inert text rather than a link to nowhere.\n if (!rawTarget) {\n return (\n <span className=\"ir-wikilink\" {...rest}>\n {text}\n </span>\n );\n }\n\n // Same-page anchor: a fragment with no path (`[[#sec-8-9]]`). Scroll within the\n // current file — no route change (§13.5). <Link> intercepts a bare `#`-href.\n if (pathPart === '' && frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n\n // R3-273 link spaces: resolution is the SHARED resolver (`linkSpace.ts`) —\n // default space (corpus-rooted absolute targets when an enclosing provider\n // declares a corpusRoot; fs-rooted otherwise) or the explicit `$fs:` prefix.\n // A malformed `$fs:` target renders BROKEN, never an anchor.\n const resolution = resolveLinkTarget(pathPart, { currentFile, corpusRoot });\n if (resolution.state === 'invalid') {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`Invalid ${FS_PREFIX} target: ${pathPart}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n const resolved = resolution.state === 'resolved' ? resolution.path : undefined;\n const files = filesMetadata ?? {};\n const loaded = Object.keys(files).length > 0;\n\n // `resolved === undefined` ⇒ a relative target with no known current file: route\n // it optimistically (can't check existence or self-ness generically).\n if (resolved !== undefined) {\n if (currentFile && resolved === currentFile) {\n // The target IS this file. With a fragment it is a same-page anchor to another\n // of this file's sections; without one it is an inert self-reference.\n if (frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n return (\n <span className=\"ir-wikilink ir-wikilink-self\" data-state=\"self\" {...rest}>\n {text}\n </span>\n );\n }\n // Existence is checked on the FRAGMENT-STRIPPED path (optimistic until loaded).\n const exists = !loaded || resolved in files;\n if (!exists) {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`No file at ${resolved}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n }\n // Resolved cross-file target: route through <Link>. A space-translated target\n // (`$fs:` prefix, or a corpus-rooted absolute) navigates to the RESOLVED path —\n // the raw text is not a routable path in those shapes; everything else carries\n // the raw target bit-for-bit so its `#fragment` rides through navigation to the\n // scroll-after-nav effect (§13.5). The fragment is re-attached either way.\n const translated =\n pathPart.startsWith(FS_PREFIX) || (corpusRoot !== null && pathPart.startsWith('/'));\n const href =\n translated && resolved !== undefined ? `${resolved}${frag ? `#${frag}` : ''}` : rawTarget;\n return (\n <Link href={href} className=\"ir-wikilink\" data-state=\"resolved\" {...rest}>\n {text}\n </Link>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA6EM;AA7EN,mBAA+B;AAC/B,kBAAqB;AACrB,qBAA+C;AAC/C,+BAAkC;AAClC,sBA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Aa,aAAa;AAG3C,UAAI,MAAM;AACR,eACE,4CAAC,oBAAK,MAAM,IAAI,IAAI,IAAI,WAAU,eAAc,cAAW,UAAU,GAAG,MACrE,gBACH;AAAA,MAEJ;AACA,aACE,4CAAC,UAAK,WAAU,gCAA+B,cAAW,QAAQ,GAAG,MAClE,gBACH;AAAA,IAEJ;AAEA,UAAM,SAAS,CAAC,UAAU,YAAY;AACtC,QAAI,CAAC,QAAQ;AACX,aACE;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,OAAO,cAAc,QAAQ;AAAA,UAC5B,GAAG;AAAA,UAEH;AAAA;AAAA,MACH;AAAA,IAEJ;AAAA,EACF;AAMA,QAAM,aACJ,SAAS,WAAW,0BAAS,KAAM,eAAe,QAAQ,SAAS,WAAW,GAAG;AACnF,QAAM,OACJ,cAAc,aAAa,SAAY,GAAG,QAAQ,GAAG,OAAO,IAAI,IAAI,KAAK,EAAE,KAAK;AAClF,SACE,4CAAC,oBAAK,MAAY,WAAU,eAAc,cAAW,YAAY,GAAG,MACjE,gBACH;AAEJ;","names":[]}
@@ -5,25 +5,11 @@ import { Link } from "./Link";
5
5
  import { RenderExportedComponentContext } from "./Include";
6
6
  import { TinkerableContext } from "../TinkerableContext";
7
7
  import { splitHash } from "../urlUtils";
8
+ import { FS_PREFIX, LinkSpaceContext, resolveLinkTarget } from "../linkSpace";
8
9
  const labelFromTarget = (target) => {
9
10
  const base = target.split(/[\\/]/).pop() ?? target;
10
11
  return base.replace(/\.mdx?$/i, "") || target;
11
12
  };
12
- const normalize = (path) => {
13
- const out = [];
14
- for (const seg of path.split("/")) {
15
- if (seg === "" || seg === ".") continue;
16
- if (seg === "..") out.pop();
17
- else out.push(seg);
18
- }
19
- return "/" + out.join("/");
20
- };
21
- const resolveWikiTarget = (target, currentFile) => {
22
- if (target.startsWith("/")) return normalize(target);
23
- if (!currentFile) return void 0;
24
- const dir = currentFile.slice(0, currentFile.lastIndexOf("/"));
25
- return normalize(`${dir}/${target}`);
26
- };
27
13
  const WikiLink = ({
28
14
  target,
29
15
  label,
@@ -31,6 +17,7 @@ const WikiLink = ({
31
17
  ...rest
32
18
  }) => {
33
19
  const { filesMetadata } = use(TinkerableContext);
20
+ const { corpusRoot } = use(LinkSpaceContext);
34
21
  const renderContext = use(RenderExportedComponentContext);
35
22
  const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;
36
23
  const rawTarget = target ?? "";
@@ -42,7 +29,20 @@ const WikiLink = ({
42
29
  if (pathPart === "" && frag) {
43
30
  return /* @__PURE__ */ jsx(Link, { href: `#${frag}`, className: "ir-wikilink", "data-state": "anchor", ...rest, children: text });
44
31
  }
45
- const resolved = resolveWikiTarget(pathPart, currentFile);
32
+ const resolution = resolveLinkTarget(pathPart, { currentFile, corpusRoot });
33
+ if (resolution.state === "invalid") {
34
+ return /* @__PURE__ */ jsx(
35
+ "span",
36
+ {
37
+ className: "ir-wikilink ir-wikilink-broken",
38
+ "data-state": "broken",
39
+ title: `Invalid ${FS_PREFIX} target: ${pathPart}`,
40
+ ...rest,
41
+ children: text
42
+ }
43
+ );
44
+ }
45
+ const resolved = resolution.state === "resolved" ? resolution.path : void 0;
46
46
  const files = filesMetadata ?? {};
47
47
  const loaded = Object.keys(files).length > 0;
48
48
  if (resolved !== void 0) {
@@ -66,7 +66,9 @@ const WikiLink = ({
66
66
  );
67
67
  }
68
68
  }
69
- return /* @__PURE__ */ jsx(Link, { href: rawTarget, className: "ir-wikilink", "data-state": "resolved", ...rest, children: text });
69
+ const translated = pathPart.startsWith(FS_PREFIX) || corpusRoot !== null && pathPart.startsWith("/");
70
+ const href = translated && resolved !== void 0 ? `${resolved}${frag ? `#${frag}` : ""}` : rawTarget;
71
+ return /* @__PURE__ */ jsx(Link, { href, className: "ir-wikilink", "data-state": "resolved", ...rest, children: text });
70
72
  };
71
73
  export {
72
74
  WikiLink
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/WikiLink.tsx"],"sourcesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\nimport { splitHash } from '../urlUtils';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/** Collapse `.`/`..`/empty segments into a clean absolute path. */\nconst normalize = (path: string): string => {\n const out: string[] = [];\n for (const seg of path.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') out.pop();\n else out.push(seg);\n }\n return '/' + out.join('/');\n};\n\n/**\n * Resolve a wiki-link target to an absolute sandbox path, or `undefined` when it\n * cannot be resolved (a relative target with no known current file). An\n * **absolute** target (`/…`) is taken verbatim; a **relative** target resolves\n * against the current file's directory. Pure path arithmetic (MARKDOWN_SYNTAX_SPEC\n * §13.2) — it never touches the filesystem or any other file.\n */\nconst resolveWikiTarget = (target: string, currentFile?: string): string | undefined => {\n if (target.startsWith('/')) return normalize(target);\n if (!currentFile) return undefined;\n const dir = currentFile.slice(0, currentFile.lastIndexOf('/'));\n return normalize(`${dir}/${target}`);\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the\n * fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on\n * the **fragment-stripped path**, so a section citation to an existing file resolves\n * (not \"broken\"). The fragment then rides to navigation, where the scroll-after-nav\n * effect ({@link useScrollAfterNavigation}) lands the reader on the section.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):\n * - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is\n * the current file: a same-page {@link Link} that scrolls in place, no route change.\n * - **self** — the resolved path is the current file (no fragment): inert text, no link.\n * - **broken** — no file at the resolved path (and the store has loaded): rendered\n * as marked text, **not** a throw.\n * - **resolved** — routed through {@link Link} (in-app navigation for a same-app\n * href, a plain `<a>` otherwise), carrying any `#fragment`.\n *\n * The check is **optimistic until the metadata store loads** (an empty store never\n * flashes \"broken\"), and a relative target with no ambient render context (MDX\n * rendered outside `<Include>`) routes optimistically. Such an app overrides this\n * component (§11) for precise resolution.\n */\nexport const WikiLink = ({\n target,\n label,\n children,\n ...rest\n}: {\n target?: string;\n label?: ReactNode;\n children?: ReactNode;\n} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): ReactNode => {\n const { filesMetadata } = use(TinkerableContext);\n const renderContext = use(RenderExportedComponentContext);\n const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;\n\n const rawTarget = target ?? '';\n const [pathPart, frag] = splitHash(rawTarget);\n const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : '');\n\n // Defensive: the kernel never emits an empty target, but a hand-written\n // `<WikiLink>` might. Render inert text rather than a link to nowhere.\n if (!rawTarget) {\n return (\n <span className=\"ir-wikilink\" {...rest}>\n {text}\n </span>\n );\n }\n\n // Same-page anchor: a fragment with no path (`[[#sec-8-9]]`). Scroll within the\n // current file — no route change (§13.5). <Link> intercepts a bare `#`-href.\n if (pathPart === '' && frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n\n const resolved = resolveWikiTarget(pathPart, currentFile);\n const files = filesMetadata ?? {};\n const loaded = Object.keys(files).length > 0;\n\n // `resolved === undefined` ⇒ a relative target with no known current file: route\n // it optimistically (can't check existence or self-ness generically).\n if (resolved !== undefined) {\n if (currentFile && resolved === currentFile) {\n // The target IS this file. With a fragment it is a same-page anchor to another\n // of this file's sections; without one it is an inert self-reference.\n if (frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n return (\n <span className=\"ir-wikilink ir-wikilink-self\" data-state=\"self\" {...rest}>\n {text}\n </span>\n );\n }\n // Existence is checked on the FRAGMENT-STRIPPED path (optimistic until loaded).\n const exists = !loaded || resolved in files;\n if (!exists) {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`No file at ${resolved}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n }\n // Resolved cross-file target: route through <Link>, carrying the raw target so its\n // `#fragment` rides through navigation to the scroll-after-nav effect (§13.5).\n return (\n <Link href={rawTarget} className=\"ir-wikilink\" data-state=\"resolved\" {...rest}>\n {text}\n </Link>\n );\n};\n"],"mappings":";AAoGM;AApGN,SAAoB,WAAW;AAC/B,SAAS,YAAY;AACrB,SAAS,sCAAsC;AAC/C,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAG1B,MAAM,kBAAkB,CAAC,WAA2B;AAClD,QAAM,OAAO,OAAO,MAAM,OAAO,EAAE,IAAI,KAAK;AAC5C,SAAO,KAAK,QAAQ,YAAY,EAAE,KAAK;AACzC;AAGA,MAAM,YAAY,CAAC,SAA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,aAAa;AAG3C,UAAI,MAAM;AACR,eACE,oBAAC,QAAK,MAAM,IAAI,IAAI,IAAI,WAAU,eAAc,cAAW,UAAU,GAAG,MACrE,gBACH;AAAA,MAEJ;AACA,aACE,oBAAC,UAAK,WAAU,gCAA+B,cAAW,QAAQ,GAAG,MAClE,gBACH;AAAA,IAEJ;AAEA,UAAM,SAAS,CAAC,UAAU,YAAY;AACtC,QAAI,CAAC,QAAQ;AACX,aACE;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,OAAO,cAAc,QAAQ;AAAA,UAC5B,GAAG;AAAA,UAEH;AAAA;AAAA,MACH;AAAA,IAEJ;AAAA,EACF;AAGA,SACE,oBAAC,QAAK,MAAM,WAAW,WAAU,eAAc,cAAW,YAAY,GAAG,MACtE,gBACH;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../src/components/WikiLink.tsx"],"sourcesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\nimport { splitHash } from '../urlUtils';\nimport { FS_PREFIX, LinkSpaceContext, resolveLinkTarget } from '../linkSpace';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the\n * fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on\n * the **fragment-stripped path**, so a section citation to an existing file resolves\n * (not \"broken\"). The fragment then rides to navigation, where the scroll-after-nav\n * effect ({@link useScrollAfterNavigation}) lands the reader on the section.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):\n * - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is\n * the current file: a same-page {@link Link} that scrolls in place, no route change.\n * - **self** — the resolved path is the current file (no fragment): inert text, no link.\n * - **broken** — no file at the resolved path (and the store has loaded): rendered\n * as marked text, **not** a throw.\n * - **resolved** — routed through {@link Link} (in-app navigation for a same-app\n * href, a plain `<a>` otherwise), carrying any `#fragment`.\n *\n * The check is **optimistic until the metadata store loads** (an empty store never\n * flashes \"broken\"), and a relative target with no ambient render context (MDX\n * rendered outside `<Include>`) routes optimistically. Such an app overrides this\n * component (§11) for precise resolution.\n */\nexport const WikiLink = ({\n target,\n label,\n children,\n ...rest\n}: {\n target?: string;\n label?: ReactNode;\n children?: ReactNode;\n} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): ReactNode => {\n const { filesMetadata } = use(TinkerableContext);\n const { corpusRoot } = use(LinkSpaceContext);\n const renderContext = use(RenderExportedComponentContext);\n const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;\n\n const rawTarget = target ?? '';\n const [pathPart, frag] = splitHash(rawTarget);\n const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : '');\n\n // Defensive: the kernel never emits an empty target, but a hand-written\n // `<WikiLink>` might. Render inert text rather than a link to nowhere.\n if (!rawTarget) {\n return (\n <span className=\"ir-wikilink\" {...rest}>\n {text}\n </span>\n );\n }\n\n // Same-page anchor: a fragment with no path (`[[#sec-8-9]]`). Scroll within the\n // current file — no route change (§13.5). <Link> intercepts a bare `#`-href.\n if (pathPart === '' && frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n\n // R3-273 link spaces: resolution is the SHARED resolver (`linkSpace.ts`) —\n // default space (corpus-rooted absolute targets when an enclosing provider\n // declares a corpusRoot; fs-rooted otherwise) or the explicit `$fs:` prefix.\n // A malformed `$fs:` target renders BROKEN, never an anchor.\n const resolution = resolveLinkTarget(pathPart, { currentFile, corpusRoot });\n if (resolution.state === 'invalid') {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`Invalid ${FS_PREFIX} target: ${pathPart}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n const resolved = resolution.state === 'resolved' ? resolution.path : undefined;\n const files = filesMetadata ?? {};\n const loaded = Object.keys(files).length > 0;\n\n // `resolved === undefined` ⇒ a relative target with no known current file: route\n // it optimistically (can't check existence or self-ness generically).\n if (resolved !== undefined) {\n if (currentFile && resolved === currentFile) {\n // The target IS this file. With a fragment it is a same-page anchor to another\n // of this file's sections; without one it is an inert self-reference.\n if (frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n return (\n <span className=\"ir-wikilink ir-wikilink-self\" data-state=\"self\" {...rest}>\n {text}\n </span>\n );\n }\n // Existence is checked on the FRAGMENT-STRIPPED path (optimistic until loaded).\n const exists = !loaded || resolved in files;\n if (!exists) {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`No file at ${resolved}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n }\n // Resolved cross-file target: route through <Link>. A space-translated target\n // (`$fs:` prefix, or a corpus-rooted absolute) navigates to the RESOLVED path —\n // the raw text is not a routable path in those shapes; everything else carries\n // the raw target bit-for-bit so its `#fragment` rides through navigation to the\n // scroll-after-nav effect (§13.5). The fragment is re-attached either way.\n const translated =\n pathPart.startsWith(FS_PREFIX) || (corpusRoot !== null && pathPart.startsWith('/'));\n const href =\n translated && resolved !== undefined ? `${resolved}${frag ? `#${frag}` : ''}` : rawTarget;\n return (\n <Link href={href} className=\"ir-wikilink\" data-state=\"resolved\" {...rest}>\n {text}\n </Link>\n );\n};\n"],"mappings":";AA6EM;AA7EN,SAAoB,WAAW;AAC/B,SAAS,YAAY;AACrB,SAAS,sCAAsC;AAC/C,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,WAAW,kBAAkB,yBAAyB;AAG/D,MAAM,kBAAkB,CAAC,WAA2B;AAClD,QAAM,OAAO,OAAO,MAAM,OAAO,EAAE,IAAI,KAAK;AAC5C,SAAO,KAAK,QAAQ,YAAY,EAAE,KAAK;AACzC;AA2CO,MAAM,WAAW,CAAC;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,MAI+E;AAC7E,QAAM,EAAE,cAAc,IAAI,IAAI,iBAAiB;AAC/C,QAAM,EAAE,WAAW,IAAI,IAAI,gBAAgB;AAC3C,QAAM,gBAAgB,IAAI,8BAA8B;AACxD,QAAM,cAAc,eAAe,mBAAmB,YAAY,QAAQ;AAE1E,QAAM,YAAY,UAAU;AAC5B,QAAM,CAAC,UAAU,IAAI,IAAI,UAAU,SAAS;AAC5C,QAAM,OAAO,YAAY,UAAU,YAAY,gBAAgB,YAAY,QAAQ,SAAS,IAAI;AAIhG,MAAI,CAAC,WAAW;AACd,WACE,oBAAC,UAAK,WAAU,eAAe,GAAG,MAC/B,gBACH;AAAA,EAEJ;AAIA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H;AAEJ;","names":[]}
@@ -22,8 +22,9 @@ __export(contribute_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(contribute_exports);
24
24
  var import_protocolStream = require("./protocolStream");
25
+ var import_protocol = require("./generated/protocol");
25
26
  function contribute(opts) {
26
- return (0, import_protocolStream.protocolStream)("protocol-contribute", "run", [opts]);
27
+ return (0, import_protocolStream.protocolStream)(import_protocol.PROTOCOL_CONTRIBUTE, "run", [opts]);
27
28
  }
28
29
  // Annotate the CommonJS export names for ESM import in node:
29
30
  0 && (module.exports = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contribute.ts"],"sourcesContent":["// Contribute — stream a save (PR or direct commit) from app code\n// (UI_AS_APPS_SPEC §5.1, CONTRIBUTE_SPEC). The host runs the *existing*\n// contribution orchestrator and streams its stages back; this is the typed\n// front door over `protocolStream`.\n//\n// The OAuth token never reaches here — it stays on the host. The app passes a\n// commit message + save mode and watches stages go by; the host owns the token,\n// the GitHub API calls, and the user-facing consent.\nimport { protocolStream } from './protocolStream';\n\n/** The save strategy. `direct` requires the first-party `contribute:direct`\n * capability and a scarier consent line — a `contribute:any` app asking for it\n * is REJECTED (`forbidden`), never silently downgraded to a PR (threat T11). */\nexport type ContributeMode = 'pr' | 'direct';\n\n/** A stage emitted as the contribution runs. Mirrors the host orchestrator's\n * event union; carries progress metadata only — never the token or file blobs. */\nexport type ContributionEvent =\n | { stage: 'auth-check' }\n | { stage: 'diff-compute' }\n | { stage: 'permission-check' }\n | { stage: 'install-required'; targetOwner: string; targetRepo: string; installUrl: string }\n | { stage: 'conflict-check' }\n | { stage: 'fork-prepare'; forkOwner: string; alreadyExists: boolean }\n | { stage: 'upload-blob'; path: string; index: number; total: number }\n | { stage: 'create-tree' }\n | { stage: 'create-commit' }\n | { stage: 'create-branch'; branchName: string }\n | { stage: 'create-pr' }\n | { stage: 'pr-updated'; prNumber: number; prUrl: string; commitSha: string }\n | { stage: 'commit-pushed'; ref: string; commitSha: string }\n | { stage: 'switch-branch'; provider: 'github'; pushOwner: string; repository: string; branchName: string }\n | { stage: 'done'; prUrl?: string; prNumber?: number; commitSha: string }\n | { stage: 'warning'; message: string; details?: unknown }\n | { stage: 'error'; message: string; recoverable: boolean };\n\n/** The settled outcome (the stream's return value). */\nexport interface ContributionResult {\n prUrl?: string;\n prNumber?: number;\n commitSha: string;\n treeSha: string;\n branchName: string;\n mode: 'direct-commit' | 'new-branch-pr' | 'extend-existing';\n}\n\n/** Options for a contribution: the commit message, save {@link ContributeMode},\n * and (PR mode) an optional branch name. */\nexport interface ContributeOptions {\n /** The commit message / PR title. */\n commitMessage: string;\n /** `'pr'` (default) opens a PR; `'direct'` commits to the branch and needs\n * the first-party `contribute:direct` capability. */\n mode?: ContributeMode;\n /** Override the generated branch name (PR mode). */\n branchName?: string;\n}\n\n/**\n * Save the current working tree, streaming each stage.\n *\n * ```ts\n * for await (const ev of contribute({ commitMessage: 'Edit post' })) {\n * if (ev.stage === 'done') console.log(ev.prUrl);\n * }\n * ```\n *\n * Yields {@link ContributionEvent}s and returns a {@link ContributionResult}.\n * Throws a `StreamError` (`.code`) if the host rejects the request — notably\n * `forbidden` when a `contribute:any` app asks for `mode: 'direct'` (T11).\n */\nexport function contribute(\n opts: ContributeOptions\n): AsyncGenerator<ContributionEvent, ContributionResult, void> {\n return protocolStream<ContributionEvent, ContributionResult>('protocol-contribute', 'run', [opts]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,4BAA+B;AA+DxB,SAAS,WACd,MAC6D;AAC7D,aAAO,sCAAsD,uBAAuB,OAAO,CAAC,IAAI,CAAC;AACnG;","names":[]}
1
+ {"version":3,"sources":["../src/contribute.ts"],"sourcesContent":["// Contribute — stream a save (PR or direct commit) from app code\n// (UI_AS_APPS_SPEC §5.1, CONTRIBUTE_SPEC). The host runs the *existing*\n// contribution orchestrator and streams its stages back; this is the typed\n// front door over `protocolStream`.\n//\n// The OAuth token never reaches here — it stays on the host. The app passes a\n// commit message + save mode and watches stages go by; the host owns the token,\n// the GitHub API calls, and the user-facing consent.\nimport { protocolStream } from './protocolStream';\nimport { PROTOCOL_CONTRIBUTE } from './generated/protocol';\n\n/** The save strategy. `direct` requires the first-party `contribute:direct`\n * capability and a scarier consent line — a `contribute:any` app asking for it\n * is REJECTED (`forbidden`), never silently downgraded to a PR (threat T11). */\nexport type ContributeMode = 'pr' | 'direct';\n\n/** A stage emitted as the contribution runs. Mirrors the host orchestrator's\n * event union; carries progress metadata only — never the token or file blobs. */\nexport type ContributionEvent =\n | { stage: 'auth-check' }\n | { stage: 'diff-compute' }\n | { stage: 'permission-check' }\n | { stage: 'install-required'; targetOwner: string; targetRepo: string; installUrl: string }\n | { stage: 'conflict-check' }\n | { stage: 'fork-prepare'; forkOwner: string; alreadyExists: boolean }\n | { stage: 'upload-blob'; path: string; index: number; total: number }\n | { stage: 'create-tree' }\n | { stage: 'create-commit' }\n | { stage: 'create-branch'; branchName: string }\n | { stage: 'create-pr' }\n | { stage: 'pr-updated'; prNumber: number; prUrl: string; commitSha: string }\n | { stage: 'commit-pushed'; ref: string; commitSha: string }\n | { stage: 'switch-branch'; provider: 'github'; pushOwner: string; repository: string; branchName: string }\n | { stage: 'done'; prUrl?: string; prNumber?: number; commitSha: string }\n | { stage: 'warning'; message: string; details?: unknown }\n | { stage: 'error'; message: string; recoverable: boolean };\n\n/** The settled outcome (the stream's return value). */\nexport interface ContributionResult {\n prUrl?: string;\n prNumber?: number;\n commitSha: string;\n treeSha: string;\n branchName: string;\n mode: 'direct-commit' | 'new-branch-pr' | 'extend-existing';\n}\n\n/** Options for a contribution: the commit message, save {@link ContributeMode},\n * and (PR mode) an optional branch name. */\nexport interface ContributeOptions {\n /** The commit message / PR title. */\n commitMessage: string;\n /** `'pr'` (default) opens a PR; `'direct'` commits to the branch and needs\n * the first-party `contribute:direct` capability. */\n mode?: ContributeMode;\n /** Override the generated branch name (PR mode). */\n branchName?: string;\n}\n\n/**\n * Save the current working tree, streaming each stage.\n *\n * ```ts\n * for await (const ev of contribute({ commitMessage: 'Edit post' })) {\n * if (ev.stage === 'done') console.log(ev.prUrl);\n * }\n * ```\n *\n * Yields {@link ContributionEvent}s and returns a {@link ContributionResult}.\n * Throws a `StreamError` (`.code`) if the host rejects the request — notably\n * `forbidden` when a `contribute:any` app asks for `mode: 'direct'` (T11).\n */\nexport function contribute(\n opts: ContributeOptions\n): AsyncGenerator<ContributionEvent, ContributionResult, void> {\n return protocolStream<ContributionEvent, ContributionResult>(PROTOCOL_CONTRIBUTE, 'run', [opts]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,4BAA+B;AAC/B,sBAAoC;AA+D7B,SAAS,WACd,MAC6D;AAC7D,aAAO,sCAAsD,qCAAqB,OAAO,CAAC,IAAI,CAAC;AACjG;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import "./chunk-VHAA22YE.js";
2
2
  import { protocolStream } from "./protocolStream";
3
+ import { PROTOCOL_CONTRIBUTE } from "./generated/protocol";
3
4
  function contribute(opts) {
4
- return protocolStream("protocol-contribute", "run", [opts]);
5
+ return protocolStream(PROTOCOL_CONTRIBUTE, "run", [opts]);
5
6
  }
6
7
  export {
7
8
  contribute
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contribute.ts"],"sourcesContent":["// Contribute — stream a save (PR or direct commit) from app code\n// (UI_AS_APPS_SPEC §5.1, CONTRIBUTE_SPEC). The host runs the *existing*\n// contribution orchestrator and streams its stages back; this is the typed\n// front door over `protocolStream`.\n//\n// The OAuth token never reaches here — it stays on the host. The app passes a\n// commit message + save mode and watches stages go by; the host owns the token,\n// the GitHub API calls, and the user-facing consent.\nimport { protocolStream } from './protocolStream';\n\n/** The save strategy. `direct` requires the first-party `contribute:direct`\n * capability and a scarier consent line — a `contribute:any` app asking for it\n * is REJECTED (`forbidden`), never silently downgraded to a PR (threat T11). */\nexport type ContributeMode = 'pr' | 'direct';\n\n/** A stage emitted as the contribution runs. Mirrors the host orchestrator's\n * event union; carries progress metadata only — never the token or file blobs. */\nexport type ContributionEvent =\n | { stage: 'auth-check' }\n | { stage: 'diff-compute' }\n | { stage: 'permission-check' }\n | { stage: 'install-required'; targetOwner: string; targetRepo: string; installUrl: string }\n | { stage: 'conflict-check' }\n | { stage: 'fork-prepare'; forkOwner: string; alreadyExists: boolean }\n | { stage: 'upload-blob'; path: string; index: number; total: number }\n | { stage: 'create-tree' }\n | { stage: 'create-commit' }\n | { stage: 'create-branch'; branchName: string }\n | { stage: 'create-pr' }\n | { stage: 'pr-updated'; prNumber: number; prUrl: string; commitSha: string }\n | { stage: 'commit-pushed'; ref: string; commitSha: string }\n | { stage: 'switch-branch'; provider: 'github'; pushOwner: string; repository: string; branchName: string }\n | { stage: 'done'; prUrl?: string; prNumber?: number; commitSha: string }\n | { stage: 'warning'; message: string; details?: unknown }\n | { stage: 'error'; message: string; recoverable: boolean };\n\n/** The settled outcome (the stream's return value). */\nexport interface ContributionResult {\n prUrl?: string;\n prNumber?: number;\n commitSha: string;\n treeSha: string;\n branchName: string;\n mode: 'direct-commit' | 'new-branch-pr' | 'extend-existing';\n}\n\n/** Options for a contribution: the commit message, save {@link ContributeMode},\n * and (PR mode) an optional branch name. */\nexport interface ContributeOptions {\n /** The commit message / PR title. */\n commitMessage: string;\n /** `'pr'` (default) opens a PR; `'direct'` commits to the branch and needs\n * the first-party `contribute:direct` capability. */\n mode?: ContributeMode;\n /** Override the generated branch name (PR mode). */\n branchName?: string;\n}\n\n/**\n * Save the current working tree, streaming each stage.\n *\n * ```ts\n * for await (const ev of contribute({ commitMessage: 'Edit post' })) {\n * if (ev.stage === 'done') console.log(ev.prUrl);\n * }\n * ```\n *\n * Yields {@link ContributionEvent}s and returns a {@link ContributionResult}.\n * Throws a `StreamError` (`.code`) if the host rejects the request — notably\n * `forbidden` when a `contribute:any` app asks for `mode: 'direct'` (T11).\n */\nexport function contribute(\n opts: ContributeOptions\n): AsyncGenerator<ContributionEvent, ContributionResult, void> {\n return protocolStream<ContributionEvent, ContributionResult>('protocol-contribute', 'run', [opts]);\n}\n"],"mappings":";AAQA,SAAS,sBAAsB;AA+DxB,SAAS,WACd,MAC6D;AAC7D,SAAO,eAAsD,uBAAuB,OAAO,CAAC,IAAI,CAAC;AACnG;","names":[]}
1
+ {"version":3,"sources":["../src/contribute.ts"],"sourcesContent":["// Contribute — stream a save (PR or direct commit) from app code\n// (UI_AS_APPS_SPEC §5.1, CONTRIBUTE_SPEC). The host runs the *existing*\n// contribution orchestrator and streams its stages back; this is the typed\n// front door over `protocolStream`.\n//\n// The OAuth token never reaches here — it stays on the host. The app passes a\n// commit message + save mode and watches stages go by; the host owns the token,\n// the GitHub API calls, and the user-facing consent.\nimport { protocolStream } from './protocolStream';\nimport { PROTOCOL_CONTRIBUTE } from './generated/protocol';\n\n/** The save strategy. `direct` requires the first-party `contribute:direct`\n * capability and a scarier consent line — a `contribute:any` app asking for it\n * is REJECTED (`forbidden`), never silently downgraded to a PR (threat T11). */\nexport type ContributeMode = 'pr' | 'direct';\n\n/** A stage emitted as the contribution runs. Mirrors the host orchestrator's\n * event union; carries progress metadata only — never the token or file blobs. */\nexport type ContributionEvent =\n | { stage: 'auth-check' }\n | { stage: 'diff-compute' }\n | { stage: 'permission-check' }\n | { stage: 'install-required'; targetOwner: string; targetRepo: string; installUrl: string }\n | { stage: 'conflict-check' }\n | { stage: 'fork-prepare'; forkOwner: string; alreadyExists: boolean }\n | { stage: 'upload-blob'; path: string; index: number; total: number }\n | { stage: 'create-tree' }\n | { stage: 'create-commit' }\n | { stage: 'create-branch'; branchName: string }\n | { stage: 'create-pr' }\n | { stage: 'pr-updated'; prNumber: number; prUrl: string; commitSha: string }\n | { stage: 'commit-pushed'; ref: string; commitSha: string }\n | { stage: 'switch-branch'; provider: 'github'; pushOwner: string; repository: string; branchName: string }\n | { stage: 'done'; prUrl?: string; prNumber?: number; commitSha: string }\n | { stage: 'warning'; message: string; details?: unknown }\n | { stage: 'error'; message: string; recoverable: boolean };\n\n/** The settled outcome (the stream's return value). */\nexport interface ContributionResult {\n prUrl?: string;\n prNumber?: number;\n commitSha: string;\n treeSha: string;\n branchName: string;\n mode: 'direct-commit' | 'new-branch-pr' | 'extend-existing';\n}\n\n/** Options for a contribution: the commit message, save {@link ContributeMode},\n * and (PR mode) an optional branch name. */\nexport interface ContributeOptions {\n /** The commit message / PR title. */\n commitMessage: string;\n /** `'pr'` (default) opens a PR; `'direct'` commits to the branch and needs\n * the first-party `contribute:direct` capability. */\n mode?: ContributeMode;\n /** Override the generated branch name (PR mode). */\n branchName?: string;\n}\n\n/**\n * Save the current working tree, streaming each stage.\n *\n * ```ts\n * for await (const ev of contribute({ commitMessage: 'Edit post' })) {\n * if (ev.stage === 'done') console.log(ev.prUrl);\n * }\n * ```\n *\n * Yields {@link ContributionEvent}s and returns a {@link ContributionResult}.\n * Throws a `StreamError` (`.code`) if the host rejects the request — notably\n * `forbidden` when a `contribute:any` app asks for `mode: 'direct'` (T11).\n */\nexport function contribute(\n opts: ContributeOptions\n): AsyncGenerator<ContributionEvent, ContributionResult, void> {\n return protocolStream<ContributionEvent, ContributionResult>(PROTOCOL_CONTRIBUTE, 'run', [opts]);\n}\n"],"mappings":";AAQA,SAAS,sBAAsB;AAC/B,SAAS,2BAA2B;AA+D7B,SAAS,WACd,MAC6D;AAC7D,SAAO,eAAsD,qBAAqB,OAAO,CAAC,IAAI,CAAC;AACjG;","names":[]}
package/dist/debug.cjs CHANGED
@@ -26,9 +26,10 @@ __export(debug_exports, {
26
26
  module.exports = __toCommonJS(debug_exports);
27
27
  var import_pushChannel = require("./pushChannel");
28
28
  var import_sandboxUtils = require("./sandboxUtils");
29
+ var import_protocol = require("./generated/protocol");
29
30
  const enabledChannel = (0, import_pushChannel.createPushChannel)({
30
- pushType: "debug-enabled",
31
- requestType: "request-debug-enabled",
31
+ pushType: import_protocol.DEBUG_ENABLED,
32
+ requestType: import_protocol.REQUEST_DEBUG_ENABLED,
32
33
  initial: false,
33
34
  parse: (msg) => typeof msg.enabled === "boolean" ? msg.enabled : void 0
34
35
  });
@@ -49,7 +50,7 @@ function safeData(data) {
49
50
  function log(level, message, data) {
50
51
  if (!enabledChannel.get()) return;
51
52
  try {
52
- (0, import_sandboxUtils.sendMessage)("debug-log", { level, message: String(message), data: safeData(data) });
53
+ (0, import_sandboxUtils.sendMessage)(import_protocol.DEBUG_LOG, { level, message: String(message), data: safeData(data) });
53
54
  } catch {
54
55
  }
55
56
  }
@@ -121,7 +122,7 @@ let responderStarted = false;
121
122
  function startResponder() {
122
123
  if (responderStarted || typeof window === "undefined") return;
123
124
  responderStarted = true;
124
- (0, import_sandboxUtils.addListener)("debug-query", (msg) => {
125
+ (0, import_sandboxUtils.addListener)(import_protocol.DEBUG_QUERY, (msg) => {
125
126
  if (!enabledChannel.get()) return;
126
127
  const id = msg.id;
127
128
  const method = msg.method;
@@ -149,7 +150,7 @@ function startResponder() {
149
150
  error = e instanceof Error ? e.message : String(e);
150
151
  }
151
152
  try {
152
- (0, import_sandboxUtils.sendMessage)("debug-query-result", { id, ok, result, error });
153
+ (0, import_sandboxUtils.sendMessage)(import_protocol.DEBUG_QUERY_RESULT, { id, ok, result, error });
153
154
  } catch {
154
155
  }
155
156
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/debug.ts"],"sourcesContent":["// System-app devtools — the app-facing surface (plan: docs/plans/system-app-devtools.md).\n//\n// Two opt-in, DEV-ONLY instruments for debugging a sandboxed UI-as-app region:\n// 1. `debug.log(...)` — an app→host one-way log surfaced in the host dev panel\n// / CLI `/debug` stream (instead of hand-fishing console output out of a\n// cross-origin iframe's devtools).\n// 2. a READ-ONLY DOM/layout responder the host can query from outside — the\n// thing a cross-origin screenshot can't reliably give you (a blank capture\n// is ambiguous between a real 0-height collapse and a paint artifact).\n//\n// SECURITY (the gating constraint — see the plan's §0):\n// - Both are inert unless the HOST signals dev mode via the `debug-enabled`\n// channel. The host only sets it for a dev/override session (the `ir-dev-*`\n// deep link) or an explicit operator developer-mode. A published app served\n// to a normal user gets `enabled:false` → `debug.log` is a no-op and the\n// responder never answers. Production isolation is therefore unchanged.\n// - The responder is READ-ONLY with a fixed vocabulary (snapshotDom /\n// computedStyle / rect). There is deliberately NO eval bridge — that would\n// turn a debug aid into remote code execution into the sandbox.\n// - The responder reads only its OWN `document` (it lives in its own opaque\n// iframe and cannot reach a sibling app), so there is no app↔app leak even\n// in dev.\n// - Output is bounded (node/depth/text caps) so a query can't exfiltrate an\n// unbounded payload or wedge the app.\n//\n// Apps that want the strongest guarantee can additionally guard their own usage\n// behind `import.meta.env.DEV` so the calls are tree-shaken from prod bundles;\n// the runtime gate here is the backstop that holds regardless.\n\nimport { createPushChannel } from './pushChannel';\nimport { sendMessage, addListener } from './sandboxUtils';\n\n/** Severity of a {@link debug.log} entry. */\nexport type DebugLevel = 'debug' | 'info' | 'warn' | 'error';\n\n// ── Dev gate ────────────────────────────────────────────────────────────────\n// The host pushes `debug-enabled:true` only for a dev/override session. Until\n// then (and always in production) it stays false and every instrument is inert.\nconst enabledChannel = createPushChannel<boolean>({\n pushType: 'debug-enabled',\n requestType: 'request-debug-enabled',\n initial: false,\n parse: (msg) => (typeof msg.enabled === 'boolean' ? msg.enabled : undefined),\n});\n\n/** Is the host dev-debug surface active for this session? `false` in production. */\nexport const isDebugEnabled = (): boolean => enabledChannel.get();\n\n/** React hook: whether the host dev-debug surface is active (re-renders on change).\n * Handy for showing a debug affordance only when it would do something. */\nexport const useDebugEnabled = (): boolean => enabledChannel.use();\n\n// ── 1. App→host debug log ─────────────────────────────────────────────────────\n// Best-effort: a value that can't be structured-cloned is replaced with a marker\n// rather than throwing — `debug.log` must never break the app.\nconst MAX_DATA_BYTES = 16 * 1024;\n\nfunction safeData(data: unknown): unknown {\n if (data === undefined) return undefined;\n try {\n const json = JSON.stringify(data);\n if (json === undefined) return '[unserializable]';\n if (json.length > MAX_DATA_BYTES) return `[truncated ${json.length}B]`;\n return JSON.parse(json);\n } catch {\n return '[unserializable]';\n }\n}\n\n/**\n * Emit a structured debug entry to the host dev surface. A NO-OP unless the host\n * has enabled the dev-debug session ({@link isDebugEnabled}); in production it\n * does nothing and sends nothing.\n *\n * debug.log('info', 'mounted', { activeFile });\n */\nexport function log(level: DebugLevel, message: string, data?: unknown): void {\n if (!enabledChannel.get()) return; // inert in prod / non-dev sessions\n try {\n sendMessage('debug-log', { level, message: String(message), data: safeData(data) });\n } catch {\n /* transport not ready — drop silently; logging must never throw */\n }\n}\n\n// ── 2. Read-only DOM / layout responder ───────────────────────────────────────\n// The host sends `debug-query` { id, method, params }; we reply with\n// `debug-query-result` { id, ok, result | error }. Only ever active while the dev\n// gate is enabled. Vocabulary is fixed and read-only.\n\ninterface DomNode {\n tag: string;\n id?: string;\n classes?: string[];\n attrs?: Record<string, string>;\n rect?: { x: number; y: number; w: number; h: number };\n text?: string;\n children?: DomNode[];\n truncated?: true;\n}\n\nconst ATTR_ALLOW = new Set(['role', 'aria-hidden', 'data-theme', 'data-active', 'href', 'type', 'hidden']);\nconst MAX_NODES = 2000;\nconst MAX_DEPTH = 25;\nconst MAX_TEXT = 200;\n\nfunction round(n: number): number {\n return Math.round(n);\n}\n\nfunction snapshotDom(params: { selector?: string; maxDepth?: number; maxNodes?: number }): DomNode | null {\n if (typeof document === 'undefined') return null;\n const root = params.selector ? document.querySelector(params.selector) : document.body;\n if (!root) return null;\n const maxDepth = Math.min(params.maxDepth ?? MAX_DEPTH, MAX_DEPTH);\n const maxNodes = Math.min(params.maxNodes ?? MAX_NODES, MAX_NODES);\n let budget = maxNodes;\n\n const walk = (el: Element, depth: number): DomNode => {\n budget--;\n const r = el.getBoundingClientRect();\n const classes = el.classList.length ? [...el.classList] : undefined;\n const attrs: Record<string, string> = {};\n for (const name of el.getAttributeNames()) {\n if (ATTR_ALLOW.has(name)) attrs[name] = el.getAttribute(name) ?? '';\n }\n // Direct text (not descendants') so a leaf's label is visible without dumping\n // the whole subtree's text.\n const ownText = [...el.childNodes]\n .filter((n) => n.nodeType === 3)\n .map((n) => (n.textContent ?? '').trim())\n .join(' ')\n .trim();\n const node: DomNode = {\n tag: el.tagName.toLowerCase(),\n ...(el.id ? { id: el.id } : {}),\n ...(classes ? { classes } : {}),\n ...(Object.keys(attrs).length ? { attrs } : {}),\n rect: { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) },\n ...(ownText ? { text: ownText.slice(0, MAX_TEXT) } : {}),\n };\n if (depth < maxDepth && el.children.length && budget > 0) {\n const children: DomNode[] = [];\n for (const child of el.children) {\n if (budget <= 0) {\n node.truncated = true;\n break;\n }\n children.push(walk(child, depth + 1));\n }\n if (children.length) node.children = children;\n } else if (el.children.length) {\n node.truncated = true;\n }\n return node;\n };\n\n return walk(root, 0);\n}\n\nfunction computedStyle(params: { selector: string; props: string[] }): Record<string, string> | null {\n if (typeof document === 'undefined') return null;\n const el = document.querySelector(params.selector);\n if (!el) return null;\n const cs = getComputedStyle(el);\n const out: Record<string, string> = {};\n for (const p of params.props.slice(0, 50)) out[p] = cs.getPropertyValue(p) || cs[p as keyof CSSStyleDeclaration]?.toString?.() || '';\n return out;\n}\n\nfunction rects(params: { selector: string }): Array<{ x: number; y: number; w: number; h: number }> {\n if (typeof document === 'undefined') return [];\n return [...document.querySelectorAll(params.selector)].slice(0, 200).map((el) => {\n const r = el.getBoundingClientRect();\n return { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) };\n });\n}\n\nlet responderStarted = false;\n\n/** Wire the read-only DOM/layout responder. Idempotent; called lazily once the\n * dev gate turns on. No effect when `document` is absent (non-browser realm). */\nfunction startResponder(): void {\n if (responderStarted || typeof window === 'undefined') return;\n responderStarted = true;\n addListener('debug-query', (msg: { id?: unknown; method?: unknown; params?: unknown }) => {\n if (!enabledChannel.get()) return; // gate: ignore unless dev-enabled\n const id = msg.id;\n const method = msg.method;\n const params = (msg.params ?? {}) as Record<string, unknown>;\n let ok = true;\n let result: unknown = null;\n let error: string | undefined;\n try {\n switch (method) {\n case 'snapshotDom':\n result = snapshotDom(params as never);\n break;\n case 'computedStyle':\n result = computedStyle(params as never);\n break;\n case 'rect':\n result = rects(params as never);\n break;\n default:\n ok = false;\n error = `unknown debug method: ${String(method)}`;\n }\n } catch (e) {\n ok = false;\n error = e instanceof Error ? e.message : String(e);\n }\n try {\n sendMessage('debug-query-result', { id, ok, result, error });\n } catch {\n /* transport gone — nothing to do */\n }\n });\n}\n\n// Start the responder as soon as the gate flips on (and not before).\nenabledChannel.onChange((enabled) => {\n if (enabled) startResponder();\n});\n\n/** The dev-only debug surface. Inert unless the host enables it ({@link isDebugEnabled}). */\nexport const debug = { log, isEnabled: isDebugEnabled } as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BA,yBAAkC;AAClC,0BAAyC;AAQzC,MAAM,qBAAiB,sCAA2B;AAAA,EAChD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAS,OAAO,IAAI,YAAY,YAAY,IAAI,UAAU;AACpE,CAAC;AAGM,MAAM,iBAAiB,MAAe,eAAe,IAAI;AAIzD,MAAM,kBAAkB,MAAe,eAAe,IAAI;AAKjE,MAAM,iBAAiB,KAAK;AAE5B,SAAS,SAAS,MAAwB;AACxC,MAAI,SAAS,OAAW,QAAO;AAC/B,MAAI;AACF,UAAM,OAAO,KAAK,UAAU,IAAI;AAChC,QAAI,SAAS,OAAW,QAAO;AAC/B,QAAI,KAAK,SAAS,eAAgB,QAAO,cAAc,KAAK,MAAM;AAClE,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASO,SAAS,IAAI,OAAmB,SAAiB,MAAsB;AAC5E,MAAI,CAAC,eAAe,IAAI,EAAG;AAC3B,MAAI;AACF,yCAAY,aAAa,EAAE,OAAO,SAAS,OAAO,OAAO,GAAG,MAAM,SAAS,IAAI,EAAE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EAAE,CAAC,GAAG,GAAG,MAAM,EAAE,CAAC,GAAG,GAAG,MAAM,EAAE,KAAK,GAAG,GAAG,MAAM,EAAE,MAAM,EAAE;AAAA,EAC/E,CAAC;AACH;AAEA,IAAI,mBAAmB;AAIvB,SAAS,iBAAuB;AAC9B,MAAI,oBAAoB,OAAO,WAAW,YAAa;AACvD,qBAAmB;AACnB,uCAAY,eAAe,CAAC,QAA8D;AACxF,QAAI,CAAC,eAAe,IAAI,EAAG;AAC3B,UAAM,KAAK,IAAI;AACf,UAAM,SAAS,IAAI;AACnB,UAAM,SAAU,IAAI,UAAU,CAAC;AAC/B,QAAI,KAAK;AACT,QAAI,SAAkB;AACtB,QAAI;AACJ,QAAI;AACF,cAAQ,QAAQ;AAAA,QACd,KAAK;AACH,mBAAS,YAAY,MAAe;AACpC;AAAA,QACF,KAAK;AACH,mBAAS,cAAc,MAAe;AACtC;AAAA,QACF,KAAK;AACH,mBAAS,MAAM,MAAe;AAC9B;AAAA,QACF;AACE,eAAK;AACL,kBAAQ,yBAAyB,OAAO,MAAM,CAAC;AAAA,MACnD;AAAA,IACF,SAAS,GAAG;AACV,WAAK;AACL,cAAQ,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AAAA,IACnD;AACA,QAAI;AACF,2CAAY,sBAAsB,EAAE,IAAI,IAAI,QAAQ,MAAM,CAAC;AAAA,IAC7D,QAAQ;AAAA,IAER;AAAA,EACF,CAAC;AACH;AAGA,eAAe,SAAS,CAAC,YAAY;AACnC,MAAI,QAAS,gBAAe;AAC9B,CAAC;AAGM,MAAM,QAAQ,EAAE,KAAK,WAAW,eAAe;","names":[]}
1
+ {"version":3,"sources":["../src/debug.ts"],"sourcesContent":["// System-app devtools — the app-facing surface (plan: docs/plans/system-app-devtools.md).\n//\n// Two opt-in, DEV-ONLY instruments for debugging a sandboxed UI-as-app region:\n// 1. `debug.log(...)` — an app→host one-way log surfaced in the host dev panel\n// / CLI `/debug` stream (instead of hand-fishing console output out of a\n// cross-origin iframe's devtools).\n// 2. a READ-ONLY DOM/layout responder the host can query from outside — the\n// thing a cross-origin screenshot can't reliably give you (a blank capture\n// is ambiguous between a real 0-height collapse and a paint artifact).\n//\n// SECURITY (the gating constraint — see the plan's §0):\n// - Both are inert unless the HOST signals dev mode via the `debug-enabled`\n// channel. The host only sets it for a dev/override session (the `ir-dev-*`\n// deep link) or an explicit operator developer-mode. A published app served\n// to a normal user gets `enabled:false` → `debug.log` is a no-op and the\n// responder never answers. Production isolation is therefore unchanged.\n// - The responder is READ-ONLY with a fixed vocabulary (snapshotDom /\n// computedStyle / rect). There is deliberately NO eval bridge — that would\n// turn a debug aid into remote code execution into the sandbox.\n// - The responder reads only its OWN `document` (it lives in its own opaque\n// iframe and cannot reach a sibling app), so there is no app↔app leak even\n// in dev.\n// - Output is bounded (node/depth/text caps) so a query can't exfiltrate an\n// unbounded payload or wedge the app.\n//\n// Apps that want the strongest guarantee can additionally guard their own usage\n// behind `import.meta.env.DEV` so the calls are tree-shaken from prod bundles;\n// the runtime gate here is the backstop that holds regardless.\n\nimport { createPushChannel } from './pushChannel';\nimport { sendMessage, addListener } from './sandboxUtils';\nimport {\n DEBUG_ENABLED,\n DEBUG_LOG,\n DEBUG_QUERY,\n DEBUG_QUERY_RESULT,\n REQUEST_DEBUG_ENABLED,\n} from './generated/protocol';\n\n/** Severity of a {@link debug.log} entry. */\nexport type DebugLevel = 'debug' | 'info' | 'warn' | 'error';\n\n// ── Dev gate ────────────────────────────────────────────────────────────────\n// The host pushes `debug-enabled:true` only for a dev/override session. Until\n// then (and always in production) it stays false and every instrument is inert.\nconst enabledChannel = createPushChannel<boolean>({\n pushType: DEBUG_ENABLED,\n requestType: REQUEST_DEBUG_ENABLED,\n initial: false,\n parse: (msg) => (typeof msg.enabled === 'boolean' ? msg.enabled : undefined),\n});\n\n/** Is the host dev-debug surface active for this session? `false` in production. */\nexport const isDebugEnabled = (): boolean => enabledChannel.get();\n\n/** React hook: whether the host dev-debug surface is active (re-renders on change).\n * Handy for showing a debug affordance only when it would do something. */\nexport const useDebugEnabled = (): boolean => enabledChannel.use();\n\n// ── 1. App→host debug log ─────────────────────────────────────────────────────\n// Best-effort: a value that can't be structured-cloned is replaced with a marker\n// rather than throwing — `debug.log` must never break the app.\nconst MAX_DATA_BYTES = 16 * 1024;\n\nfunction safeData(data: unknown): unknown {\n if (data === undefined) return undefined;\n try {\n const json = JSON.stringify(data);\n if (json === undefined) return '[unserializable]';\n if (json.length > MAX_DATA_BYTES) return `[truncated ${json.length}B]`;\n return JSON.parse(json);\n } catch {\n return '[unserializable]';\n }\n}\n\n/**\n * Emit a structured debug entry to the host dev surface. A NO-OP unless the host\n * has enabled the dev-debug session ({@link isDebugEnabled}); in production it\n * does nothing and sends nothing.\n *\n * debug.log('info', 'mounted', { activeFile });\n */\nexport function log(level: DebugLevel, message: string, data?: unknown): void {\n if (!enabledChannel.get()) return; // inert in prod / non-dev sessions\n try {\n sendMessage(DEBUG_LOG, { level, message: String(message), data: safeData(data) });\n } catch {\n /* transport not ready — drop silently; logging must never throw */\n }\n}\n\n// ── 2. Read-only DOM / layout responder ───────────────────────────────────────\n// The host sends `debug-query` { id, method, params }; we reply with\n// `debug-query-result` { id, ok, result | error }. Only ever active while the dev\n// gate is enabled. Vocabulary is fixed and read-only.\n\ninterface DomNode {\n tag: string;\n id?: string;\n classes?: string[];\n attrs?: Record<string, string>;\n rect?: { x: number; y: number; w: number; h: number };\n text?: string;\n children?: DomNode[];\n truncated?: true;\n}\n\nconst ATTR_ALLOW = new Set(['role', 'aria-hidden', 'data-theme', 'data-active', 'href', 'type', 'hidden']);\nconst MAX_NODES = 2000;\nconst MAX_DEPTH = 25;\nconst MAX_TEXT = 200;\n\nfunction round(n: number): number {\n return Math.round(n);\n}\n\nfunction snapshotDom(params: { selector?: string; maxDepth?: number; maxNodes?: number }): DomNode | null {\n if (typeof document === 'undefined') return null;\n const root = params.selector ? document.querySelector(params.selector) : document.body;\n if (!root) return null;\n const maxDepth = Math.min(params.maxDepth ?? MAX_DEPTH, MAX_DEPTH);\n const maxNodes = Math.min(params.maxNodes ?? MAX_NODES, MAX_NODES);\n let budget = maxNodes;\n\n const walk = (el: Element, depth: number): DomNode => {\n budget--;\n const r = el.getBoundingClientRect();\n const classes = el.classList.length ? [...el.classList] : undefined;\n const attrs: Record<string, string> = {};\n for (const name of el.getAttributeNames()) {\n if (ATTR_ALLOW.has(name)) attrs[name] = el.getAttribute(name) ?? '';\n }\n // Direct text (not descendants') so a leaf's label is visible without dumping\n // the whole subtree's text.\n const ownText = [...el.childNodes]\n .filter((n) => n.nodeType === 3)\n .map((n) => (n.textContent ?? '').trim())\n .join(' ')\n .trim();\n const node: DomNode = {\n tag: el.tagName.toLowerCase(),\n ...(el.id ? { id: el.id } : {}),\n ...(classes ? { classes } : {}),\n ...(Object.keys(attrs).length ? { attrs } : {}),\n rect: { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) },\n ...(ownText ? { text: ownText.slice(0, MAX_TEXT) } : {}),\n };\n if (depth < maxDepth && el.children.length && budget > 0) {\n const children: DomNode[] = [];\n for (const child of el.children) {\n if (budget <= 0) {\n node.truncated = true;\n break;\n }\n children.push(walk(child, depth + 1));\n }\n if (children.length) node.children = children;\n } else if (el.children.length) {\n node.truncated = true;\n }\n return node;\n };\n\n return walk(root, 0);\n}\n\nfunction computedStyle(params: { selector: string; props: string[] }): Record<string, string> | null {\n if (typeof document === 'undefined') return null;\n const el = document.querySelector(params.selector);\n if (!el) return null;\n const cs = getComputedStyle(el);\n const out: Record<string, string> = {};\n for (const p of params.props.slice(0, 50)) out[p] = cs.getPropertyValue(p) || cs[p as keyof CSSStyleDeclaration]?.toString?.() || '';\n return out;\n}\n\nfunction rects(params: { selector: string }): Array<{ x: number; y: number; w: number; h: number }> {\n if (typeof document === 'undefined') return [];\n return [...document.querySelectorAll(params.selector)].slice(0, 200).map((el) => {\n const r = el.getBoundingClientRect();\n return { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) };\n });\n}\n\nlet responderStarted = false;\n\n/** Wire the read-only DOM/layout responder. Idempotent; called lazily once the\n * dev gate turns on. No effect when `document` is absent (non-browser realm). */\nfunction startResponder(): void {\n if (responderStarted || typeof window === 'undefined') return;\n responderStarted = true;\n addListener(DEBUG_QUERY, (msg: { id?: unknown; method?: unknown; params?: unknown }) => {\n if (!enabledChannel.get()) return; // gate: ignore unless dev-enabled\n const id = msg.id;\n const method = msg.method;\n const params = (msg.params ?? {}) as Record<string, unknown>;\n let ok = true;\n let result: unknown = null;\n let error: string | undefined;\n try {\n switch (method) {\n case 'snapshotDom':\n result = snapshotDom(params as never);\n break;\n case 'computedStyle':\n result = computedStyle(params as never);\n break;\n case 'rect':\n result = rects(params as never);\n break;\n default:\n ok = false;\n error = `unknown debug method: ${String(method)}`;\n }\n } catch (e) {\n ok = false;\n error = e instanceof Error ? e.message : String(e);\n }\n try {\n sendMessage(DEBUG_QUERY_RESULT, { id, ok, result, error });\n } catch {\n /* transport gone — nothing to do */\n }\n });\n}\n\n// Start the responder as soon as the gate flips on (and not before).\nenabledChannel.onChange((enabled) => {\n if (enabled) startResponder();\n});\n\n/** The dev-only debug surface. Inert unless the host enables it ({@link isDebugEnabled}). */\nexport const debug = { log, isEnabled: isDebugEnabled } as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BA,yBAAkC;AAClC,0BAAyC;AACzC,sBAMO;AAQP,MAAM,qBAAiB,sCAA2B;AAAA,EAChD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAS,OAAO,IAAI,YAAY,YAAY,IAAI,UAAU;AACpE,CAAC;AAGM,MAAM,iBAAiB,MAAe,eAAe,IAAI;AAIzD,MAAM,kBAAkB,MAAe,eAAe,IAAI;AAKjE,MAAM,iBAAiB,KAAK;AAE5B,SAAS,SAAS,MAAwB;AACxC,MAAI,SAAS,OAAW,QAAO;A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QAAQ;AAAA,IAER;AAAA,EACF,CAAC;AACH;AAGA,eAAe,SAAS,CAAC,YAAY;AACnC,MAAI,QAAS,gBAAe;AAC9B,CAAC;AAGM,MAAM,QAAQ,EAAE,KAAK,WAAW,eAAe;","names":[]}
package/dist/debug.js CHANGED
@@ -1,9 +1,16 @@
1
1
  import "./chunk-VHAA22YE.js";
2
2
  import { createPushChannel } from "./pushChannel";
3
3
  import { sendMessage, addListener } from "./sandboxUtils";
4
+ import {
5
+ DEBUG_ENABLED,
6
+ DEBUG_LOG,
7
+ DEBUG_QUERY,
8
+ DEBUG_QUERY_RESULT,
9
+ REQUEST_DEBUG_ENABLED
10
+ } from "./generated/protocol";
4
11
  const enabledChannel = createPushChannel({
5
- pushType: "debug-enabled",
6
- requestType: "request-debug-enabled",
12
+ pushType: DEBUG_ENABLED,
13
+ requestType: REQUEST_DEBUG_ENABLED,
7
14
  initial: false,
8
15
  parse: (msg) => typeof msg.enabled === "boolean" ? msg.enabled : void 0
9
16
  });
@@ -24,7 +31,7 @@ function safeData(data) {
24
31
  function log(level, message, data) {
25
32
  if (!enabledChannel.get()) return;
26
33
  try {
27
- sendMessage("debug-log", { level, message: String(message), data: safeData(data) });
34
+ sendMessage(DEBUG_LOG, { level, message: String(message), data: safeData(data) });
28
35
  } catch {
29
36
  }
30
37
  }
@@ -96,7 +103,7 @@ let responderStarted = false;
96
103
  function startResponder() {
97
104
  if (responderStarted || typeof window === "undefined") return;
98
105
  responderStarted = true;
99
- addListener("debug-query", (msg) => {
106
+ addListener(DEBUG_QUERY, (msg) => {
100
107
  if (!enabledChannel.get()) return;
101
108
  const id = msg.id;
102
109
  const method = msg.method;
@@ -124,7 +131,7 @@ function startResponder() {
124
131
  error = e instanceof Error ? e.message : String(e);
125
132
  }
126
133
  try {
127
- sendMessage("debug-query-result", { id, ok, result, error });
134
+ sendMessage(DEBUG_QUERY_RESULT, { id, ok, result, error });
128
135
  } catch {
129
136
  }
130
137
  });
package/dist/debug.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/debug.ts"],"sourcesContent":["// System-app devtools — the app-facing surface (plan: docs/plans/system-app-devtools.md).\n//\n// Two opt-in, DEV-ONLY instruments for debugging a sandboxed UI-as-app region:\n// 1. `debug.log(...)` — an app→host one-way log surfaced in the host dev panel\n// / CLI `/debug` stream (instead of hand-fishing console output out of a\n// cross-origin iframe's devtools).\n// 2. a READ-ONLY DOM/layout responder the host can query from outside — the\n// thing a cross-origin screenshot can't reliably give you (a blank capture\n// is ambiguous between a real 0-height collapse and a paint artifact).\n//\n// SECURITY (the gating constraint — see the plan's §0):\n// - Both are inert unless the HOST signals dev mode via the `debug-enabled`\n// channel. The host only sets it for a dev/override session (the `ir-dev-*`\n// deep link) or an explicit operator developer-mode. A published app served\n// to a normal user gets `enabled:false` → `debug.log` is a no-op and the\n// responder never answers. Production isolation is therefore unchanged.\n// - The responder is READ-ONLY with a fixed vocabulary (snapshotDom /\n// computedStyle / rect). There is deliberately NO eval bridge — that would\n// turn a debug aid into remote code execution into the sandbox.\n// - The responder reads only its OWN `document` (it lives in its own opaque\n// iframe and cannot reach a sibling app), so there is no app↔app leak even\n// in dev.\n// - Output is bounded (node/depth/text caps) so a query can't exfiltrate an\n// unbounded payload or wedge the app.\n//\n// Apps that want the strongest guarantee can additionally guard their own usage\n// behind `import.meta.env.DEV` so the calls are tree-shaken from prod bundles;\n// the runtime gate here is the backstop that holds regardless.\n\nimport { createPushChannel } from './pushChannel';\nimport { sendMessage, addListener } from './sandboxUtils';\n\n/** Severity of a {@link debug.log} entry. */\nexport type DebugLevel = 'debug' | 'info' | 'warn' | 'error';\n\n// ── Dev gate ────────────────────────────────────────────────────────────────\n// The host pushes `debug-enabled:true` only for a dev/override session. Until\n// then (and always in production) it stays false and every instrument is inert.\nconst enabledChannel = createPushChannel<boolean>({\n pushType: 'debug-enabled',\n requestType: 'request-debug-enabled',\n initial: false,\n parse: (msg) => (typeof msg.enabled === 'boolean' ? msg.enabled : undefined),\n});\n\n/** Is the host dev-debug surface active for this session? `false` in production. */\nexport const isDebugEnabled = (): boolean => enabledChannel.get();\n\n/** React hook: whether the host dev-debug surface is active (re-renders on change).\n * Handy for showing a debug affordance only when it would do something. */\nexport const useDebugEnabled = (): boolean => enabledChannel.use();\n\n// ── 1. App→host debug log ─────────────────────────────────────────────────────\n// Best-effort: a value that can't be structured-cloned is replaced with a marker\n// rather than throwing — `debug.log` must never break the app.\nconst MAX_DATA_BYTES = 16 * 1024;\n\nfunction safeData(data: unknown): unknown {\n if (data === undefined) return undefined;\n try {\n const json = JSON.stringify(data);\n if (json === undefined) return '[unserializable]';\n if (json.length > MAX_DATA_BYTES) return `[truncated ${json.length}B]`;\n return JSON.parse(json);\n } catch {\n return '[unserializable]';\n }\n}\n\n/**\n * Emit a structured debug entry to the host dev surface. A NO-OP unless the host\n * has enabled the dev-debug session ({@link isDebugEnabled}); in production it\n * does nothing and sends nothing.\n *\n * debug.log('info', 'mounted', { activeFile });\n */\nexport function log(level: DebugLevel, message: string, data?: unknown): void {\n if (!enabledChannel.get()) return; // inert in prod / non-dev sessions\n try {\n sendMessage('debug-log', { level, message: String(message), data: safeData(data) });\n } catch {\n /* transport not ready — drop silently; logging must never throw */\n }\n}\n\n// ── 2. Read-only DOM / layout responder ───────────────────────────────────────\n// The host sends `debug-query` { id, method, params }; we reply with\n// `debug-query-result` { id, ok, result | error }. Only ever active while the dev\n// gate is enabled. Vocabulary is fixed and read-only.\n\ninterface DomNode {\n tag: string;\n id?: string;\n classes?: string[];\n attrs?: Record<string, string>;\n rect?: { x: number; y: number; w: number; h: number };\n text?: string;\n children?: DomNode[];\n truncated?: true;\n}\n\nconst ATTR_ALLOW = new Set(['role', 'aria-hidden', 'data-theme', 'data-active', 'href', 'type', 'hidden']);\nconst MAX_NODES = 2000;\nconst MAX_DEPTH = 25;\nconst MAX_TEXT = 200;\n\nfunction round(n: number): number {\n return Math.round(n);\n}\n\nfunction snapshotDom(params: { selector?: string; maxDepth?: number; maxNodes?: number }): DomNode | null {\n if (typeof document === 'undefined') return null;\n const root = params.selector ? document.querySelector(params.selector) : document.body;\n if (!root) return null;\n const maxDepth = Math.min(params.maxDepth ?? MAX_DEPTH, MAX_DEPTH);\n const maxNodes = Math.min(params.maxNodes ?? MAX_NODES, MAX_NODES);\n let budget = maxNodes;\n\n const walk = (el: Element, depth: number): DomNode => {\n budget--;\n const r = el.getBoundingClientRect();\n const classes = el.classList.length ? [...el.classList] : undefined;\n const attrs: Record<string, string> = {};\n for (const name of el.getAttributeNames()) {\n if (ATTR_ALLOW.has(name)) attrs[name] = el.getAttribute(name) ?? '';\n }\n // Direct text (not descendants') so a leaf's label is visible without dumping\n // the whole subtree's text.\n const ownText = [...el.childNodes]\n .filter((n) => n.nodeType === 3)\n .map((n) => (n.textContent ?? '').trim())\n .join(' ')\n .trim();\n const node: DomNode = {\n tag: el.tagName.toLowerCase(),\n ...(el.id ? { id: el.id } : {}),\n ...(classes ? { classes } : {}),\n ...(Object.keys(attrs).length ? { attrs } : {}),\n rect: { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) },\n ...(ownText ? { text: ownText.slice(0, MAX_TEXT) } : {}),\n };\n if (depth < maxDepth && el.children.length && budget > 0) {\n const children: DomNode[] = [];\n for (const child of el.children) {\n if (budget <= 0) {\n node.truncated = true;\n break;\n }\n children.push(walk(child, depth + 1));\n }\n if (children.length) node.children = children;\n } else if (el.children.length) {\n node.truncated = true;\n }\n return node;\n };\n\n return walk(root, 0);\n}\n\nfunction computedStyle(params: { selector: string; props: string[] }): Record<string, string> | null {\n if (typeof document === 'undefined') return null;\n const el = document.querySelector(params.selector);\n if (!el) return null;\n const cs = getComputedStyle(el);\n const out: Record<string, string> = {};\n for (const p of params.props.slice(0, 50)) out[p] = cs.getPropertyValue(p) || cs[p as keyof CSSStyleDeclaration]?.toString?.() || '';\n return out;\n}\n\nfunction rects(params: { selector: string }): Array<{ x: number; y: number; w: number; h: number }> {\n if (typeof document === 'undefined') return [];\n return [...document.querySelectorAll(params.selector)].slice(0, 200).map((el) => {\n const r = el.getBoundingClientRect();\n return { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) };\n });\n}\n\nlet responderStarted = false;\n\n/** Wire the read-only DOM/layout responder. Idempotent; called lazily once the\n * dev gate turns on. No effect when `document` is absent (non-browser realm). */\nfunction startResponder(): void {\n if (responderStarted || typeof window === 'undefined') return;\n responderStarted = true;\n addListener('debug-query', (msg: { id?: unknown; method?: unknown; params?: unknown }) => {\n if (!enabledChannel.get()) return; // gate: ignore unless dev-enabled\n const id = msg.id;\n const method = msg.method;\n const params = (msg.params ?? {}) as Record<string, unknown>;\n let ok = true;\n let result: unknown = null;\n let error: string | undefined;\n try {\n switch (method) {\n case 'snapshotDom':\n result = snapshotDom(params as never);\n break;\n case 'computedStyle':\n result = computedStyle(params as never);\n break;\n case 'rect':\n result = rects(params as never);\n break;\n default:\n ok = false;\n error = `unknown debug method: ${String(method)}`;\n }\n } catch (e) {\n ok = false;\n error = e instanceof Error ? e.message : String(e);\n }\n try {\n sendMessage('debug-query-result', { id, ok, result, error });\n } catch {\n /* transport gone — nothing to do */\n }\n });\n}\n\n// Start the responder as soon as the gate flips on (and not before).\nenabledChannel.onChange((enabled) => {\n if (enabled) startResponder();\n});\n\n/** The dev-only debug surface. Inert unless the host enables it ({@link isDebugEnabled}). */\nexport const debug = { log, isEnabled: isDebugEnabled } as const;\n"],"mappings":";AA6BA,SAAS,yBAAyB;AAClC,SAAS,aAAa,mBAAmB;AAQzC,MAAM,iBAAiB,kBAA2B;AAAA,EAChD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAS,OAAO,IAAI,YAAY,YAAY,IAAI,UAAU;AACpE,CAAC;AAGM,MAAM,iBAAiB,MAAe,eAAe,IAAI;AAIzD,MAAM,kBAAkB,MAAe,eAAe,IAAI;AAKjE,MAAM,iBAAiB,KAAK;AAE5B,SAAS,SAAS,MAAwB;AACxC,MAAI,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C;AAAA,IAC7D,QAAQ;AAAA,IAER;AAAA,EACF,CAAC;AACH;AAGA,eAAe,SAAS,CAAC,YAAY;AACnC,MAAI,QAAS,gBAAe;AAC9B,CAAC;AAGM,MAAM,QAAQ,EAAE,KAAK,WAAW,eAAe;","names":[]}
1
+ {"version":3,"sources":["../src/debug.ts"],"sourcesContent":["// System-app devtools — the app-facing surface (plan: docs/plans/system-app-devtools.md).\n//\n// Two opt-in, DEV-ONLY instruments for debugging a sandboxed UI-as-app region:\n// 1. `debug.log(...)` — an app→host one-way log surfaced in the host dev panel\n// / CLI `/debug` stream (instead of hand-fishing console output out of a\n// cross-origin iframe's devtools).\n// 2. a READ-ONLY DOM/layout responder the host can query from outside — the\n// thing a cross-origin screenshot can't reliably give you (a blank capture\n// is ambiguous between a real 0-height collapse and a paint artifact).\n//\n// SECURITY (the gating constraint — see the plan's §0):\n// - Both are inert unless the HOST signals dev mode via the `debug-enabled`\n// channel. The host only sets it for a dev/override session (the `ir-dev-*`\n// deep link) or an explicit operator developer-mode. A published app served\n// to a normal user gets `enabled:false` → `debug.log` is a no-op and the\n// responder never answers. Production isolation is therefore unchanged.\n// - The responder is READ-ONLY with a fixed vocabulary (snapshotDom /\n// computedStyle / rect). There is deliberately NO eval bridge — that would\n// turn a debug aid into remote code execution into the sandbox.\n// - The responder reads only its OWN `document` (it lives in its own opaque\n// iframe and cannot reach a sibling app), so there is no app↔app leak even\n// in dev.\n// - Output is bounded (node/depth/text caps) so a query can't exfiltrate an\n// unbounded payload or wedge the app.\n//\n// Apps that want the strongest guarantee can additionally guard their own usage\n// behind `import.meta.env.DEV` so the calls are tree-shaken from prod bundles;\n// the runtime gate here is the backstop that holds regardless.\n\nimport { createPushChannel } from './pushChannel';\nimport { sendMessage, addListener } from './sandboxUtils';\nimport {\n DEBUG_ENABLED,\n DEBUG_LOG,\n DEBUG_QUERY,\n DEBUG_QUERY_RESULT,\n REQUEST_DEBUG_ENABLED,\n} from './generated/protocol';\n\n/** Severity of a {@link debug.log} entry. */\nexport type DebugLevel = 'debug' | 'info' | 'warn' | 'error';\n\n// ── Dev gate ────────────────────────────────────────────────────────────────\n// The host pushes `debug-enabled:true` only for a dev/override session. Until\n// then (and always in production) it stays false and every instrument is inert.\nconst enabledChannel = createPushChannel<boolean>({\n pushType: DEBUG_ENABLED,\n requestType: REQUEST_DEBUG_ENABLED,\n initial: false,\n parse: (msg) => (typeof msg.enabled === 'boolean' ? msg.enabled : undefined),\n});\n\n/** Is the host dev-debug surface active for this session? `false` in production. */\nexport const isDebugEnabled = (): boolean => enabledChannel.get();\n\n/** React hook: whether the host dev-debug surface is active (re-renders on change).\n * Handy for showing a debug affordance only when it would do something. */\nexport const useDebugEnabled = (): boolean => enabledChannel.use();\n\n// ── 1. App→host debug log ─────────────────────────────────────────────────────\n// Best-effort: a value that can't be structured-cloned is replaced with a marker\n// rather than throwing — `debug.log` must never break the app.\nconst MAX_DATA_BYTES = 16 * 1024;\n\nfunction safeData(data: unknown): unknown {\n if (data === undefined) return undefined;\n try {\n const json = JSON.stringify(data);\n if (json === undefined) return '[unserializable]';\n if (json.length > MAX_DATA_BYTES) return `[truncated ${json.length}B]`;\n return JSON.parse(json);\n } catch {\n return '[unserializable]';\n }\n}\n\n/**\n * Emit a structured debug entry to the host dev surface. A NO-OP unless the host\n * has enabled the dev-debug session ({@link isDebugEnabled}); in production it\n * does nothing and sends nothing.\n *\n * debug.log('info', 'mounted', { activeFile });\n */\nexport function log(level: DebugLevel, message: string, data?: unknown): void {\n if (!enabledChannel.get()) return; // inert in prod / non-dev sessions\n try {\n sendMessage(DEBUG_LOG, { level, message: String(message), data: safeData(data) });\n } catch {\n /* transport not ready — drop silently; logging must never throw */\n }\n}\n\n// ── 2. Read-only DOM / layout responder ───────────────────────────────────────\n// The host sends `debug-query` { id, method, params }; we reply with\n// `debug-query-result` { id, ok, result | error }. Only ever active while the dev\n// gate is enabled. Vocabulary is fixed and read-only.\n\ninterface DomNode {\n tag: string;\n id?: string;\n classes?: string[];\n attrs?: Record<string, string>;\n rect?: { x: number; y: number; w: number; h: number };\n text?: string;\n children?: DomNode[];\n truncated?: true;\n}\n\nconst ATTR_ALLOW = new Set(['role', 'aria-hidden', 'data-theme', 'data-active', 'href', 'type', 'hidden']);\nconst MAX_NODES = 2000;\nconst MAX_DEPTH = 25;\nconst MAX_TEXT = 200;\n\nfunction round(n: number): number {\n return Math.round(n);\n}\n\nfunction snapshotDom(params: { selector?: string; maxDepth?: number; maxNodes?: number }): DomNode | null {\n if (typeof document === 'undefined') return null;\n const root = params.selector ? document.querySelector(params.selector) : document.body;\n if (!root) return null;\n const maxDepth = Math.min(params.maxDepth ?? MAX_DEPTH, MAX_DEPTH);\n const maxNodes = Math.min(params.maxNodes ?? MAX_NODES, MAX_NODES);\n let budget = maxNodes;\n\n const walk = (el: Element, depth: number): DomNode => {\n budget--;\n const r = el.getBoundingClientRect();\n const classes = el.classList.length ? [...el.classList] : undefined;\n const attrs: Record<string, string> = {};\n for (const name of el.getAttributeNames()) {\n if (ATTR_ALLOW.has(name)) attrs[name] = el.getAttribute(name) ?? '';\n }\n // Direct text (not descendants') so a leaf's label is visible without dumping\n // the whole subtree's text.\n const ownText = [...el.childNodes]\n .filter((n) => n.nodeType === 3)\n .map((n) => (n.textContent ?? '').trim())\n .join(' ')\n .trim();\n const node: DomNode = {\n tag: el.tagName.toLowerCase(),\n ...(el.id ? { id: el.id } : {}),\n ...(classes ? { classes } : {}),\n ...(Object.keys(attrs).length ? { attrs } : {}),\n rect: { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) },\n ...(ownText ? { text: ownText.slice(0, MAX_TEXT) } : {}),\n };\n if (depth < maxDepth && el.children.length && budget > 0) {\n const children: DomNode[] = [];\n for (const child of el.children) {\n if (budget <= 0) {\n node.truncated = true;\n break;\n }\n children.push(walk(child, depth + 1));\n }\n if (children.length) node.children = children;\n } else if (el.children.length) {\n node.truncated = true;\n }\n return node;\n };\n\n return walk(root, 0);\n}\n\nfunction computedStyle(params: { selector: string; props: string[] }): Record<string, string> | null {\n if (typeof document === 'undefined') return null;\n const el = document.querySelector(params.selector);\n if (!el) return null;\n const cs = getComputedStyle(el);\n const out: Record<string, string> = {};\n for (const p of params.props.slice(0, 50)) out[p] = cs.getPropertyValue(p) || cs[p as keyof CSSStyleDeclaration]?.toString?.() || '';\n return out;\n}\n\nfunction rects(params: { selector: string }): Array<{ x: number; y: number; w: number; h: number }> {\n if (typeof document === 'undefined') return [];\n return [...document.querySelectorAll(params.selector)].slice(0, 200).map((el) => {\n const r = el.getBoundingClientRect();\n return { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height) };\n });\n}\n\nlet responderStarted = false;\n\n/** Wire the read-only DOM/layout responder. Idempotent; called lazily once the\n * dev gate turns on. No effect when `document` is absent (non-browser realm). */\nfunction startResponder(): void {\n if (responderStarted || typeof window === 'undefined') return;\n responderStarted = true;\n addListener(DEBUG_QUERY, (msg: { id?: unknown; method?: unknown; params?: unknown }) => {\n if (!enabledChannel.get()) return; // gate: ignore unless dev-enabled\n const id = msg.id;\n const method = msg.method;\n const params = (msg.params ?? {}) as Record<string, unknown>;\n let ok = true;\n let result: unknown = null;\n let error: string | undefined;\n try {\n switch (method) {\n case 'snapshotDom':\n result = snapshotDom(params as never);\n break;\n case 'computedStyle':\n result = computedStyle(params as never);\n break;\n case 'rect':\n result = rects(params as never);\n break;\n default:\n ok = false;\n error = `unknown debug method: ${String(method)}`;\n }\n } catch (e) {\n ok = false;\n error = e instanceof Error ? e.message : String(e);\n }\n try {\n sendMessage(DEBUG_QUERY_RESULT, { id, ok, result, error });\n } catch {\n /* transport gone — nothing to do */\n }\n });\n}\n\n// Start the responder as soon as the gate flips on (and not before).\nenabledChannel.onChange((enabled) => {\n if (enabled) startResponder();\n});\n\n/** The dev-only debug surface. Inert unless the host enables it ({@link isDebugEnabled}). */\nexport const debug = { log, isEnabled: isDebugEnabled } as const;\n"],"mappings":";AA6BA,SAAS,yBAAyB;AAClC,SAAS,aAAa,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AQ;AAAA,QACd,KAAK;AACH,mBAAS,YAAY,MAAe;AACpC;AAAA,QACF,KAAK;AACH,mBAAS,cAAc,MAAe;AACtC;AAAA,QACF,KAAK;AACH,mBAAS,MAAM,MAAe;AAC9B;AAAA,QACF;AACE,eAAK;AACL,kBAAQ,yBAAyB,OAAO,MAAM,CAAC;AAAA,MACnD;AAAA,IACF,SAAS,GAAG;AACV,WAAK;AACL,cAAQ,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AAAA,IACnD;AACA,QAAI;AACF,kBAAY,oBAAoB,EAAE,IAAI,IAAI,QAAQ,MAAM,CAAC;AAAA,IAC3D,QAAQ;AAAA,IAER;AAAA,EACF,CAAC;AACH;AAGA,eAAe,SAAS,CAAC,YAAY;AACnC,MAAI,QAAS,gBAAe;AAC9B,CAAC;AAGM,MAAM,QAAQ,EAAE,KAAK,WAAW,eAAe;","names":[]}
@@ -24,10 +24,11 @@ __export(diagnostics_exports, {
24
24
  });
25
25
  module.exports = __toCommonJS(diagnostics_exports);
26
26
  var import_pushChannel = require("./pushChannel");
27
+ var import_protocol = require("./generated/protocol");
27
28
  const EMPTY = { buildErrors: [], consoleEntries: [], provenance: null };
28
29
  const channel = (0, import_pushChannel.createPushChannel)({
29
- pushType: "diagnostics",
30
- requestType: "request-diagnostics",
30
+ pushType: import_protocol.DIAGNOSTICS,
31
+ requestType: import_protocol.REQUEST_DIAGNOSTICS,
31
32
  initial: EMPTY,
32
33
  parse: (msg) => {
33
34
  if (!Array.isArray(msg.buildErrors) || !Array.isArray(msg.consoleEntries)) return void 0;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/diagnostics.ts"],"sourcesContent":["// The `diagnostics:read` channel — app-facing surface (LLM_AND_AGENTS_SPEC §3.3/§4,\n// D4; roadmap R3-74 / P3-72).\n//\n// A *sibling* agent app (one holding `diagnostics:read`) observes the result of its\n// edits to the PREVIEWED app: the build/transpile errors from the sandbox bundler\n// and the previewed app's captured `console.*`. This is the in-browser analogue of\n// a local coding agent reading compiler/test output (P3-73's `get_diagnostics()`\n// tool). Read-only and scoped host-side to the paired previewed app's OWN\n// diagnostics — never another app's (the host channel projection enforces it; the\n// previewed app itself holds no `diagnostics:read`, so it is origin-excluded).\n//\n// Recipe-A push channel, identical get/onChange/use trio as `secrets`/`catalog`:\n// the host pushes `diagnostics` on change and answers a `request-diagnostics` poll,\n// gated per-frame by the read ACL. Inert until the host wires the channel\n// (site-main `channelBridge`); the contract ships here so the agent app (P3-73) can\n// be written against it.\nimport { createPushChannel } from './pushChannel';\n\n/** One build/transpile error from the sandbox bundler's compile of the previewed\n * app. `path` is repo-relative (leading slash) when the error is file-located. */\nexport interface BuildError {\n message: string;\n path?: string;\n line?: number;\n column?: number;\n}\n\n/** The `console.*` method a captured entry came from. */\nexport type ConsoleLevel = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\n/** One captured `console.*` entry from the previewed app. The host renders the\n * console arguments to text host-side — the agent never receives live object\n * handles across the boundary. */\nexport interface ConsoleEntry {\n level: ConsoleLevel;\n text: string;\n /** Host-side timestamp (ms) at capture. */\n at: number;\n}\n\n/** Provenance (D4 / EDITOR_AS_APP_SPEC §12.3): WHICH previewed app + compile this\n * snapshot describes, so a consumer can tell stale output from fresh and never\n * conflates two apps' diagnostics. `null` until a first compile is observed. */\nexport interface DiagnosticsProvenance {\n /** The previewed app's stable key (`provider/ns/repo`). */\n appKey?: string;\n /** Monotonic id of the compile that produced these build errors. */\n compileId?: string;\n}\n\n/** A snapshot of the previewed app's diagnostics: its build errors, captured\n * console output, and the {@link DiagnosticsProvenance} of the compile. */\nexport interface Diagnostics {\n buildErrors: BuildError[];\n consoleEntries: ConsoleEntry[];\n provenance: DiagnosticsProvenance | null;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `diagnostics:read`): an empty, provenance-less snapshot. */\nconst EMPTY: Diagnostics = { buildErrors: [], consoleEntries: [], provenance: null };\n\nconst channel = createPushChannel<Diagnostics>({\n pushType: 'diagnostics',\n requestType: 'request-diagnostics',\n initial: EMPTY,\n parse: (msg) => {\n // Require both arrays; tolerate an absent/partial provenance. A malformed push\n // is ignored (returns undefined) so the last good snapshot stands.\n if (!Array.isArray(msg.buildErrors) || !Array.isArray(msg.consoleEntries)) return undefined;\n const provenance =\n msg.provenance && typeof msg.provenance === 'object'\n ? (msg.provenance as DiagnosticsProvenance)\n : null;\n return {\n buildErrors: msg.buildErrors as BuildError[],\n consoleEntries: msg.consoleEntries as ConsoleEntry[],\n provenance,\n };\n },\n});\n\n/** One-off read of the previewed app's current diagnostics. Returns the empty\n * snapshot until the host answers (or if the app lacks `diagnostics:read`). Use\n * {@link onDiagnosticsChange}/{@link useDiagnostics} to react to live updates. */\nexport const getDiagnostics = (): Diagnostics => channel.get();\n\n/** Subscribe to diagnostics. Invoked immediately with the current value, then on\n * every host push. Returns an unsubscribe. */\nexport const onDiagnosticsChange = (listener: (d: Diagnostics) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current diagnostics, re-rendering on every change. */\nexport const useDiagnostics = (): Diagnostics => channel.use();\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,yBAAkC;AA4ClC,MAAM,QAAqB,EAAE,aAAa,CAAC,GAAG,gBAAgB,CAAC,GAAG,YAAY,KAAK;AAEnF,MAAM,cAAU,sCAA+B;AAAA,EAC7C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,MAAM,QAAQ,IAAI,WAAW,KAAK,CAAC,MAAM,QAAQ,IAAI,cAAc,EAAG,QAAO;AAClF,UAAM,aACJ,IAAI,cAAc,OAAO,IAAI,eAAe,WACvC,IAAI,aACL;AACN,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,MACjB,gBAAgB,IAAI;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAKM,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;AAItD,MAAM,sBAAsB,CAAC,aAClC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;","names":[]}
1
+ {"version":3,"sources":["../src/diagnostics.ts"],"sourcesContent":["// The `diagnostics:read` channel — app-facing surface (LLM_AND_AGENTS_SPEC §3.3/§4,\n// D4; roadmap R3-74 / P3-72).\n//\n// A *sibling* agent app (one holding `diagnostics:read`) observes the result of its\n// edits to the PREVIEWED app: the build/transpile errors from the sandbox bundler\n// and the previewed app's captured `console.*`. This is the in-browser analogue of\n// a local coding agent reading compiler/test output (P3-73's `get_diagnostics()`\n// tool). Read-only and scoped host-side to the paired previewed app's OWN\n// diagnostics — never another app's (the host channel projection enforces it; the\n// previewed app itself holds no `diagnostics:read`, so it is origin-excluded).\n//\n// Recipe-A push channel, identical get/onChange/use trio as `secrets`/`catalog`:\n// the host pushes `diagnostics` on change and answers a `request-diagnostics` poll,\n// gated per-frame by the read ACL. Inert until the host wires the channel\n// (site-main `channelBridge`); the contract ships here so the agent app (P3-73) can\n// be written against it.\nimport { createPushChannel } from './pushChannel';\nimport { DIAGNOSTICS, REQUEST_DIAGNOSTICS } from './generated/protocol';\n\n/** One build/transpile error from the sandbox bundler's compile of the previewed\n * app. `path` is repo-relative (leading slash) when the error is file-located. */\nexport interface BuildError {\n message: string;\n path?: string;\n line?: number;\n column?: number;\n}\n\n/** The `console.*` method a captured entry came from. */\nexport type ConsoleLevel = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\n/** One captured `console.*` entry from the previewed app. The host renders the\n * console arguments to text host-side — the agent never receives live object\n * handles across the boundary. */\nexport interface ConsoleEntry {\n level: ConsoleLevel;\n text: string;\n /** Host-side timestamp (ms) at capture. */\n at: number;\n}\n\n/** Provenance (D4 / EDITOR_AS_APP_SPEC §12.3): WHICH previewed app + compile this\n * snapshot describes, so a consumer can tell stale output from fresh and never\n * conflates two apps' diagnostics. `null` until a first compile is observed. */\nexport interface DiagnosticsProvenance {\n /** The previewed app's stable key (`provider/ns/repo`). */\n appKey?: string;\n /** Monotonic id of the compile that produced these build errors. */\n compileId?: string;\n}\n\n/** A snapshot of the previewed app's diagnostics: its build errors, captured\n * console output, and the {@link DiagnosticsProvenance} of the compile. */\nexport interface Diagnostics {\n buildErrors: BuildError[];\n consoleEntries: ConsoleEntry[];\n provenance: DiagnosticsProvenance | null;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `diagnostics:read`): an empty, provenance-less snapshot. */\nconst EMPTY: Diagnostics = { buildErrors: [], consoleEntries: [], provenance: null };\n\nconst channel = createPushChannel<Diagnostics>({\n pushType: DIAGNOSTICS,\n requestType: REQUEST_DIAGNOSTICS,\n initial: EMPTY,\n parse: (msg) => {\n // Require both arrays; tolerate an absent/partial provenance. A malformed push\n // is ignored (returns undefined) so the last good snapshot stands.\n if (!Array.isArray(msg.buildErrors) || !Array.isArray(msg.consoleEntries)) return undefined;\n const provenance =\n msg.provenance && typeof msg.provenance === 'object'\n ? (msg.provenance as DiagnosticsProvenance)\n : null;\n return {\n buildErrors: msg.buildErrors as BuildError[],\n consoleEntries: msg.consoleEntries as ConsoleEntry[],\n provenance,\n };\n },\n});\n\n/** One-off read of the previewed app's current diagnostics. Returns the empty\n * snapshot until the host answers (or if the app lacks `diagnostics:read`). Use\n * {@link onDiagnosticsChange}/{@link useDiagnostics} to react to live updates. */\nexport const getDiagnostics = (): Diagnostics => channel.get();\n\n/** Subscribe to diagnostics. Invoked immediately with the current value, then on\n * every host push. Returns an unsubscribe. */\nexport const onDiagnosticsChange = (listener: (d: Diagnostics) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current diagnostics, re-rendering on every change. */\nexport const useDiagnostics = (): Diagnostics => channel.use();\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,yBAAkC;AAClC,sBAAiD;AA4CjD,MAAM,QAAqB,EAAE,aAAa,CAAC,GAAG,gBAAgB,CAAC,GAAG,YAAY,KAAK;AAEnF,MAAM,cAAU,sCAA+B;AAAA,EAC7C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,MAAM,QAAQ,IAAI,WAAW,KAAK,CAAC,MAAM,QAAQ,IAAI,cAAc,EAAG,QAAO;AAClF,UAAM,aACJ,IAAI,cAAc,OAAO,IAAI,eAAe,WACvC,IAAI,aACL;AACN,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,MACjB,gBAAgB,IAAI;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAKM,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;AAItD,MAAM,sBAAsB,CAAC,aAClC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;","names":[]}
@@ -1,9 +1,10 @@
1
1
  import "./chunk-VHAA22YE.js";
2
2
  import { createPushChannel } from "./pushChannel";
3
+ import { DIAGNOSTICS, REQUEST_DIAGNOSTICS } from "./generated/protocol";
3
4
  const EMPTY = { buildErrors: [], consoleEntries: [], provenance: null };
4
5
  const channel = createPushChannel({
5
- pushType: "diagnostics",
6
- requestType: "request-diagnostics",
6
+ pushType: DIAGNOSTICS,
7
+ requestType: REQUEST_DIAGNOSTICS,
7
8
  initial: EMPTY,
8
9
  parse: (msg) => {
9
10
  if (!Array.isArray(msg.buildErrors) || !Array.isArray(msg.consoleEntries)) return void 0;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/diagnostics.ts"],"sourcesContent":["// The `diagnostics:read` channel — app-facing surface (LLM_AND_AGENTS_SPEC §3.3/§4,\n// D4; roadmap R3-74 / P3-72).\n//\n// A *sibling* agent app (one holding `diagnostics:read`) observes the result of its\n// edits to the PREVIEWED app: the build/transpile errors from the sandbox bundler\n// and the previewed app's captured `console.*`. This is the in-browser analogue of\n// a local coding agent reading compiler/test output (P3-73's `get_diagnostics()`\n// tool). Read-only and scoped host-side to the paired previewed app's OWN\n// diagnostics — never another app's (the host channel projection enforces it; the\n// previewed app itself holds no `diagnostics:read`, so it is origin-excluded).\n//\n// Recipe-A push channel, identical get/onChange/use trio as `secrets`/`catalog`:\n// the host pushes `diagnostics` on change and answers a `request-diagnostics` poll,\n// gated per-frame by the read ACL. Inert until the host wires the channel\n// (site-main `channelBridge`); the contract ships here so the agent app (P3-73) can\n// be written against it.\nimport { createPushChannel } from './pushChannel';\n\n/** One build/transpile error from the sandbox bundler's compile of the previewed\n * app. `path` is repo-relative (leading slash) when the error is file-located. */\nexport interface BuildError {\n message: string;\n path?: string;\n line?: number;\n column?: number;\n}\n\n/** The `console.*` method a captured entry came from. */\nexport type ConsoleLevel = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\n/** One captured `console.*` entry from the previewed app. The host renders the\n * console arguments to text host-side — the agent never receives live object\n * handles across the boundary. */\nexport interface ConsoleEntry {\n level: ConsoleLevel;\n text: string;\n /** Host-side timestamp (ms) at capture. */\n at: number;\n}\n\n/** Provenance (D4 / EDITOR_AS_APP_SPEC §12.3): WHICH previewed app + compile this\n * snapshot describes, so a consumer can tell stale output from fresh and never\n * conflates two apps' diagnostics. `null` until a first compile is observed. */\nexport interface DiagnosticsProvenance {\n /** The previewed app's stable key (`provider/ns/repo`). */\n appKey?: string;\n /** Monotonic id of the compile that produced these build errors. */\n compileId?: string;\n}\n\n/** A snapshot of the previewed app's diagnostics: its build errors, captured\n * console output, and the {@link DiagnosticsProvenance} of the compile. */\nexport interface Diagnostics {\n buildErrors: BuildError[];\n consoleEntries: ConsoleEntry[];\n provenance: DiagnosticsProvenance | null;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `diagnostics:read`): an empty, provenance-less snapshot. */\nconst EMPTY: Diagnostics = { buildErrors: [], consoleEntries: [], provenance: null };\n\nconst channel = createPushChannel<Diagnostics>({\n pushType: 'diagnostics',\n requestType: 'request-diagnostics',\n initial: EMPTY,\n parse: (msg) => {\n // Require both arrays; tolerate an absent/partial provenance. A malformed push\n // is ignored (returns undefined) so the last good snapshot stands.\n if (!Array.isArray(msg.buildErrors) || !Array.isArray(msg.consoleEntries)) return undefined;\n const provenance =\n msg.provenance && typeof msg.provenance === 'object'\n ? (msg.provenance as DiagnosticsProvenance)\n : null;\n return {\n buildErrors: msg.buildErrors as BuildError[],\n consoleEntries: msg.consoleEntries as ConsoleEntry[],\n provenance,\n };\n },\n});\n\n/** One-off read of the previewed app's current diagnostics. Returns the empty\n * snapshot until the host answers (or if the app lacks `diagnostics:read`). Use\n * {@link onDiagnosticsChange}/{@link useDiagnostics} to react to live updates. */\nexport const getDiagnostics = (): Diagnostics => channel.get();\n\n/** Subscribe to diagnostics. Invoked immediately with the current value, then on\n * every host push. Returns an unsubscribe. */\nexport const onDiagnosticsChange = (listener: (d: Diagnostics) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current diagnostics, re-rendering on every change. */\nexport const useDiagnostics = (): Diagnostics => channel.use();\n"],"mappings":";AAgBA,SAAS,yBAAyB;AA4ClC,MAAM,QAAqB,EAAE,aAAa,CAAC,GAAG,gBAAgB,CAAC,GAAG,YAAY,KAAK;AAEnF,MAAM,UAAU,kBAA+B;AAAA,EAC7C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,MAAM,QAAQ,IAAI,WAAW,KAAK,CAAC,MAAM,QAAQ,IAAI,cAAc,EAAG,QAAO;AAClF,UAAM,aACJ,IAAI,cAAc,OAAO,IAAI,eAAe,WACvC,IAAI,aACL;AACN,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,MACjB,gBAAgB,IAAI;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAKM,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;AAItD,MAAM,sBAAsB,CAAC,aAClC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;","names":[]}
1
+ {"version":3,"sources":["../src/diagnostics.ts"],"sourcesContent":["// The `diagnostics:read` channel — app-facing surface (LLM_AND_AGENTS_SPEC §3.3/§4,\n// D4; roadmap R3-74 / P3-72).\n//\n// A *sibling* agent app (one holding `diagnostics:read`) observes the result of its\n// edits to the PREVIEWED app: the build/transpile errors from the sandbox bundler\n// and the previewed app's captured `console.*`. This is the in-browser analogue of\n// a local coding agent reading compiler/test output (P3-73's `get_diagnostics()`\n// tool). Read-only and scoped host-side to the paired previewed app's OWN\n// diagnostics — never another app's (the host channel projection enforces it; the\n// previewed app itself holds no `diagnostics:read`, so it is origin-excluded).\n//\n// Recipe-A push channel, identical get/onChange/use trio as `secrets`/`catalog`:\n// the host pushes `diagnostics` on change and answers a `request-diagnostics` poll,\n// gated per-frame by the read ACL. Inert until the host wires the channel\n// (site-main `channelBridge`); the contract ships here so the agent app (P3-73) can\n// be written against it.\nimport { createPushChannel } from './pushChannel';\nimport { DIAGNOSTICS, REQUEST_DIAGNOSTICS } from './generated/protocol';\n\n/** One build/transpile error from the sandbox bundler's compile of the previewed\n * app. `path` is repo-relative (leading slash) when the error is file-located. */\nexport interface BuildError {\n message: string;\n path?: string;\n line?: number;\n column?: number;\n}\n\n/** The `console.*` method a captured entry came from. */\nexport type ConsoleLevel = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\n/** One captured `console.*` entry from the previewed app. The host renders the\n * console arguments to text host-side — the agent never receives live object\n * handles across the boundary. */\nexport interface ConsoleEntry {\n level: ConsoleLevel;\n text: string;\n /** Host-side timestamp (ms) at capture. */\n at: number;\n}\n\n/** Provenance (D4 / EDITOR_AS_APP_SPEC §12.3): WHICH previewed app + compile this\n * snapshot describes, so a consumer can tell stale output from fresh and never\n * conflates two apps' diagnostics. `null` until a first compile is observed. */\nexport interface DiagnosticsProvenance {\n /** The previewed app's stable key (`provider/ns/repo`). */\n appKey?: string;\n /** Monotonic id of the compile that produced these build errors. */\n compileId?: string;\n}\n\n/** A snapshot of the previewed app's diagnostics: its build errors, captured\n * console output, and the {@link DiagnosticsProvenance} of the compile. */\nexport interface Diagnostics {\n buildErrors: BuildError[];\n consoleEntries: ConsoleEntry[];\n provenance: DiagnosticsProvenance | null;\n}\n\n/** Value before the host answers — also the value when the app may not read the\n * channel (no `diagnostics:read`): an empty, provenance-less snapshot. */\nconst EMPTY: Diagnostics = { buildErrors: [], consoleEntries: [], provenance: null };\n\nconst channel = createPushChannel<Diagnostics>({\n pushType: DIAGNOSTICS,\n requestType: REQUEST_DIAGNOSTICS,\n initial: EMPTY,\n parse: (msg) => {\n // Require both arrays; tolerate an absent/partial provenance. A malformed push\n // is ignored (returns undefined) so the last good snapshot stands.\n if (!Array.isArray(msg.buildErrors) || !Array.isArray(msg.consoleEntries)) return undefined;\n const provenance =\n msg.provenance && typeof msg.provenance === 'object'\n ? (msg.provenance as DiagnosticsProvenance)\n : null;\n return {\n buildErrors: msg.buildErrors as BuildError[],\n consoleEntries: msg.consoleEntries as ConsoleEntry[],\n provenance,\n };\n },\n});\n\n/** One-off read of the previewed app's current diagnostics. Returns the empty\n * snapshot until the host answers (or if the app lacks `diagnostics:read`). Use\n * {@link onDiagnosticsChange}/{@link useDiagnostics} to react to live updates. */\nexport const getDiagnostics = (): Diagnostics => channel.get();\n\n/** Subscribe to diagnostics. Invoked immediately with the current value, then on\n * every host push. Returns an unsubscribe. */\nexport const onDiagnosticsChange = (listener: (d: Diagnostics) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current diagnostics, re-rendering on every change. */\nexport const useDiagnostics = (): Diagnostics => channel.use();\n"],"mappings":";AAgBA,SAAS,yBAAyB;AAClC,SAAS,aAAa,2BAA2B;AA4CjD,MAAM,QAAqB,EAAE,aAAa,CAAC,GAAG,gBAAgB,CAAC,GAAG,YAAY,KAAK;AAEnF,MAAM,UAAU,kBAA+B;AAAA,EAC7C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AAGd,QAAI,CAAC,MAAM,QAAQ,IAAI,WAAW,KAAK,CAAC,MAAM,QAAQ,IAAI,cAAc,EAAG,QAAO;AAClF,UAAM,aACJ,IAAI,cAAc,OAAO,IAAI,eAAe,WACvC,IAAI,aACL;AACN,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,MACjB,gBAAgB,IAAI;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAKM,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;AAItD,MAAM,sBAAsB,CAAC,aAClC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,iBAAiB,MAAmB,QAAQ,IAAI;","names":[]}
package/dist/dnd.cjs CHANGED
@@ -26,8 +26,10 @@ __export(dnd_exports, {
26
26
  module.exports = __toCommonJS(dnd_exports);
27
27
  var import_react = require("react");
28
28
  var import_sandboxUtils = require("./sandboxUtils");
29
+ var import_protocol = require("./generated/protocol");
30
+ var import_protocolSchemes = require("./protocolSchemes");
29
31
  const startItemDrag = async (item) => {
30
- const res = await (0, import_sandboxUtils.protocolRequest)("dnd", "startDrag", [item]);
32
+ const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_DND], "startDrag", [item]);
31
33
  if (!res || res.ok !== true) {
32
34
  const err = new Error(res?.message ?? "dnd startDrag failed");
33
35
  err.code = res?.code ?? "unknown";
@@ -35,10 +37,10 @@ const startItemDrag = async (item) => {
35
37
  }
36
38
  };
37
39
  const cancelItemDrag = () => {
38
- (0, import_sandboxUtils.sendMessage)("dnd-cancel", {});
40
+ (0, import_sandboxUtils.sendMessage)(import_protocol.DND_CANCEL, {});
39
41
  };
40
42
  const onItemDrop = (listener) => (0, import_sandboxUtils.addListener)(
41
- "dropped-item",
43
+ import_protocol.DROPPED_ITEM,
42
44
  (m) => listener({ item: m.item, from: m.from, position: m.position })
43
45
  );
44
46
  const useDroppedItem = () => {