@atmem/architect 0.0.0-stage → 0.2.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 (512) hide show
  1. package/CONSTITUTION.md +144 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +6 -0
  4. package/README.md +31 -2
  5. package/agent-skills/discovery/SKILL.md +48 -0
  6. package/agent-skills/discovery/topics.json +139 -0
  7. package/agent-skills/generation-capabilities.json +760 -0
  8. package/agent-skills/service-lifecycle.json +21 -0
  9. package/agent-skills/specialists/architecture/SKILL.md +15 -0
  10. package/agent-skills/specialists/aws/SKILL.md +17 -0
  11. package/agent-skills/specialists/azure/SKILL.md +7 -0
  12. package/agent-skills/specialists/composition/SKILL.md +17 -0
  13. package/agent-skills/specialists/devops/SKILL.md +10 -0
  14. package/agent-skills/specialists/finops/SKILL.md +7 -0
  15. package/agent-skills/specialists/gcp/SKILL.md +7 -0
  16. package/agent-skills/specialists/ibm/SKILL.md +7 -0
  17. package/agent-skills/specialists/manifest.json +13 -0
  18. package/agent-skills/specialists/pulumi/SKILL.md +7 -0
  19. package/agent-skills/specialists/security/SKILL.md +7 -0
  20. package/agent-skills/specialists/terraform/SKILL.md +14 -0
  21. package/agent-skills/upstream/aws/LICENSE +175 -0
  22. package/agent-skills/upstream/aws/SKILL.md +125 -0
  23. package/agent-skills/upstream/azure/LICENSE +21 -0
  24. package/agent-skills/upstream/azure/SKILL.md +387 -0
  25. package/agent-skills/upstream/gcp/LICENSE +202 -0
  26. package/agent-skills/upstream/gcp/SKILL.md +159 -0
  27. package/agent-skills/upstream/manifest.json +57 -0
  28. package/agent-skills/upstream/pulumi/LICENSE +201 -0
  29. package/agent-skills/upstream/pulumi/SKILL.md +501 -0
  30. package/agent-skills/upstream/terraform/LICENSE +373 -0
  31. package/agent-skills/upstream/terraform/SKILL.md +316 -0
  32. package/agent-skills/workflows/workflows.json +601 -0
  33. package/cli/architect.mjs +3 -0
  34. package/cli/runtime.mjs +115 -0
  35. package/dist/assets/html2canvas.esm-QH1iLAAe.js +22 -0
  36. package/dist/assets/index-BTLHaa3J.css +1 -0
  37. package/dist/assets/index-CQ2C1gKF.js +21338 -0
  38. package/dist/assets/index.es-DTyqIdaO.js +18 -0
  39. package/dist/assets/purify.es-CAi2OJFm.js +3 -0
  40. package/dist/assets/visual-export-Ox0j5xj5.js +173 -0
  41. package/dist/favicon.svg +2 -0
  42. package/dist/fonts/DM-Sans-OFL.txt +93 -0
  43. package/dist/fonts/Manrope-OFL.txt +93 -0
  44. package/dist/fonts/NotoSans-Regular.ttf +0 -0
  45. package/dist/fonts/OFL.txt +94 -0
  46. package/dist/fonts/dm-sans-latin-wght-normal.woff2 +0 -0
  47. package/dist/fonts/manrope-latin-wght-normal.woff2 +0 -0
  48. package/dist/index.html +4 -0
  49. package/dist/licenses/atmem-APACHE-2.0.txt +202 -0
  50. package/dist/licenses/aws-architect-LICENSE.txt +17 -0
  51. package/dist/licenses/aws-mcp-LICENSE.txt +175 -0
  52. package/dist/licenses/aws-mcp-NOTICE.txt +1 -0
  53. package/dist/licenses/cloud-emulation-notices.txt +36619 -0
  54. package/dist/licenses/dependency-notices.txt +6379 -0
  55. package/dist/licenses/emulation-notices.txt +717 -0
  56. package/dist/licenses/github-copilot-sdk-LICENSE.txt +21 -0
  57. package/dist/licenses/memory-dependency-notices.txt +3319 -0
  58. package/dist/licenses/openarchflow-LICENSE.txt +21 -0
  59. package/dist/licenses/python-dependency-notices.txt +11951 -0
  60. package/docs/upstream-lock.json +26 -0
  61. package/knowledge/engineering-practices.json +536 -0
  62. package/package.json +30 -4
  63. package/packaging/uv-release-lock.json +54 -0
  64. package/public/licenses/atmem-APACHE-2.0.txt +202 -0
  65. package/public/licenses/aws-architect-LICENSE.txt +17 -0
  66. package/public/licenses/aws-mcp-LICENSE.txt +175 -0
  67. package/public/licenses/aws-mcp-NOTICE.txt +1 -0
  68. package/public/licenses/cloud-emulation-notices.txt +36619 -0
  69. package/public/licenses/dependency-notices.txt +6379 -0
  70. package/public/licenses/emulation-notices.txt +717 -0
  71. package/public/licenses/github-copilot-sdk-LICENSE.txt +21 -0
  72. package/public/licenses/memory-dependency-notices.txt +3319 -0
  73. package/public/licenses/openarchflow-LICENSE.txt +21 -0
  74. package/public/licenses/python-dependency-notices.txt +11951 -0
  75. package/scripts/terraform-render.mjs +8 -0
  76. package/server/__init__.py +0 -0
  77. package/server/abstraction.py +28 -0
  78. package/server/agent_runtime.py +153 -0
  79. package/server/app.py +257 -0
  80. package/server/architect.py +112 -0
  81. package/server/architecture_activity.py +67 -0
  82. package/server/attachments.py +101 -0
  83. package/server/cloud-emulation-requirements.txt +29 -0
  84. package/server/codex_app_server.py +219 -0
  85. package/server/codex_engineering_backend.py +266 -0
  86. package/server/codex_worker_policy.py +193 -0
  87. package/server/contracts.py +315 -0
  88. package/server/copilot_worker.py +16 -0
  89. package/server/dependency_mirror.py +54 -0
  90. package/server/design_patch.py +43 -0
  91. package/server/emulation-requirements.txt +8 -0
  92. package/server/emulation_adapters.py +20 -0
  93. package/server/emulation_routes.py +98 -0
  94. package/server/emulation_worker.py +351 -0
  95. package/server/engineering_artifacts.py +221 -0
  96. package/server/engineering_assets/application-runtime.json +4372 -0
  97. package/server/engineering_assets/architecture_work.schema.json +79 -0
  98. package/server/engineering_assets/materialize_runtime.py +62 -0
  99. package/server/engineering_assets/prepare_tools.py +96 -0
  100. package/server/engineering_assets/sql_validation.py +59 -0
  101. package/server/engineering_contexts.py +120 -0
  102. package/server/engineering_delivery.py +210 -0
  103. package/server/engineering_finalization.py +210 -0
  104. package/server/engineering_handoff.py +172 -0
  105. package/server/engineering_jobs.py +206 -0
  106. package/server/engineering_knowledge.py +75 -0
  107. package/server/engineering_reconciliation.py +159 -0
  108. package/server/engineering_routes.py +483 -0
  109. package/server/engineering_sessions.py +273 -0
  110. package/server/engineering_tools.py +166 -0
  111. package/server/generation_lint.py +18 -0
  112. package/server/local_providers.py +185 -0
  113. package/server/local_validation.py +236 -0
  114. package/server/memory-requirements.lock +181 -0
  115. package/server/memory-requirements.txt +6 -0
  116. package/server/memory_context.py +58 -0
  117. package/server/memory_routes.py +141 -0
  118. package/server/memory_service.py +306 -0
  119. package/server/memory_worker.py +129 -0
  120. package/server/openai_voice.py +80 -0
  121. package/server/orca_handoff.py +90 -0
  122. package/server/packaged_app.py +9 -0
  123. package/server/pricing.py +190 -0
  124. package/server/process_control_observation.py +31 -0
  125. package/server/prompts.py +136 -0
  126. package/server/public_faq_emulation_worker.py +44 -0
  127. package/server/requirements.lock +1618 -0
  128. package/server/requirements.txt +68 -0
  129. package/server/runtime_dependency_locks.py +27 -0
  130. package/server/runtime_evidence.py +93 -0
  131. package/server/settings.py +14 -0
  132. package/server/skills.py +103 -0
  133. package/server/storage_emulation_worker.py +160 -0
  134. package/server/structured_emulation_worker.py +48 -0
  135. package/server/terraform_routes.py +118 -0
  136. package/server/upstream/__init__.py +0 -0
  137. package/server/upstream/agent/__init__.py +1 -0
  138. package/server/upstream/agent/aws_architect.py +600 -0
  139. package/server/upstream/agent/config/__init__.py +1 -0
  140. package/server/upstream/agent/config/agent_config.py +82 -0
  141. package/server/upstream/agent/config/prompts.py +138 -0
  142. package/server/upstream/agent/rate_limiter.py +62 -0
  143. package/server/upstream/utils/__init__.py +1 -0
  144. package/server/upstream/utils/file_writer.py +43 -0
  145. package/server/validation_applicability.py +85 -0
  146. package/server/validation_jobs.py +252 -0
  147. package/server/validation_workers.py +48 -0
  148. package/server/voice_routes.py +91 -0
  149. package/server/voice_worker.py +26 -0
  150. package/server/windows_snapshot.py +119 -0
  151. package/specs/028-convergence-evaluation/evidence/20261110-ibm-invoice-native/registry-structured/qualification.json +72 -0
  152. package/specs/028-convergence-evaluation/evidence/20261110-invoice-runtime/durable-current/receipt.json +61 -0
  153. package/specs/029-general-purpose-engine/evidence/20261111-runtime-dependencies/sdk/receipt.json +22 -0
  154. package/src/ArchitectureActivity.jsx +54 -0
  155. package/src/ArchitectureWorkPanel.jsx +39 -0
  156. package/src/ArtifactChecks.jsx +49 -0
  157. package/src/BlockRequirements.jsx +13 -0
  158. package/src/BrainActivity.jsx +11 -0
  159. package/src/ChatMessage.jsx +29 -0
  160. package/src/ChatResizeHandle.jsx +6 -0
  161. package/src/CodePreview.jsx +8 -0
  162. package/src/ComponentReview.jsx +31 -0
  163. package/src/DeliveryViews.jsx +59 -0
  164. package/src/EmulationPanel.jsx +44 -0
  165. package/src/EngagementViews.jsx +387 -0
  166. package/src/EngineeringPanel.jsx +151 -0
  167. package/src/FileTree.jsx +7 -0
  168. package/src/FinalChecklist.jsx +15 -0
  169. package/src/HelpNote.jsx +3 -0
  170. package/src/ImplementationDelivery.jsx +91 -0
  171. package/src/JourneyViews.jsx +403 -0
  172. package/src/LocationChoices.jsx +12 -0
  173. package/src/MemoryPanel.jsx +58 -0
  174. package/src/OpenAIVoicePanel.jsx +66 -0
  175. package/src/OutputsView.jsx +71 -0
  176. package/src/ProjectChecks.jsx +44 -0
  177. package/src/TerraformView.jsx +57 -0
  178. package/src/WorkbenchDialogs.jsx +532 -0
  179. package/src/activity-presentation.mjs +28 -0
  180. package/src/ai-qualification-scenarios.mjs +31 -0
  181. package/src/approval-application-files.mjs +32 -0
  182. package/src/approval-applications.mjs +82 -0
  183. package/src/approval-spec-kit.mjs +30 -0
  184. package/src/architecture-activity.css +28 -0
  185. package/src/architecture-activity.mjs +63 -0
  186. package/src/architecture-work.mjs +176 -0
  187. package/src/artifact-work.mjs +103 -0
  188. package/src/async-documents.mjs +191 -0
  189. package/src/atflow.css +1140 -0
  190. package/src/atforma.css +748 -0
  191. package/src/atmem-tokens.css +79 -0
  192. package/src/aws-preflight.mjs +60 -0
  193. package/src/aws-public-faq.mjs +102 -0
  194. package/src/aws-validation-scenarios.mjs +10 -0
  195. package/src/aws-validation.mjs +48 -0
  196. package/src/azure-plan-mocks.mjs +25 -0
  197. package/src/azure-structured.mjs +133 -0
  198. package/src/bedrock-summary.mjs +152 -0
  199. package/src/bounded-rag.mjs +60 -0
  200. package/src/brand.css +9 -0
  201. package/src/canvas-view.mjs +28 -0
  202. package/src/capability-composition.mjs +44 -0
  203. package/src/chat-attachments.mjs +13 -0
  204. package/src/cloud-provider-locks.mjs +9 -0
  205. package/src/cloud-storage-scenarios.mjs +2 -0
  206. package/src/component-review.mjs +55 -0
  207. package/src/composition-spec-kit.mjs +30 -0
  208. package/src/consultation-context.mjs +15 -0
  209. package/src/consultation.mjs +52 -0
  210. package/src/container-contracts.mjs +5 -0
  211. package/src/container-inspection.mjs +75 -0
  212. package/src/container-runtime.mjs +30 -0
  213. package/src/container-security-inspection.mjs +49 -0
  214. package/src/container-terraform.mjs +109 -0
  215. package/src/conversation.mjs +18 -0
  216. package/src/core.mjs +863 -0
  217. package/src/cross-cloud-storage.mjs +100 -0
  218. package/src/delivery-capabilities.mjs +25 -0
  219. package/src/delivery.mjs +58 -0
  220. package/src/deployment-ownership.mjs +10 -0
  221. package/src/deployment-region.mjs +11 -0
  222. package/src/derive.mjs +31 -0
  223. package/src/design-build-flow.mjs +10 -0
  224. package/src/diagram-attention.mjs +24 -0
  225. package/src/discovery.mjs +359 -0
  226. package/src/document.mjs +170 -0
  227. package/src/emulation-feedback.mjs +61 -0
  228. package/src/emulation-guidance.mjs +37 -0
  229. package/src/engagement.mjs +274 -0
  230. package/src/engineering-client.mjs +73 -0
  231. package/src/engineering-defaults.mjs +17 -0
  232. package/src/engineering.css +31 -0
  233. package/src/enterprise-application.mjs +76 -0
  234. package/src/enterprise-aws-host-infrastructure.mjs +62 -0
  235. package/src/enterprise-aws-host-tests.mjs +15 -0
  236. package/src/enterprise-aws-infrastructure-tests.mjs +38 -0
  237. package/src/enterprise-aws-infrastructure.mjs +138 -0
  238. package/src/enterprise-google-infrastructure.mjs +84 -0
  239. package/src/enterprise-google-tests.mjs +25 -0
  240. package/src/estimate.mjs +190 -0
  241. package/src/existing-references.mjs +18 -0
  242. package/src/external-identities.mjs +17 -0
  243. package/src/faq-lambda-build.mjs +28 -0
  244. package/src/final-package.mjs +34 -0
  245. package/src/gcp-structured.mjs +104 -0
  246. package/src/generation-provider.mjs +7 -0
  247. package/src/generation-quality.mjs +69 -0
  248. package/src/handoff.mjs +141 -0
  249. package/src/ibm-registry.mjs +12 -0
  250. package/src/ibm-structured.mjs +103 -0
  251. package/src/identifiers.mjs +15 -0
  252. package/src/implementation-map.mjs +14 -0
  253. package/src/implementation-outcome.mjs +8 -0
  254. package/src/incomplete-terraform.mjs +9 -0
  255. package/src/integrations.ts +137 -0
  256. package/src/interface-contracts.mjs +30 -0
  257. package/src/invoice-application.mjs +66 -0
  258. package/src/invoice-aws-operations.mjs +136 -0
  259. package/src/invoice-aws.mjs +143 -0
  260. package/src/invoice-azure-operations.mjs +147 -0
  261. package/src/invoice-azure.mjs +134 -0
  262. package/src/invoice-builder.mjs +35 -0
  263. package/src/invoice-dependencies.mjs +43 -0
  264. package/src/invoice-gcp-operations.mjs +178 -0
  265. package/src/invoice-gcp.mjs +104 -0
  266. package/src/invoice-ibm-operations.mjs +278 -0
  267. package/src/invoice-ibm.mjs +142 -0
  268. package/src/invoice-operations.mjs +143 -0
  269. package/src/invoice-plan.mjs +45 -0
  270. package/src/invoice-region.mjs +6 -0
  271. package/src/invoice-spec-kit.mjs +61 -0
  272. package/src/invoice-state.mjs +7 -0
  273. package/src/invoice-terraform.mjs +29 -0
  274. package/src/invoice-tests.mjs +122 -0
  275. package/src/journey-workspace.css +106 -0
  276. package/src/journey.mjs +97 -0
  277. package/src/levels.mjs +145 -0
  278. package/src/local-agent.mjs +184 -0
  279. package/src/main.jsx +2481 -0
  280. package/src/model-policy-preflight.mjs +34 -0
  281. package/src/openai-voice.mjs +102 -0
  282. package/src/output-bundle.mjs +13 -0
  283. package/src/ownership-inspection.mjs +28 -0
  284. package/src/pack.mjs +201 -0
  285. package/src/pricing.mjs +85 -0
  286. package/src/production-state.mjs +8 -0
  287. package/src/project-copy.mjs +10 -0
  288. package/src/project-file.mjs +160 -0
  289. package/src/project-links.mjs +3 -0
  290. package/src/protected-state.mjs +43 -0
  291. package/src/public-faq-builder.mjs +19 -0
  292. package/src/public-faq-clouds.mjs +251 -0
  293. package/src/public-faq.mjs +122 -0
  294. package/src/pulumi.mjs +123 -0
  295. package/src/python-container.mjs +25 -0
  296. package/src/python-runtime.mjs +50 -0
  297. package/src/rag-handler.mjs +43 -0
  298. package/src/rag-web-assets.mjs +52 -0
  299. package/src/rag-web.mjs +68 -0
  300. package/src/records.mjs +177 -0
  301. package/src/resources.mjs +163 -0
  302. package/src/review.mjs +252 -0
  303. package/src/runtime/EnterpriseDocument.java +89 -0
  304. package/src/runtime/approved_http_destination.py +72 -0
  305. package/src/runtime/aws-lambda-qualification-lock.json +7 -0
  306. package/src/runtime/aws-python-lock.json +82 -0
  307. package/src/runtime/aws-web-python-lock.json +887 -0
  308. package/src/runtime/aws_json_model.py +42 -0
  309. package/src/runtime/azure-python-lock.json +863 -0
  310. package/src/runtime/azure-sources.json +8 -0
  311. package/src/runtime/azure-test-lock.json +23 -0
  312. package/src/runtime/azure_acceptance.py +192 -0
  313. package/src/runtime/azure_structured.py +153 -0
  314. package/src/runtime/bounded_rag.py +126 -0
  315. package/src/runtime/catalog_admin.py +70 -0
  316. package/src/runtime/cloud-sql-proxy-lock.json +8 -0
  317. package/src/runtime/cloud-sql-proxy-security-review.json +30 -0
  318. package/src/runtime/connector_cli.py +50 -0
  319. package/src/runtime/connector_sync.py +70 -0
  320. package/src/runtime/durable-python-lock.json +247 -0
  321. package/src/runtime/durable_workflow.py +325 -0
  322. package/src/runtime/enterprise-application-manifest.json +110 -0
  323. package/src/runtime/enterprise-application-sources.json +266 -0
  324. package/src/runtime/enterprise-auth-python-lock.json +592 -0
  325. package/src/runtime/enterprise-aws-host-bootstrap-source.json +1 -0
  326. package/src/runtime/enterprise-aws-host-probe-source.json +1 -0
  327. package/src/runtime/enterprise-aws-task-template.json +235 -0
  328. package/src/runtime/enterprise-document-lock.json +18 -0
  329. package/src/runtime/enterprise-document.Dockerfile +15 -0
  330. package/src/runtime/enterprise-runtime-aws-python-lock.json +1115 -0
  331. package/src/runtime/enterprise-runtime-azure-python-lock.json +1106 -0
  332. package/src/runtime/enterprise-runtime-gcp-python-lock.json +1060 -0
  333. package/src/runtime/enterprise-runtime-ibm-python-lock.json +1096 -0
  334. package/src/runtime/enterprise-runtime-python-lock.json +1058 -0
  335. package/src/runtime/enterprise-runtime.Dockerfile +15 -0
  336. package/src/runtime/enterprise-web-app.js +1 -0
  337. package/src/runtime/enterprise-web-entry.js +105 -0
  338. package/src/runtime/enterprise-web-lock.json +29 -0
  339. package/src/runtime/enterprise-web-notices.txt +229 -0
  340. package/src/runtime/enterprise-web.css +4 -0
  341. package/src/runtime/enterprise-web.html +8 -0
  342. package/src/runtime/enterprise_audit.py +91 -0
  343. package/src/runtime/enterprise_audit_schema.sql +25 -0
  344. package/src/runtime/enterprise_auth_schema.sql +67 -0
  345. package/src/runtime/enterprise_auth_store.py +241 -0
  346. package/src/runtime/enterprise_aws_host_bootstrap.py +120 -0
  347. package/src/runtime/enterprise_aws_host_probe.py +105 -0
  348. package/src/runtime/enterprise_aws_hosts.py +136 -0
  349. package/src/runtime/enterprise_aws_jobs.py +300 -0
  350. package/src/runtime/enterprise_aws_objects.py +93 -0
  351. package/src/runtime/enterprise_aws_transfer.py +83 -0
  352. package/src/runtime/enterprise_azure_batch_api.py +128 -0
  353. package/src/runtime/enterprise_azure_host.py +599 -0
  354. package/src/runtime/enterprise_azure_jobs.py +294 -0
  355. package/src/runtime/enterprise_azure_objects.py +234 -0
  356. package/src/runtime/enterprise_azure_pool.py +161 -0
  357. package/src/runtime/enterprise_azure_transfer.py +122 -0
  358. package/src/runtime/enterprise_configuration.py +136 -0
  359. package/src/runtime/enterprise_document.py +116 -0
  360. package/src/runtime/enterprise_document_cli.py +32 -0
  361. package/src/runtime/enterprise_document_contract.py +54 -0
  362. package/src/runtime/enterprise_document_job.py +109 -0
  363. package/src/runtime/enterprise_document_jobs.py +122 -0
  364. package/src/runtime/enterprise_document_jobs_schema.sql +23 -0
  365. package/src/runtime/enterprise_extraction_cache.py +186 -0
  366. package/src/runtime/enterprise_extraction_schema.sql +17 -0
  367. package/src/runtime/enterprise_google_jobs.py +275 -0
  368. package/src/runtime/enterprise_google_transfer.py +85 -0
  369. package/src/runtime/enterprise_http.py +212 -0
  370. package/src/runtime/enterprise_identity.py +52 -0
  371. package/src/runtime/enterprise_knowledge.py +152 -0
  372. package/src/runtime/enterprise_models.py +94 -0
  373. package/src/runtime/enterprise_native.py +181 -0
  374. package/src/runtime/enterprise_oauth.py +132 -0
  375. package/src/runtime/enterprise_operator.py +160 -0
  376. package/src/runtime/enterprise_parser_service.py +136 -0
  377. package/src/runtime/enterprise_parser_transport.py +68 -0
  378. package/src/runtime/enterprise_queries.py +255 -0
  379. package/src/runtime/enterprise_queries_schema.sql +27 -0
  380. package/src/runtime/enterprise_query_service.py +111 -0
  381. package/src/runtime/enterprise_secrets.py +110 -0
  382. package/src/runtime/enterprise_sessions.py +95 -0
  383. package/src/runtime/enterprise_sources.py +260 -0
  384. package/src/runtime/enterprise_web.py +39 -0
  385. package/src/runtime/enterprise_worker.py +68 -0
  386. package/src/runtime/export_contract_acceptance.py +18 -0
  387. package/src/runtime/faq-output-contract.json +40 -0
  388. package/src/runtime/faq-web-app.js +41 -0
  389. package/src/runtime/faq-web.css +1 -0
  390. package/src/runtime/faq-web.html +6 -0
  391. package/src/runtime/gcp-sources.json +9 -0
  392. package/src/runtime/gcp_acceptance.py +110 -0
  393. package/src/runtime/gcp_structured.py +150 -0
  394. package/src/runtime/http_acceptance.py +39 -0
  395. package/src/runtime/iap-web-app.js +36 -0
  396. package/src/runtime/iap-web-source.json +1 -0
  397. package/src/runtime/ibm-python-lock.json +856 -0
  398. package/src/runtime/ibm-sources.json +9 -0
  399. package/src/runtime/ibm_acceptance.py +133 -0
  400. package/src/runtime/ibm_structured.py +113 -0
  401. package/src/runtime/invoice-azapi-provider-lock.json +7 -0
  402. package/src/runtime/invoice-ibm-provider-lock.json +7 -0
  403. package/src/runtime/invoice-parser-lock.json +1199 -0
  404. package/src/runtime/invoice-parser-python-lock.json +56 -0
  405. package/src/runtime/invoice-parser.Dockerfile +190 -0
  406. package/src/runtime/invoice-sources.json +58 -0
  407. package/src/runtime/invoice-test-sources.json +24 -0
  408. package/src/runtime/invoice-web.css +2 -0
  409. package/src/runtime/invoice-web.html +12 -0
  410. package/src/runtime/invoice-web.js +112 -0
  411. package/src/runtime/invoice_configuration.py +17 -0
  412. package/src/runtime/invoice_document.py +95 -0
  413. package/src/runtime/invoice_extraction.py +96 -0
  414. package/src/runtime/invoice_http.py +129 -0
  415. package/src/runtime/invoice_identity.py +5 -0
  416. package/src/runtime/invoice_maintenance.py +40 -0
  417. package/src/runtime/invoice_native.py +77 -0
  418. package/src/runtime/invoice_object_store.py +153 -0
  419. package/src/runtime/invoice_operations.py +108 -0
  420. package/src/runtime/invoice_operator.py +79 -0
  421. package/src/runtime/invoice_operator_core.py +39 -0
  422. package/src/runtime/invoice_operator_job.py +147 -0
  423. package/src/runtime/invoice_parser_cli.py +17 -0
  424. package/src/runtime/invoice_parser_identity.py +39 -0
  425. package/src/runtime/invoice_parser_service.py +89 -0
  426. package/src/runtime/invoice_parser_transport.py +89 -0
  427. package/src/runtime/invoice_processing.py +24 -0
  428. package/src/runtime/invoice_retention.py +16 -0
  429. package/src/runtime/invoice_runtime_secrets.py +43 -0
  430. package/src/runtime/invoice_stage.py +80 -0
  431. package/src/runtime/invoice_web.py +39 -0
  432. package/src/runtime/invoice_worker.py +50 -0
  433. package/src/runtime/lambda_faq.py +5 -0
  434. package/src/runtime/parser-requirements.lock +4 -0
  435. package/src/runtime/policy_review.py +18 -0
  436. package/src/runtime/postgres-qualification-lock.json +21 -0
  437. package/src/runtime/public-faq-sources.json +22 -0
  438. package/src/runtime/public_catalog_admin.py +122 -0
  439. package/src/runtime/public_catalog_store.py +125 -0
  440. package/src/runtime/public_faq.py +144 -0
  441. package/src/runtime/public_faq_app.py +49 -0
  442. package/src/runtime/python-container-lock.json +18 -0
  443. package/src/runtime/rag-sources.json +10 -0
  444. package/src/runtime/rag_acceptance.py +60 -0
  445. package/src/runtime/rag_aws_adapter.py +95 -0
  446. package/src/runtime/rds-ca-source.json +9 -0
  447. package/src/runtime/rds-global-ca.pem +2888 -0
  448. package/src/runtime/state-contract-check-source.json +4 -0
  449. package/src/runtime/state_contract_check.py +338 -0
  450. package/src/runtime/structured-source.json +1 -0
  451. package/src/runtime/structured-web-app.js +71 -0
  452. package/src/runtime/structured-web-source.json +1 -0
  453. package/src/runtime/structured_http.py +105 -0
  454. package/src/runtime/structured_output.py +48 -0
  455. package/src/runtime/web-python-lock.json +802 -0
  456. package/src/runtime/web_user_admin.py +44 -0
  457. package/src/runtime/workflow_application.py +62 -0
  458. package/src/runtime/workflow_bindings.py +128 -0
  459. package/src/runtime/workflow_configuration.py +40 -0
  460. package/src/runtime/workflow_connection.py +105 -0
  461. package/src/runtime/workflow_contract.py +54 -0
  462. package/src/runtime/workflow_database.py +94 -0
  463. package/src/runtime/workflow_errors.py +6 -0
  464. package/src/runtime/workflow_http.py +178 -0
  465. package/src/runtime/workflow_identity.py +69 -0
  466. package/src/runtime/workflow_payload.py +118 -0
  467. package/src/runtime/workflow_process_stage.py +88 -0
  468. package/src/runtime/workflow_profile.py +91 -0
  469. package/src/runtime/workflow_review.py +106 -0
  470. package/src/runtime/workflow_role_bootstrap.py +104 -0
  471. package/src/runtime/workflow_schema.sql +72 -0
  472. package/src/runtime/workflow_worker.py +142 -0
  473. package/src/runtime-settings.mjs +15 -0
  474. package/src/s3-access.mjs +14 -0
  475. package/src/source-contracts.mjs +17 -0
  476. package/src/spec-kit.mjs +186 -0
  477. package/src/state-custody.mjs +32 -0
  478. package/src/state-inspection.mjs +45 -0
  479. package/src/state-spec-kit.mjs +13 -0
  480. package/src/storage-tests.mjs +25 -0
  481. package/src/structured-api.mjs +133 -0
  482. package/src/structured-contract.mjs +19 -0
  483. package/src/structured-operation-policy.mjs +2 -0
  484. package/src/structured-web.mjs +17 -0
  485. package/src/style.css +1 -0
  486. package/src/system-description.mjs +26 -0
  487. package/src/terraform-admission.mjs +66 -0
  488. package/src/terraform-composition.mjs +83 -0
  489. package/src/terraform-expressions.mjs +46 -0
  490. package/src/terraform-validation-coverage.mjs +11 -0
  491. package/src/terraform.mjs +128 -0
  492. package/src/text-statistics.mjs +51 -0
  493. package/src/upstream/openarchflow/format-payload.ts +26 -0
  494. package/src/upstream/openarchflow/import/mermaid.ts +205 -0
  495. package/src/upstream/openarchflow/import/sql-ddl.ts +109 -0
  496. package/src/upstream/openarchflow/layout.ts +54 -0
  497. package/src/upstream/openarchflow/providers/aws.ts +196 -0
  498. package/src/upstream/openarchflow/providers/azure.ts +126 -0
  499. package/src/upstream/openarchflow/providers/cloudnative.ts +71 -0
  500. package/src/upstream/openarchflow/providers/generic.ts +227 -0
  501. package/src/upstream/openarchflow/providers/integration.ts +22 -0
  502. package/src/upstream/openarchflow/providers/types.ts +2 -0
  503. package/src/upstream/openarchflow/templates.ts +937 -0
  504. package/src/upstream-catalog.mjs +10 -0
  505. package/src/useChatScroll.jsx +37 -0
  506. package/src/useEmulation.jsx +36 -0
  507. package/src/useEngineeringStatus.mjs +17 -0
  508. package/src/validation-receipt.mjs +10 -0
  509. package/src/visual-export.mjs +92 -0
  510. package/src/voice-conversation.mjs +117 -0
  511. package/src/work-intake.mjs +24 -0
  512. package/src/workflow-runtime-inventory.mjs +3 -0
@@ -0,0 +1,15 @@
1
+ # The staging context supplies only reviewed runtime files and the emitted hash lock.
2
+ # The compiled package must also supply its owned enterprise-deployment.json.
3
+ FROM docker.io/library/python:3.13-slim-trixie@sha256:48d884813cf44e927cf64c5529dd630dd3b18338c6dc727991eef9b71e934a20 AS wheels
4
+ COPY requirements.lock /build/requirements.lock
5
+ RUN python -I -m pip --isolated download --only-binary=:all: --require-hashes --dest /wheels -r /build/requirements.lock
6
+ FROM docker.io/library/python:3.13-slim-trixie@sha256:48d884813cf44e927cf64c5529dd630dd3b18338c6dc727991eef9b71e934a20
7
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
8
+ WORKDIR /app
9
+ ADD --checksum=sha256:8c27c342230503b73dfde629642c3b352e87b554e06d60cf58772f236a305ceb https://deb.debian.org/debian-security/pool/updates/main/z/zlib/zlib1g_1.3.dfsg%2breally1.3.1-1%2bdeb13u1_amd64.deb /tmp/zlib1g.deb
10
+ RUN dpkg -i /tmp/zlib1g.deb && rm /tmp/zlib1g.deb
11
+ COPY requirements.lock /app/requirements.lock
12
+ RUN --mount=type=bind,from=wheels,source=/wheels,target=/wheels,readonly python -I -m pip --isolated install --no-index --find-links=/wheels --only-binary=:all: --no-cache-dir --require-hashes -r /app/requirements.lock && python -I -m pip --isolated check && python -I -m pip --isolated uninstall --yes pip && rm -rf /usr/local/lib/python3.13/ensurepip
13
+ COPY runtime/ /app/
14
+ USER 10001:10001
15
+ CMD ["python", "-I", "/app/enterprise_native.py", "api"]
@@ -0,0 +1 @@
1
+ (()=>{var B=class extends Error{};B.prototype.name="InvalidTokenError";function Ye(e){return decodeURIComponent(atob(e).replace(/(.)/g,(t,s)=>{let i=s.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}function Xe(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Ye(t)}catch{return atob(t)}}function be(e,t){if(typeof e!="string")throw new B("Invalid token specified: must be a string");t||(t={});let s=t.header===!0?0:1,i=e.split(".")[s];if(typeof i!="string")throw new B(`Invalid token specified: missing part #${s+1}`);let r;try{r=Xe(i)}catch(o){throw new B(`Invalid token specified: invalid base64 for part #${s+1} (${o.message})`)}try{return JSON.parse(r)}catch(o){throw new B(`Invalid token specified: invalid json for part #${s+1} (${o.message})`)}}var Ze={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},C,P,re=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(re||{});(e=>{function t(){C=3,P=Ze}e.reset=t;function s(r){if(!(0<=r&&r<=4))throw new Error("Invalid log level");C=r}e.setLevel=s;function i(r){P=r}e.setLogger=i})(re||(re={}));var u=class R{constructor(t){this._name=t}debug(...t){C>=4&&P.debug(R._format(this._name,this._method),...t)}info(...t){C>=3&&P.info(R._format(this._name,this._method),...t)}warn(...t){C>=2&&P.warn(R._format(this._name,this._method),...t)}error(...t){C>=1&&P.error(R._format(this._name,this._method),...t)}throw(t){throw this.error(t),t}create(t){let s=Object.create(this);return s._method=t,s.debug("begin"),s}static createStatic(t,s){let i=new R(`${t}.${s}`);return i.debug("begin"),i}static _format(t,s){let i=`[${t}]`;return s?`${i} ${s}:`:i}static debug(t,...s){C>=4&&P.debug(R._format(t),...s)}static info(t,...s){C>=3&&P.info(R._format(t),...s)}static warn(t,...s){C>=2&&P.warn(R._format(t),...s)}static error(t,...s){C>=1&&P.error(R._format(t),...s)}};re.reset();var ee=class{static decode(e){try{return be(e)}catch(t){throw u.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,s){let i=_.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),r=_.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t))),o=`${i}.${r}`,n=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},s,new TextEncoder().encode(o)),a=_.encodeBase64Url(new Uint8Array(n));return`${o}.${a}`}static async generateSignedJwtWithHmac(e,t,s){let i=_.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),r=_.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t))),o=`${i}.${r}`,n=await window.crypto.subtle.sign("HMAC",s,new TextEncoder().encode(o)),a=_.encodeBase64Url(new Uint8Array(n));return`${o}.${a}`}},et="10000000-1000-4000-8000-100000000000",de=e=>btoa([...new Uint8Array(e)].map(t=>String.fromCharCode(t)).join("")),Ce=class b{static _randomWord(){let t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]}static generateUUIDv4(){return et.replace(/[018]/g,s=>(+s^b._randomWord()&15>>+s/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return b.generateUUIDv4()+b.generateUUIDv4()+b.generateUUIDv4()}static async generateCodeChallenge(t){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{let i=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",i);return de(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(s){throw u.error("CryptoUtils.generateCodeChallenge",s),s}}static generateBasicAuth(t,s){let r=new TextEncoder().encode([t,s].join(":"));return de(r)}static async hash(t,s){let i=new TextEncoder().encode(s),r=await crypto.subtle.digest(t,i);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let s;switch(t.kty){case"RSA":s={e:t.e,kty:t.kty,n:t.n};break;case"EC":s={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":s={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":s={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}let i=await b.hash("SHA-256",JSON.stringify(s));return b.encodeBase64Url(i)}static async generateDPoPProof({url:t,accessToken:s,httpMethod:i,keyPair:r,nonce:o}){let n,a,c={jti:window.crypto.randomUUID(),htm:i??"GET",htu:t,iat:Math.floor(Date.now()/1e3)};s&&(n=await b.hash("SHA-256",s),a=b.encodeBase64Url(n),c.ath=a),o&&(c.nonce=o);try{let l=await crypto.subtle.exportKey("jwk",r.publicKey),d={alg:"ES256",typ:"dpop+jwt",jwk:{crv:l.crv,kty:l.kty,x:l.x,y:l.y}};return await ee.generateSignedJwt(d,c,r.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{let s=await crypto.subtle.exportKey("jwk",t.publicKey);return await b.customCalculateJwkThumbprint(s)}catch(s){throw s instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${s.message}`):s}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,s,i,r="HS256"){let o=Math.floor(Date.now()/1e3),n={alg:r,typ:"JWT"},a={iss:t,sub:t,aud:i,jti:b.generateUUIDv4(),exp:o+300,iat:o},l={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[r];if(!l)throw new Error(`Unsupported algorithm: ${r}. Supported algorithms are: HS256, HS384, HS512`);let d=new TextEncoder,h=await crypto.subtle.importKey("raw",d.encode(s),{name:"HMAC",hash:l},!1,["sign"]);return await ee.generateSignedJwtWithHmac(n,a,h)}};Ce.encodeBase64Url=e=>de(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var _=Ce,N=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new u(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){let t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(let t of this._callbacks)await t(...e)}},ke=class{static center({...e}){var t,s,i;return e.width==null&&(e.width=(t=[800,720,600,480].find(r=>r<=window.outerWidth/1.618))!=null?t:360),(s=e.left)!=null||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),e.height!=null&&((i=e.top)!=null||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,t])=>t!=null).map(([t,s])=>`${t}=${typeof s!="boolean"?s:s?"yes":"no"}`).join(",")}},U=class ie extends N{constructor(){super(...arguments),this._logger=new u(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{let t=this._expiration-ie.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=ie.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){let s=this._logger.create("init");t=Math.max(Math.floor(t),1);let i=ie.getEpochTime()+t;if(this.expiration===i&&this._timerHandle){s.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),s.debug("using duration",t),this._expiration=i;let r=Math.min(t,5);this._timerHandle=setInterval(this._callback,r*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},he=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");let i=new URL(e,"http://127.0.0.1")[t==="fragment"?"hash":"search"];return new URLSearchParams(i.slice(1))}},Y=";",V=class extends Error{constructor(e,t){var s,i,r;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw u.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=(s=e.error_description)!=null?s:null,this.error_uri=(i=e.error_uri)!=null?i:null,this.state=e.userState,this.session_state=(r=e.session_state)!=null?r:null,this.url_state=e.url_state}},we=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},tt=class{constructor(e){this._logger=new u("AccessTokenEvents"),this._expiringTimer=new U("Access token expiring"),this._expiredTimer=new U("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){let t=this._logger.create("load");if(e.access_token&&e.expires_in!==void 0){let s=e.expires_in;if(t.debug("access token present, remaining duration:",s),s>0){let r=s-this._expiringNotificationTimeInSeconds;r<=0&&(r=1),t.debug("registering expiring timer, raising in",r,"seconds"),this._expiringTimer.init(r)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();let i=s+1;t.debug("registering expired timer, raising in",i,"seconds"),this._expiredTimer.init(i)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},st=class{constructor(e,t,s,i,r){this._callback=e,this._client_id=t,this._intervalInSeconds=i,this._stopOnError=r,this._logger=new u("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=n=>{n.origin===this._frame_origin&&n.source===this._frame.contentWindow&&(n.data==="error"?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):n.data==="changed"?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(n.data+" message from check session op iframe"))};let o=new URL(s);this._frame_origin=o.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=o.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;let t=()=>{!this._frame.contentWindow||!this._session_state||this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,this._intervalInSeconds*1e3)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},oe=class{constructor(){this._logger=new u("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},ue=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},fe=class{constructor(e=[],t=null,s={}){this._jwtHandler=t,this._extraHeaders=s,this._logger=new u("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){let{timeoutInSeconds:s,...i}=t;if(!s)return await fetch(e,i);let r=new AbortController,o=setTimeout(()=>r.abort(),s*1e3);try{return await fetch(e,{...t,signal:r.signal})}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?new we("Network timed out"):n}finally{clearTimeout(o)}}async getJson(e,{token:t,credentials:s,timeoutInSeconds:i}={}){let r=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};t&&(r.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+t),this._appendExtraHeaders(o);let n;try{r.debug("url:",e),n=await this.fetchWithTimeout(e,{method:"GET",headers:o,timeoutInSeconds:i,credentials:s})}catch(l){throw r.error("Network Error"),l}r.debug("HTTP response received, status",n.status);let a=n.headers.get("Content-Type");if(a&&!this._contentTypes.find(l=>a.startsWith(l))&&r.throw(new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${e}`)),n.ok&&this._jwtHandler&&a?.startsWith("application/jwt"))return await this._jwtHandler(await n.text());let c;try{c=await n.json()}catch(l){throw r.error("Error parsing JSON response",l),n.ok?l:new Error(`${n.statusText} (${n.status})`)}if(!n.ok)throw r.error("Error from server:",c),c.error?new V(c):new Error(`${n.statusText} (${n.status}): ${JSON.stringify(c)}`);return c}async postForm(e,{body:t,basicAuth:s,timeoutInSeconds:i,initCredentials:r,extraHeaders:o}){let n=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...o};s!==void 0&&(a.Authorization="Basic "+s),this._appendExtraHeaders(a);let c;try{n.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:i,credentials:r})}catch(p){throw n.error("Network error"),p}n.debug("HTTP response received, status",c.status);let l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find(p=>l.startsWith(p)))throw new Error(`Invalid response Content-Type: ${l??"undefined"}, from URL: ${e}`);let d=await c.text(),h={};if(d)try{h=JSON.parse(d)}catch(p){throw n.error("Error parsing JSON response",p),c.ok?p:new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(n.error("Error from server:",h),c.headers.has("dpop-nonce")){let p=c.headers.get("dpop-nonce");throw new ue(p,`${JSON.stringify(h)}`)}throw h.error?new V(h,t):new Error(`${c.statusText} (${c.status}): ${JSON.stringify(h)}`)}return h}_appendExtraHeaders(e){let t=this._logger.create("appendExtraHeaders"),s=Object.keys(this._extraHeaders),i=["accept","content-type"],r=["authorization"];s.length!==0&&s.forEach(o=>{if(i.includes(o.toLocaleLowerCase())){t.warn("Protected header could not be set",o,i);return}if(r.includes(o.toLocaleLowerCase())&&Object.keys(e).includes(o)){t.warn("Header could not be overridden",o,r);return}let n=typeof this._extraHeaders[o]=="function"?this._extraHeaders[o]():this._extraHeaders[o];n&&n!==""&&(e[o]=n)})}},it=class{constructor(e){this._settings=e,this._logger=new u("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new fe(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){let e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);let t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){let s=this._logger.create(`_getMetadataProperty('${e}')`),i=await this.getMetadata();if(s.debug("resolved"),i[e]===void 0){if(t===!0){s.warn("Metadata does not contain optional property");return}s.throw(new Error("Metadata does not contain property "+e))}return i[e]}async getSigningKeys(){let e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;let t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);let s=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",s),!Array.isArray(s.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=s.keys,this._signingKeys}},te=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new u("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;let t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");let e=await this._store.length,t=[];for(let s=0;s<e;s++){let i=await this._store.key(s);i&&i.indexOf(this._prefix)===0&&t.push(i.substr(this._prefix.length))}return t}},rt="code",nt="openid",ot="client_secret_post",at=900,ge=class{constructor({authority:e,metadataUrl:t,metadata:s,signingKeys:i,metadataSeed:r,client_id:o,client_secret:n,response_type:a=rt,scope:c=nt,redirect_uri:l,post_logout_redirect_uri:d,client_authentication:h=ot,token_endpoint_auth_signing_alg:p="HS256",prompt:y,display:J,max_age:L,ui_locales:W,acr_values:K,resource:A,response_mode:F,filterProtocolClaims:O=!0,loadUserInfo:T=!1,requestTimeoutInSeconds:w,staleStateAgeInSeconds:I=at,mergeClaimsStrategy:x={array:"replace"},disablePKCE:S=!1,stateStore:z,revokeTokenAdditionalContentTypes:We,fetchRequestCredentials:Se,refreshTokenAllowedScope:Ke,extraQueryParams:Fe={},extraTokenParams:ze={},extraHeaders:Be={},dpop:Ve,omitScopeWhenRequesting:Qe=!1}){var ve;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=s,this.metadataSeed=r,this.signingKeys=i,this.client_id=o,this.client_secret=n,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=d,this.client_authentication=h,this.token_endpoint_auth_signing_alg=p,this.prompt=y,this.display=J,this.max_age=L,this.ui_locales=W,this.acr_values=K,this.resource=A,this.response_mode=F,this.filterProtocolClaims=O??!0,this.loadUserInfo=!!T,this.staleStateAgeInSeconds=I,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=Qe,this.disablePKCE=!!S,this.revokeTokenAdditionalContentTypes=We,this.fetchRequestCredentials=Se||"same-origin",this.requestTimeoutInSeconds=w,z)this.stateStore=z;else{let Ge=typeof window<"u"?window.localStorage:new oe;this.stateStore=new te({store:Ge})}if(this.refreshTokenAllowedScope=Ke,this.extraQueryParams=Fe,this.extraTokenParams=ze,this.extraHeaders=Be,this.dpop=Ve,this.dpop&&!((ve=this.dpop)!=null&&ve.store))throw new Error("A DPoPStore is required when dpop is enabled")}},ct=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new u("UserInfoService"),this._getClaimsFromJwt=async s=>{let i=this._logger.create("_getClaimsFromJwt");try{let r=ee.decode(s);return i.debug("JWT decoding successful"),r}catch(r){throw i.error("Error parsing JWT response"),r}},this._jsonService=new fe(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){let t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));let s=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",s);let i=await this._jsonService.getJson(s,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",i),i}},Pe=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new u("TokenClient"),this._jsonService=new fe(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:i=this._settings.client_secret,extraHeaders:r,...o}){let n=this._logger.create("exchangeCode");s||n.throw(new Error("A client_id is required")),t||n.throw(new Error("A redirect_uri is required")),o.code||n.throw(new Error("A code is required"));let a=new URLSearchParams({grant_type:e,redirect_uri:t});for(let[h,p]of Object.entries(o))p!=null&&a.set(h,p);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&i==null)throw n.throw(new Error("A client_secret is required")),null;let c,l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=_.generateBasicAuth(s,i);break;case"client_secret_post":a.append("client_id",s),i&&a.append("client_secret",i);break;case"client_secret_jwt":{let h=await _.generateClientAssertionJwt(s,i,l,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",s),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",h);break}}n.debug("got token endpoint");let d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return n.debug("got response"),d}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:i=this._settings.scope,...r}){let o=this._logger.create("exchangeCredentials");t||o.throw(new Error("A client_id is required"));let n=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||n.set("scope",i);for(let[d,h]of Object.entries(r))h!=null&&n.set(d,h);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&s==null)throw o.throw(new Error("A client_secret is required")),null;let a,c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=_.generateBasicAuth(t,s);break;case"client_secret_post":n.append("client_id",t),s&&n.append("client_secret",s);break;case"client_secret_jwt":{let d=await _.generateClientAssertionJwt(t,s,c,this._settings.token_endpoint_auth_signing_alg);n.append("client_id",t),n.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),n.append("client_assertion",d);break}}o.debug("got token endpoint");let l=await this._jsonService.postForm(c,{body:n,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return o.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:i,extraHeaders:r,...o}){let n=this._logger.create("exchangeRefreshToken");t||n.throw(new Error("A client_id is required")),o.refresh_token||n.throw(new Error("A refresh_token is required"));let a=new URLSearchParams({grant_type:e});for(let[h,p]of Object.entries(o))Array.isArray(p)?p.forEach(y=>a.append(h,y)):p!=null&&a.set(h,p);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&s==null)throw n.throw(new Error("A client_secret is required")),null;let c,l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=_.generateBasicAuth(t,s);break;case"client_secret_post":a.append("client_id",t),s&&a.append("client_secret",s);break;case"client_secret_jwt":{let h=await _.generateClientAssertionJwt(t,s,l,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",h);break}}n.debug("got token endpoint");let d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:r});return n.debug("got response"),d}async revoke(e){var t;let s=this._logger.create("revoke");e.token||s.throw(new Error("A token is required"));let i=await this._metadataService.getRevocationEndpoint(!1);s.debug(`got revocation endpoint, revoking ${(t=e.token_type_hint)!=null?t:"default token type"}`);let r=new URLSearchParams;for(let[o,n]of Object.entries(e))n!=null&&r.set(o,n);r.set("client_id",this._settings.client_id),this._settings.client_secret&&r.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(i,{body:r,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),s.debug("got response")}},lt=class{constructor(e,t,s){this._settings=e,this._metadataService=t,this._claimsService=s,this._logger=new u("ResponseValidator"),this._userInfoService=new ct(this._settings,this._metadataService),this._tokenClient=new Pe(this._settings,this._metadataService)}async validateSigninResponse(e,t,s){let i=this._logger.create("validateSigninResponse");this._processSigninState(e,t),i.debug("state processed"),await this._processCode(e,t,s),i.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e,"",t.nonce),i.debug("tokens validated"),await this._processClaims(e,t?.skipUserInfo,e.isOpenId),i.debug("claims processed")}async validateCredentialsResponse(e,t){let s=this._logger.create("validateCredentialsResponse"),i=e.isOpenId&&!!e.id_token;i&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,t,i),s.debug("claims processed")}async validateRefreshResponse(e,t){var s,i;let r=this._logger.create("validateRefreshResponse");e.userState=t.data,(s=e.session_state)!=null||(e.session_state=t.session_state),(i=e.scope)!=null||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);let o=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,o),r.debug("claims processed")}validateSignoutResponse(e,t){let s=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&s.throw(new Error("State does not match")),s.debug("state validated"),e.userState=t.data,e.error)throw s.warn("Response was error",e.error),new V(e)}_processSigninState(e,t){var s;let i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,(s=e.scope)!=null||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new V(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,s=!0){let i=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){i.debug("not loading user info");return}i.debug("loading user info");let r=await this._userInfoService.getClaims(e.access_token);i.debug("user info claims received from user info endpoint"),s&&r.sub!==e.profile.sub&&i.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(r)),i.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,s){let i=this._logger.create("_processCode");if(e.code){i.debug("Validating code");let r=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:s,...t.extraTokenParams});Object.assign(e,r)}else i.debug("No code to process")}_validateIdTokenAttributes(e,t,s){var i;let r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");let o=ee.decode((i=e.id_token)!=null?i:"");if(o.sub||r.throw(new Error("ID Token is missing a subject claim")),s&&o.nonce!==s&&r.throw(new Error("nonce in id_token does not match nonce in client storage")),t){let n=ee.decode(t);o.sub!==n.sub&&r.throw(new Error("sub in id_token does not match current sub")),o.auth_time&&o.auth_time!==n.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),o.azp&&o.azp!==n.azp&&r.throw(new Error("azp in id_token does not match original azp")),!o.azp&&n.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=o}},ne=class pe{constructor(t){this.id=t.id||_.generateUUIDv4(),this.data=t.data,t.created&&t.created>0?this.created=t.created:this.created=U.getEpochTime(),this.request_type=t.request_type,this.url_state=t.url_state}toStorageString(){return new u("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return u.createStatic("State","fromStorageString"),Promise.resolve(new pe(JSON.parse(t)))}static async clearStaleState(t,s){let i=u.createStatic("State","clearStaleState"),r=U.getEpochTime()-s,o=await t.getAllKeys();i.debug("got keys",o);for(let n=0;n<o.length;n++){let a=o[n],c=await t.get(a),l=!1;if(c)try{let d=await pe.fromStorageString(c);i.debug("got item from key:",a,d.created),d.created<=r&&(l=!0)}catch(d){i.error("Error parsing state for key:",a,d),l=!0}else i.debug("no item in storage for key:",a),l=!0;l&&(i.debug("removed item for key:",a),t.remove(a))}}},Ie=class _e extends ne{constructor(t){super(t),this.code_verifier=t.code_verifier,this.code_challenge=t.code_challenge,this.authority=t.authority,this.client_id=t.client_id,this.redirect_uri=t.redirect_uri,this.scope=t.scope,this.client_secret=t.client_secret,this.extraTokenParams=t.extraTokenParams,this.response_mode=t.response_mode,this.skipUserInfo=t.skipUserInfo,this.nonce=t.nonce}static async create(t){let s=t.code_verifier===!0?_.generateCodeVerifier():t.code_verifier||void 0,i=s?await _.generateCodeChallenge(s):void 0;return new _e({...t,code_verifier:s,code_challenge:i})}toStorageString(){return new u("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo,nonce:this.nonce})}static fromStorageString(t){u.createStatic("SigninState","fromStorageString");let s=JSON.parse(t);return _e.create(s)}},xe=class Ue{constructor(t){this.url=t.url,this.state=t.state}static async create({url:t,authority:s,client_id:i,redirect_uri:r,response_type:o,scope:n,state_data:a,response_mode:c,request_type:l,client_secret:d,nonce:h,url_state:p,resource:y,skipUserInfo:J,extraQueryParams:L,extraTokenParams:W,disablePKCE:K,dpopJkt:A,omitScopeWhenRequesting:F,...O}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!i)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!o)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("create: No scope passed"),new Error("scope");if(!s)throw this._logger.error("create: No authority passed"),new Error("authority");let T=await Ie.create({data:a,request_type:l,url_state:p,code_verifier:!K,client_id:i,authority:s,redirect_uri:r,response_mode:c,client_secret:d,scope:n,extraTokenParams:W,skipUserInfo:J,nonce:h}),w=new URL(t);w.searchParams.append("client_id",i),w.searchParams.append("redirect_uri",r),w.searchParams.append("response_type",o),F||w.searchParams.append("scope",n),h&&w.searchParams.append("nonce",h),A&&w.searchParams.append("dpop_jkt",A);let I=T.id;p&&(I=`${I}${Y}${p}`),w.searchParams.append("state",I),T.code_challenge&&(w.searchParams.append("code_challenge",T.code_challenge),w.searchParams.append("code_challenge_method","S256")),y&&(Array.isArray(y)?y:[y]).forEach(S=>w.searchParams.append("resource",S));for(let[x,S]of Object.entries({response_mode:c,...O,...L}))S!=null&&w.searchParams.append(x,S.toString());return new Ue({url:w.href,state:T})}};xe._logger=new u("SigninRequest");var dt=xe,ht="openid",ce=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){let t=decodeURIComponent(this.state).split(Y);this.state=t[0],t.length>1&&(this.url_state=t.slice(1).join(Y))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-U.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+U.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(ht))||!!this.id_token}},ut=class{constructor({url:e,state_data:t,id_token_hint:s,post_logout_redirect_uri:i,extraQueryParams:r,request_type:o,client_id:n,url_state:a}){if(this._logger=new u("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");let c=new URL(e);if(s&&c.searchParams.append("id_token_hint",s),n&&c.searchParams.append("client_id",n),i&&(c.searchParams.append("post_logout_redirect_uri",i),t||a)){this.state=new ne({data:t,request_type:o,url_state:a});let l=this.state.id;a&&(l=`${l}${Y}${a}`),c.searchParams.append("state",l)}for(let[l,d]of Object.entries({...r}))d!=null&&c.searchParams.append(l,d.toString());this.url=c.href}},gt=class{constructor(e){if(this.state=e.get("state"),this.state){let t=decodeURIComponent(this.state).split(Y);this.state=t[0],t.length>1&&(this.url_state=t.slice(1).join(Y))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},pt=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],_t=["sub","iss","aud","exp","iat"],wt=class{constructor(e){this._settings=e,this._logger=new u("ClaimsService")}filterProtocolClaims(e){let t={...e};if(this._settings.filterProtocolClaims){let s;Array.isArray(this._settings.filterProtocolClaims)?s=this._settings.filterProtocolClaims:s=pt;for(let i of s)_t.includes(i)||delete t[i]}return t}mergeClaims(e,t){let s={...e};for(let[i,r]of Object.entries(t))if(s[i]!==r)if(Array.isArray(s[i])||Array.isArray(r))if(this._settings.mergeClaimsStrategy.array=="replace")s[i]=r;else{let o=Array.isArray(s[i])?s[i]:[s[i]];for(let n of Array.isArray(r)?r:[r])o.includes(n)||o.push(n);s[i]=o}else typeof s[i]=="object"&&typeof r=="object"?s[i]=this.mergeClaims(s[i],r):s[i]=r;return s}},qe=class{constructor(e,t){this.keys=e,this.nonce=t}},ft=class{constructor(e,t){this._logger=new u("OidcClient"),this.settings=e instanceof ge?e:new ge(e),this.metadataService=t??new it(this.settings),this._claimsService=new wt(this.settings),this._validator=new lt(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Pe(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:s,request_type:i,id_token_hint:r,login_hint:o,skipUserInfo:n,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:d=this.settings.scope,redirect_uri:h=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:y=this.settings.display,max_age:J=this.settings.max_age,ui_locales:L=this.settings.ui_locales,acr_values:W=this.settings.acr_values,resource:K=this.settings.resource,response_mode:A=this.settings.response_mode,extraQueryParams:F=this.settings.extraQueryParams,extraTokenParams:O=this.settings.extraTokenParams,dpopJkt:T,omitScopeWhenRequesting:w=this.settings.omitScopeWhenRequesting}){let I=this._logger.create("createSigninRequest");if(l!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");let x=await this.metadataService.getAuthorizationEndpoint();I.debug("Received authorization endpoint",x);let S=await dt.create({url:x,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:h,response_type:l,scope:d,state_data:e,url_state:c,prompt:p,display:y,max_age:J,ui_locales:L,id_token_hint:r,login_hint:o,acr_values:W,dpopJkt:T,resource:K,request:t,request_uri:s,extraQueryParams:F,extraTokenParams:O,request_type:i,response_mode:A,client_secret:this.settings.client_secret,skipUserInfo:n,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:w});await this.clearStaleState();let z=S.state;return await this.settings.stateStore.set(z.id,z.toStorageString()),S}async readSigninResponseState(e,t=!1){let s=this._logger.create("readSigninResponseState"),i=new ce(he.readParams(e,this.settings.response_mode));if(!i.state)throw s.throw(new Error("No state in response")),null;let r=await this.settings.stateStore[t?"remove":"get"](i.state);if(!r)throw s.throw(new Error("No matching state found in storage")),null;return{state:await Ie.fromStorageString(r),response:i}}async processSigninResponse(e,t,s=!0){let i=this._logger.create("processSigninResponse"),{state:r,response:o}=await this.readSigninResponseState(e,s);if(i.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){let n=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:n}}try{await this._validator.validateSigninResponse(o,r,t)}catch(n){if(n instanceof ue&&this.settings.dpop){let a=await this.getDpopProof(this.settings.dpop.store,n.nonce);t.DPoP=a,await this._validator.validateSigninResponse(o,r,t)}else throw n}return o}async getDpopProof(e,t){let s,i;return(await e.getAllKeys()).includes(this.settings.client_id)?(i=await e.get(this.settings.client_id),i.nonce!==t&&t&&(i.nonce=t,await e.set(this.settings.client_id,i))):(s=await _.generateDPoPKeys(),i=new qe(s,t),await e.set(this.settings.client_id,i)),await _.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:i.keys,nonce:i.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s=!1,extraTokenParams:i={}}){let r=await this._tokenClient.exchangeCredentials({username:e,password:t,...i}),o=new ce(new URLSearchParams);return Object.assign(o,r),await this._validator.validateCredentialsResponse(o,s),o}async useRefreshToken({state:e,redirect_uri:t,resource:s,timeoutInSeconds:i,extraHeaders:r,extraTokenParams:o}){var n;let a=this._logger.create("useRefreshToken"),c;if(this.settings.refreshTokenAllowedScope===void 0)c=e.scope;else{let h=this.settings.refreshTokenAllowedScope.split(" ");c=(((n=e.scope)==null?void 0:n.split(" "))||[]).filter(y=>h.includes(y)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){let h=await this.getDpopProof(this.settings.dpop.store);r={...r,DPoP:h}}let l;try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:s,timeoutInSeconds:i,extraHeaders:r,...o})}catch(h){if(h instanceof ue&&this.settings.dpop)r.DPoP=await this.getDpopProof(this.settings.dpop.store,h.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:s,timeoutInSeconds:i,extraHeaders:r,...o});else throw h}let d=new ce(new URLSearchParams);return Object.assign(d,l),a.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...e,scope:c}),d}async createSignoutRequest({state:e,id_token_hint:t,client_id:s,request_type:i,url_state:r,post_logout_redirect_uri:o=this.settings.post_logout_redirect_uri,extraQueryParams:n=this.settings.extraQueryParams}={}){let a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),!s&&o&&!t&&(s=this.settings.client_id);let l=new ut({url:c,id_token_hint:t,client_id:s,post_logout_redirect_uri:o,state_data:e,extraQueryParams:n,request_type:i,url_state:r});await this.clearStaleState();let d=l.state;return d&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(d.id,d.toStorageString())),l}async readSignoutResponseState(e,t=!1){let s=this._logger.create("readSignoutResponseState"),i=new gt(he.readParams(e,this.settings.response_mode));if(!i.state){if(s.debug("No state in response"),i.error)throw s.warn("Response was error:",i.error),new V(i);return{state:void 0,response:i}}let r=await this.settings.stateStore[t?"remove":"get"](i.state);if(!r)throw s.throw(new Error("No matching state found in storage")),null;return{state:await ne.fromStorageString(r),response:i}}async processSignoutResponse(e){let t=this._logger.create("processSignoutResponse"),{state:s,response:i}=await this.readSignoutResponseState(e,!0);return s?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,s)):t.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),ne.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},mt=class{constructor(e){this._userManager=e,this._logger=new u("SessionMonitor"),this._start=async t=>{let s=t.session_state;if(!s)return;let i=this._logger.create("_start");if(t.profile?(this._sub=t.profile.sub,i.debug("session_state",s,", sub",this._sub)):(this._sub=void 0,i.debug("session_state",s,", anonymous user")),this._checkSessionIFrame){this._checkSessionIFrame.start(s);return}try{let r=await this._userManager.metadataService.getCheckSessionIframe();if(r){i.debug("initializing check session iframe");let o=this._userManager.settings.client_id,n=this._userManager.settings.checkSessionIntervalInSeconds,a=this._userManager.settings.stopCheckSessionOnError,c=new st(this._callback,o,r,n,a);await c.load(),this._checkSessionIFrame=c,c.start(s)}else i.warn("no check session iframe found in the metadata")}catch(r){i.error("Error from getCheckSessionIframe:",r instanceof Error?r.message:r)}},this._stop=()=>{let t=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){let s=setInterval(async()=>{clearInterval(s);try{let i=await this._userManager.querySessionStatus();if(i){let r={session_state:i.session_state,profile:i.sub?{sub:i.sub}:null};this._start(r)}}catch(i){t.error("error from querySessionStatus",i instanceof Error?i.message:i)}},1e3)}},this._callback=async()=>{let t=this._logger.create("_callback");try{let s=await this._userManager.querySessionStatus(),i=!0;s&&this._checkSessionIFrame?s.sub===this._sub?(i=!1,this._checkSessionIFrame.start(s.session_state),t.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",s.session_state),await this._userManager.events._raiseUserSessionChanged()):t.debug("different subject signed into OP",s.sub):t.debug("subject no longer signed into OP"),i?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():t.debug("no change in session detected, no event to raise")}catch(s){this._sub&&(t.debug("Error calling queryCurrentSigninSession; raising signed out event",s),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(t=>{this._logger.error(t)})}async _init(){this._logger.create("_init");let e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){let t=await this._userManager.querySessionStatus();if(t){let s={session_state:t.session_state,profile:t.sub?{sub:t.sub}:null};this._start(s)}}}},le=class Ae{constructor(t){var s;this.id_token=t.id_token,this.session_state=(s=t.session_state)!=null?s:null,this.access_token=t.access_token,this.refresh_token=t.refresh_token,this.token_type=t.token_type,this.scope=t.scope,this.profile=t.profile,this.expires_at=t.expires_at,this.state=t.userState,this.url_state=t.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-U.getEpochTime()}set expires_in(t){t!==void 0&&(this.expires_at=Math.floor(t)+U.getEpochTime())}get expired(){let t=this.expires_in;if(t!==void 0)return t<=0}get scopes(){var t,s;return(s=(t=this.scope)==null?void 0:t.split(" "))!=null?s:[]}toStorageString(){return new u("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return u.createStatic("User","fromStorageString"),new Ae(JSON.parse(t))}},Ee="oidc-client",Oe=class{constructor(){this._abort=new N("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){let t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);let{url:s,keepOpen:i}=await new Promise((r,o)=>{let n=c=>{var l;let d=c.data,h=(l=e.scriptOrigin)!=null?l:window.location.origin;if(!(c.origin!==h||d?.source!==Ee)){try{let p=he.readParams(d.url,e.response_mode).get("state");if(p||t.warn("no state found in response url"),c.source!==this._window&&p!==e.state)return}catch{this._dispose(),o(new Error("Invalid response from window"))}r(d)}};window.addEventListener("message",n,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",n,!1));let a=new BroadcastChannel(`oidc-client-popup-${e.state}`);a.addEventListener("message",n,!1),this._disposeHandlers.add(()=>a.close()),this._disposeHandlers.add(this._abort.addHandler(c=>{this._dispose(),o(c)}))});return t.debug("got response from window"),this._dispose(),i||this.close(),{url:s}}_dispose(){this._logger.create("_dispose");for(let e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,s=!1,i=window.location.origin){let r={source:Ee,url:t,keepOpen:s},o=new u("_notifyParent");if(e)o.debug("With parent. Using parent.postMessage."),e.postMessage(r,i);else{o.debug("No parent. Using BroadcastChannel.");let n=new URL(t).searchParams.get("state");if(!n)throw new Error("No parent and no state in URL. Can't complete notification.");let a=new BroadcastChannel(`oidc-client-popup-${n}`);a.postMessage(r),a.close()}}},Ne={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Me="_blank",yt=60,St=2,He=10,vt=class extends ge{constructor(e){let{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:s=e.post_logout_redirect_uri,popupWindowFeatures:i=Ne,popupWindowTarget:r=Me,redirectMethod:o="assign",redirectTarget:n="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:d=e.redirect_uri,silentRequestTimeoutInSeconds:h,automaticSilentRenew:p=!0,validateSubOnSilentRenew:y=!0,includeIdTokenInSilentRenew:J=!1,monitorSession:L=!1,monitorAnonymousSession:W=!1,checkSessionIntervalInSeconds:K=St,query_status_response_type:A="code",stopCheckSessionOnError:F=!0,revokeTokenTypes:O=["access_token","refresh_token"],revokeTokensOnSignout:T=!1,includeIdTokenInSilentSignout:w=!1,accessTokenExpiringNotificationTimeInSeconds:I=yt,maxSilentRenewTimeoutRetries:x,userStore:S}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=s,this.popupWindowFeatures=i,this.popupWindowTarget=r,this.redirectMethod=o,this.redirectTarget=n,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=d,this.silentRequestTimeoutInSeconds=h||l||He,this.automaticSilentRenew=p,this.validateSubOnSilentRenew=y,this.includeIdTokenInSilentRenew=J,this.monitorSession=L,this.monitorAnonymousSession=W,this.checkSessionIntervalInSeconds=K,this.stopCheckSessionOnError=F,this.query_status_response_type=A,this.revokeTokenTypes=O,this.revokeTokensOnSignout=T,this.includeIdTokenInSilentSignout=w,this.accessTokenExpiringNotificationTimeInSeconds=I,this.maxSilentRenewTimeoutRetries=x,S)this.userStore=S;else{let z=typeof window<"u"?window.sessionStorage:new oe;this.userStore=new te({store:z})}}},Te=class je extends Oe{constructor({silentRequestTimeoutInSeconds:t=He}){super(),this._logger=new u("IFrameWindow"),this._timeoutInSeconds=t,this._frame=je.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){let t=window.document.createElement("iframe");return t.style.visibility="hidden",t.style.position="fixed",t.style.left="-1000px",t.style.top="0",t.width="0",t.height="0",window.document.body.appendChild(t),t}async navigate(t){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);let s=setTimeout(()=>void this._abort.raise(new we("IFrame timed out without a response")),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(s)),await super.navigate(t)}close(){var t;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",s=>{var i;let r=s.target;(i=r.parentNode)==null||i.removeChild(r),this._abort.raise(new Error("IFrame removed from DOM"))},!0),(t=this._frame.contentWindow)==null||t.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(t,s){return super._notifyParent(window.parent,t,!1,s)}},bt=class{constructor(e){this._settings=e,this._logger=new u("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Te({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Te.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},kt=500,Et=1e3,Re=class extends Oe{constructor({popupWindowTarget:e=Me,popupWindowFeatures:t={},popupSignal:s,popupAbortOnClose:i}){super(),this._logger=new u("PopupWindow");let r=ke.center({...Ne,...t});this._window=window.open(void 0,e,ke.serialize(r)),this.abortOnClose=!!i,s&&s.addEventListener("abort",()=>{var o;this._abort.raise(new Error((o=s.reason)!=null?o:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{if(!this._window||typeof this._window.closed!="boolean"||this._window.closed){this._abort.raise(new Error("Popup blocked by user"));return}this.close()},t.closePopupWindowAfterInSeconds*Et)}async navigate(e){var t;(t=this._window)==null||t.focus();let s=setInterval(()=>{(!this._window||this._window.closed)&&(this._logger.debug("Popup closed by user or isolated by redirect"),i(),this._disposeHandlers.delete(i),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},kt),i=()=>clearInterval(s);return this._disposeHandlers.add(i),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),!t&&!window.opener&&window.close()}},Tt=class{constructor(e){this._settings=e,this._logger=new u("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:s,popupAbortOnClose:i}){return new Re({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:s,popupAbortOnClose:i})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Re.notifyOpener(e,t)}},Rt=class{constructor(e){this._settings=e,this._logger=new u("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var s;this._logger.create("prepare");let i=window.self;t==="top"&&(i=(s=window.top)!=null?s:window.self);let r=i.location[e].bind(i.location),o;return{navigate:async n=>(this._logger.create("navigate"),await new Promise((c,l)=>{o=l,window.addEventListener("pageshow",()=>c(window.location.href)),r(n.url)})),close:()=>{this._logger.create("close"),o?.(new Error("Redirect aborted")),i.stop()}}}async callback(){}},Ct=class extends tt{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new u("UserManagerEvents"),this._userLoaded=new N("User loaded"),this._userUnloaded=new N("User unloaded"),this._silentRenewError=new N("Silent renew error"),this._userSignedIn=new N("User signed in"),this._userSignedOut=new N("User signed out"),this._userSessionChanged=new N("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Pt=class{constructor(e){this._userManager=e,this._logger=new u("SilentRenewService"),this._isStarted=!1,this._retryTimer=new U("Retry Silent Renew"),this._timeoutRetryCount=0,this._tokenExpiring=async()=>{let t=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),this._timeoutRetryCount=0,t.debug("silent token renewal successful")}catch(s){if(s instanceof we){this._timeoutRetryCount++;let i=this._userManager.settings.maxSilentRenewTimeoutRetries;if(i!==void 0&&this._timeoutRetryCount>i){t.error(`Timeout retry limit reached (${this._timeoutRetryCount} > ${i}), raising silentRenewError:`,s),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(s);return}t.warn(`ErrorTimeout from signinSilent (attempt ${this._timeoutRetryCount}), retry in 5s:`,s),this._retryTimer.init(5);return}t.error("Error from signinSilent:",s),this._timeoutRetryCount=0,await this._userManager.events._raiseSilentRenewError(s)}}}async start(){let e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},It=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},De=class{constructor(e,t,s,i){this._logger=new u("UserManager"),this.settings=new vt(e),this._client=new ft(e),this._redirectNavigator=t??new Rt(this.settings),this._popupNavigator=s??new Tt(this.settings),this._iframeNavigator=i??new bt(this.settings),this._events=new Ct(this.settings),this._silentRenewService=new Pt(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new mt(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){let t=this._logger.create("getUser"),s=await this._loadUser();return s?(t.info("user loaded"),await this._events.load(s,e),s):(t.info("user not found in storage"),null)}async removeUser(){let e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");let{redirectMethod:s,...i}=e,r;(t=this.settings.dpop)!=null&&t.bind_authorization_code&&(r=await this.generateDPoPJkt(this.settings.dpop));let o=await this._redirectNavigator.prepare({redirectMethod:s});await this._signinStart({request_type:"si:r",dpopJkt:r,...i},o)}async signinRedirectCallback(e=window.location.href){let t=this._logger.create("signinRedirectCallback"),s=await this._signinEnd(e);return s.profile&&s.profile.sub?t.info("success, signed in subject",s.profile.sub):t.info("no subject"),s}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:s=!1}){let i=this._logger.create("signinResourceOwnerCredential"),r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s,extraTokenParams:this.settings.extraTokenParams});i.debug("got signin response");let o=await this._buildUser(r);return o.profile&&o.profile.sub?i.info("success, signed in subject",o.profile.sub):i.info("no subject"),o}async signinPopup(e={}){var t;let s=this._logger.create("signinPopup"),i;(t=this.settings.dpop)!=null&&t.bind_authorization_code&&(i=await this.generateDPoPJkt(this.settings.dpop));let{popupWindowFeatures:r,popupWindowTarget:o,popupSignal:n,popupAbortOnClose:a,...c}=e,l=this.settings.popup_redirect_uri;l||s.throw(new Error("No popup_redirect_uri configured"));let d=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:o,popupSignal:n,popupAbortOnClose:a}),h=await this._signin({request_type:"si:p",redirect_uri:l,display:"popup",dpopJkt:i,...c},d);return h&&(h.profile&&h.profile.sub?s.info("success, signed in subject",h.profile.sub):s.info("no subject")),h}async signinPopupCallback(e=window.location.href,t=!1){let s=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),s.info("success")}async signinSilent(e={}){var t,s;let i=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...o}=e,n=await this._loadUser();if(!e.forceIframeAuth&&n?.refresh_token){i.debug("using refresh token");let h=new It(n);return await this._useRefreshToken({state:h,redirect_uri:o.redirect_uri,resource:o.resource,extraTokenParams:o.extraTokenParams,timeoutInSeconds:r})}let a;(t=this.settings.dpop)!=null&&t.bind_authorization_code&&(a=await this.generateDPoPJkt(this.settings.dpop));let c=this.settings.silent_redirect_uri;c||i.throw(new Error("No silent_redirect_uri configured"));let l;n&&this.settings.validateSubOnSilentRenew&&(i.debug("subject prior to silent renew:",n.profile.sub),l=n.profile.sub);let d=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});return n=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?n?.id_token:void 0,dpopJkt:a,...o},d,l),n&&((s=n.profile)!=null&&s.sub?i.info("success, signed in subject",n.profile.sub):i.info("no subject")),n}async _useRefreshToken(e){let t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),s=new le({...e.state,...t});return await this.storeUser(s),await this._events.load(s),s}async signinSilentCallback(e=window.location.href){let t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){let{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid request_type in state")}}async signoutCallback(e=window.location.href,t=!1){let{state:s}=await this._client.readSignoutResponseState(e);if(s)switch(s.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid request_type in state")}}async querySessionStatus(e={}){let t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:s,...i}=e,r=this.settings.silent_redirect_uri;r||t.throw(new Error("No silent_redirect_uri configured"));let o=await this._loadUser(),n=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s}),a=await this._signinStart({request_type:"si:s",redirect_uri:r,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?o?.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...i},n);try{let c={},l=await this._client.processSigninResponse(a.url,c);return t.debug("got signin response"),l.session_state&&l.profile.sub?(t.info("success for subject",l.profile.sub),{session_state:l.session_state,sub:l.profile.sub}):(t.info("success, user not authenticated"),null)}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof V)switch(c.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:c.session_state}}throw c}}async _signin(e,t,s){let i=await this._signinStart(e,t);return await this._signinEnd(i.url,s)}async _signinStart(e,t){let s=this._logger.create("_signinStart");try{let i=await this._client.createSigninRequest(e);return s.debug("got signin request"),await t.navigate({url:i.url,state:i.state.id,response_mode:i.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(i){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signinEnd(e,t){let s=this._logger.create("_signinEnd"),i={},r=await this._client.processSigninResponse(e,i);return s.debug("got signin response"),await this._buildUser(r,t)}async _buildUser(e,t){let s=this._logger.create("_buildUser"),i=new le(e);if(t){if(t!==i.profile.sub)throw s.debug("current user does not match user returned from signin. sub from signin:",i.profile.sub),new V({...e,error:"login_required"});s.debug("current user matches user returned from signin")}return await this.storeUser(i),s.debug("user stored"),await this._events.load(i),i}async signoutRedirect(e={}){let t=this._logger.create("signoutRedirect"),{redirectMethod:s,...i}=e,r=await this._redirectNavigator.prepare({redirectMethod:s});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...i},r),t.info("success")}async signoutRedirectCallback(e=window.location.href){let t=this._logger.create("signoutRedirectCallback"),s=await this._signoutEnd(e);return t.info("success"),s}async signoutPopup(e={}){let t=this._logger.create("signoutPopup"),{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:r,...o}=e,n=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:r});await this._signout({request_type:"so:p",post_logout_redirect_uri:n,state:n==null?void 0:{},...o},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){let s=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),s.info("success")}async _signout(e,t){let s=await this._signoutStart(e,t);return await this._signoutEnd(s.url)}async _signoutStart(e={},t){var s;let i=this._logger.create("_signoutStart");try{let r=await this._loadUser();i.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);let o=e.id_token_hint||r&&r.id_token;o&&(i.debug("setting id_token_hint in signout request"),e.id_token_hint=o),await this.removeUser(),i.debug("user removed, creating signout request");let n=await this._client.createSignoutRequest(e);return i.debug("got signout request"),await t.navigate({url:n.url,state:(s=n.state)==null?void 0:s.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(r){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),r}}async _signoutEnd(e){let t=this._logger.create("_signoutEnd"),s=await this._client.processSignoutResponse(e);return t.debug("got signout response"),s}async signoutSilent(e={}){var t;let s=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:i,...r}=e,o=this.settings.includeIdTokenInSilentSignout?(t=await this._loadUser())==null?void 0:t.id_token:void 0,n=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i});await this._signout({request_type:"so:s",post_logout_redirect_uri:n,id_token_hint:o,...r},a),s.info("success")}async signoutSilentCallback(e=window.location.href){let t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){let t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){let s=this._logger.create("_revokeInternal");if(!e)return;let i=t.filter(r=>typeof e[r]=="string");if(!i.length){s.debug("no need to revoke due to no token(s)");return}for(let r of i)await this._client.revokeToken(e[r],r),s.info(`${r} revoked successfully`),r!=="access_token"&&(e[r]=null);await this.storeUser(e),s.debug("user stored"),await this._events.load(e)}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){let e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),le.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){let t=this._logger.create("storeUser");if(e){t.debug("storing user");let s=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,s)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,s,i){var r,o;let n=await((o=(r=this.settings.dpop)==null?void 0:r.store)==null?void 0:o.get(this.settings.client_id));if(n)return await _.generateDPoPProof({url:e,accessToken:t?.access_token,httpMethod:s,keyPair:n.keys,nonce:i})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){let s=await _.generateDPoPKeys();t=new qe(s),await e.store.set(this.settings.client_id,t)}return await _.generateDPoPJkt(t.keys)}};var g=e=>document.getElementById(e),E=g("messages"),q,X,Q=null,m=0,D=!1,se=null,$e=0,M=0,H=null,G=class extends Error{},k=class extends Error{},j=(e,t)=>e instanceof G?e.message:t,ae=new Set,f=e=>{g("status").textContent=e};function ye(){let e=H;return M++,H=null,D=!1,g("activity").hidden=!0,g("cancel-question").hidden=!0,e}function $(){m++,M++,H=null,Q=null,D=!1;for(let e of ae)e.abort();ae.clear(),E.replaceChildren(),g("question").value="",g("workspace").hidden=!0,g("welcome").hidden=!1,g("sign-out").hidden=!0,g("new-answer").hidden=!0,g("activity").hidden=!0,g("cancel-question").hidden=!0,g("sources").replaceChildren()}async function v(e,{method:t="GET",data:s,bootstrapToken:i}={}){let r=m,o=new AbortController;ae.add(o);let n=setTimeout(()=>o.abort(),45e3);try{let a=await fetch(e,{method:t,cache:"no-store",credentials:"same-origin",redirect:"error",signal:o.signal,headers:{"X-Workspace-Request":"session",...s!==void 0?{"Content-Type":"application/json"}:{},...Q?{"X-CSRF-Token":Q}:{},...i?{Authorization:"Bearer "+i}:{}},...s!==void 0?{body:JSON.stringify(s)}:{}});if(r!==m)throw new k;let c=null;if(a.status!==204&&(c=await a.json()),r!==m)throw new k;if(a.status===401||a.status===403)throw $(),new G(c?.error?.message||"Sign in with your company account to continue.");if(!a.ok){let l=new G(c?.error?.message||"The workspace is temporarily unavailable. Please try again.");throw l.retryable=a.status>=500,l}return c}finally{clearTimeout(n),ae.delete(o)}}var xt={connected:"Connected",refreshing:"Connection updating\u2026",needs_reconnect:"Connect to search your sources.",revoked:"Disconnected",needs_setup:"Your workspace owner needs to enable access."};function Ut(e){g("sources").replaceChildren();let t=!0;for(let s of e){let i=document.createElement("li"),r=document.createElement("strong"),o=document.createElement("p");r.textContent=s.name,o.textContent=xt[s.status]||"Connection unavailable",i.append(r,o);let n=document.createElement("button");if(n.type="button",s.status==="connected"&&(n.className="quiet"),n.textContent=s.status==="connected"?"Reconnect":"Connect",n.disabled=s.status==="needs_setup"||s.status==="refreshing",n.addEventListener("click",()=>At(s.id)),i.append(n),s.status==="connected"){let a=document.createElement("button");a.type="button",a.textContent="Disconnect",a.className="quiet disconnect",a.addEventListener("click",async()=>{let c=ye();try{c&&await v("/api/queries/"+encodeURIComponent(c),{method:"DELETE"}),await v("/api/sources/"+encodeURIComponent(s.id),{method:"DELETE"}),E.replaceChildren(),await Z(),f(s.name+" disconnected.")}catch{f("Could not disconnect the source. Refresh and try again.")}}),i.append(a)}else t=!1;g("sources").append(i)}e.some(s=>["needs_reconnect","revoked","needs_setup"].includes(s.status))&&(ye(),E.replaceChildren()),g("send").disabled=!t||D}async function Z(e=!1){if(!e&&se?.epoch===m)return se.promise;let t={epoch:m,serial:++$e};t.promise=(async()=>{let s=await v("/api/session");return t.serial!==$e||(Q=s.csrfToken,g("welcome").hidden=!0,g("workspace").hidden=!1,g("sign-out").hidden=!1,Ut(s.sources)),s})(),se=t;try{return await t.promise}finally{se===t&&(se=null)}}function qt(){return E.scrollHeight-E.scrollTop-E.clientHeight<80}function Je(e,t,s=[]){let i=qt(),r=document.createElement("li"),o=document.createElement("span"),n=document.createElement("div");r.className=e,o.className="message-label",o.textContent=e==="user"?"You":"Company knowledge",n.textContent=t,r.append(o,n);for(let a of s){let c=document.createElement("div"),l=document.createElement("blockquote");c.className="citation",l.textContent=a.quote;try{let d=new URL(a.url);if(d.protocol!=="https:"||!q.citationHosts.includes(d.hostname)||d.username||d.password)throw Error();let h=document.createElement("a");h.href=d.href,h.target="_blank",h.rel="noopener noreferrer",h.textContent=a.title,c.append(h)}catch{let d=document.createElement("strong");d.textContent=a.title,c.append(d)}c.append(l),r.append(c)}E.append(r),g("intro").hidden=!0,i?E.scrollTop=E.scrollHeight:g("new-answer").hidden=!1}async function At(e){try{let t=await v("/api/sources/"+encodeURIComponent(e)+"/connect",{method:"POST",data:{}}),s=new URL(t.authorizationUrl);if(!q.authorizationOrigins.includes(s.origin))throw Error();location.assign(s.href)}catch(t){t instanceof k||f(j(t,"Could not open the source connection. Try again."))}}g("sign-in").addEventListener("click",async()=>{try{await X.clearStaleState(),await X.signinRedirect()}catch{f("Company sign-in is unavailable. Please try again shortly.")}});g("sign-out").addEventListener("click",async()=>{let e=!1;try{await v("/api/session",{method:"DELETE"}),e=!0}catch{}finally{$(),await X?.removeUser(),f(e?"Signed out of this workspace.":"Sign-out could not be confirmed. Reload this page and try again.")}});g("new-answer").addEventListener("click",()=>{E.scrollTop=E.scrollHeight,g("new-answer").hidden=!0});var me={source:"Reconnect your company sources, then ask again.",setup:"Your workspace owner needs to enable source access for your account.",signin:"Sign in again to continue.",unavailable:"Your workspace could not finish this answer. Please try again shortly.",answer:"The answer could not be verified against your current sources. Please try again."};async function Le(e,t=null){let s=m,i=++M;D=!0,H=t,g("send").disabled=!0,g("activity").hidden=!1,g("cancel-question").hidden=!1,Je("user",e),g("question").value="",f("");try{if(!H){let n=await v("/api/queries",{method:"POST",data:{question:e,requestId:crypto.randomUUID()}});if(s!==m)throw new k;if(i!==M){await v("/api/queries/"+encodeURIComponent(n.id),{method:"DELETE"});return}H=n.id}let r=H,o=Date.now()+900*1e3;for(;s===m&&i===M;){if(Date.now()>o)throw await v("/api/queries/"+encodeURIComponent(r),{method:"DELETE"}),new G("This question could not finish in time. Please try again.");let n;try{n=await v("/api/queries/"+encodeURIComponent(r))}catch(a){if(a.retryable){f(j(a,me.unavailable)),await new Promise(c=>setTimeout(c,2e3));continue}throw a}if(s!==m||i!==M)throw new k;if(n.status==="ready"){Je("assistant",n.result.answer,n.result.citations),f("");break}if(n.status==="failed")throw new G(me[n.errorCode]||me.unavailable);if(n.status==="cancelled"||n.status==="expired"){f(n.status==="cancelled"?"Question cancelled.":"This question expired. Please ask again.");break}await new Promise(a=>setTimeout(a,1200))}}catch(r){s===m&&i===M&&!(r instanceof k)&&f(r.name==="AbortError"?"The connection was interrupted. Reload to resume your question.":j(r,"Could not verify an answer. Please try again."))}finally{if(s===m&&i===M&&(D=!1,H=null,g("activity").hidden=!0,g("cancel-question").hidden=!0,Q))try{await Z(!0)}catch(r){r instanceof k||($(),f(j(r,"We could not confirm access. Sign in again or retry shortly.")))}}}g("ask").addEventListener("submit",e=>{if(e.preventDefault(),D)return;let t=g("question").value.trim();t&&Le(t)});g("cancel-question").addEventListener("click",async()=>{let e=m,t=ye();g("send").disabled=!1;try{t&&await v("/api/queries/"+encodeURIComponent(t),{method:"DELETE"}),e===m&&f("Question cancelled.")}catch(s){e===m&&f(j(s,"Cancellation could not be confirmed. Please try again."))}});window.addEventListener("pagehide",$);window.addEventListener("pageshow",e=>{e.persisted&&Z().catch(()=>{$(),f("Sign in to reopen your workspace.")})});document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Q&&Z().catch(e=>{e instanceof k||($(),f(j(e,"Access could not be confirmed. Sign in again.")))})});async function Ot(){try{q=await(await fetch("/api/web-config",{cache:"no-store",credentials:"omit",redirect:"error"})).json();let e={issuer:q.company.issuer,authorization_endpoint:q.company.authorizationEndpoint,token_endpoint:q.company.tokenEndpoint};if(X=new De({authority:q.company.issuer,client_id:q.company.clientId,redirect_uri:location.origin+"/company-callback",response_type:"code",scope:q.company.scopes.join(" "),metadata:e,loadUserInfo:!1,automaticSilentRenew:!1,monitorSession:!1,disablePKCE:!1,requestTimeoutInSeconds:15,staleStateAgeInSeconds:300,userStore:new te({store:new oe}),stateStore:new te({store:window.sessionStorage})}),location.pathname==="/company-callback"){let s=location.href;history.replaceState(null,"","/");let i;try{i=await X.signinRedirectCallback(s),await v("/api/session",{method:"POST",data:{},bootstrapToken:i.access_token})}finally{await X.removeUser(),i=null}}else location.search&&history.replaceState(null,"","/");let t=await Z();if(f(""),t.sources.every(s=>s.status==="connected")){let s=await v("/api/queries"),i=s.queries.at(-1);i&&!D&&Le(i.question,i.id)}}catch(e){$(),f(j(e,"Sign in with your company account to open your workspace."))}}setInterval(()=>{Q&&!D&&document.visibilityState==="visible"&&Z().catch(e=>{e instanceof k||($(),f(j(e,"Access could not be confirmed. Sign in again or retry shortly.")))})},15e3);Ot();})();
@@ -0,0 +1,105 @@
1
+ import {UserManager,WebStorageStateStore,InMemoryWebStorage} from 'oidc-client-ts';
2
+ const $=id=>document.getElementById(id),messages=$('messages');
3
+ let config,manager,csrf=null,epoch=0,busy=false,sessionTask=null,sessionSerial=0,querySerial=0,activeQuery=null;
4
+ class WorkspaceError extends Error{}
5
+ class SessionChanged extends Error{}
6
+ const publicMessage=(error,fallback)=>error instanceof WorkspaceError?error.message:fallback;
7
+ const pending=new Set();
8
+ const say=text=>{$('status').textContent=text;};
9
+ function stopQuestion(){const identity=activeQuery;querySerial++;activeQuery=null;busy=false;$('activity').hidden=true;$('cancel-question').hidden=true;return identity;}
10
+ function clearPrivate(){
11
+ epoch++;querySerial++;activeQuery=null;csrf=null;busy=false;for(const controller of pending)controller.abort();pending.clear();messages.replaceChildren();$('question').value='';$('workspace').hidden=true;$('welcome').hidden=false;$('sign-out').hidden=true;$('new-answer').hidden=true;$('activity').hidden=true;$('cancel-question').hidden=true;$('sources').replaceChildren();
12
+ }
13
+ async function api(path,{method='GET',data,bootstrapToken}={}){
14
+ const generation=epoch,controller=new AbortController();pending.add(controller);const timeout=setTimeout(()=>controller.abort(),45000);
15
+ try{
16
+ const response=await fetch(path,{method,cache:'no-store',credentials:'same-origin',redirect:'error',signal:controller.signal,headers:{'X-Workspace-Request':'session',...(data!==undefined?{'Content-Type':'application/json'}:{}),...(csrf?{'X-CSRF-Token':csrf}:{}),...(bootstrapToken?{'Authorization':'Bearer '+bootstrapToken}:{})},...(data!==undefined?{body:JSON.stringify(data)}:{})});
17
+ if(generation!==epoch)throw new SessionChanged();
18
+ let result=null;if(response.status!==204)result=await response.json();
19
+ if(generation!==epoch)throw new SessionChanged();
20
+ if(response.status===401||response.status===403){clearPrivate();throw new WorkspaceError(result?.error?.message||'Sign in with your company account to continue.');}
21
+ if(!response.ok){const error=new WorkspaceError(result?.error?.message||'The workspace is temporarily unavailable. Please try again.');error.retryable=response.status>=500;throw error;}
22
+ return result;
23
+ }finally{clearTimeout(timeout);pending.delete(controller);}
24
+ }
25
+ const statusText={connected:'Connected',refreshing:'Connection updating…',needs_reconnect:'Connect to search your sources.',revoked:'Disconnected',needs_setup:'Your workspace owner needs to enable access.'};
26
+ function renderSources(rows){
27
+ $('sources').replaceChildren();let ready=true;
28
+ for(const row of rows){
29
+ const li=document.createElement('li'),label=document.createElement('strong'),state=document.createElement('p');label.textContent=row.name;state.textContent=statusText[row.status]||'Connection unavailable';li.append(label,state);
30
+ const connect=document.createElement('button');connect.type='button';if(row.status==='connected')connect.className='quiet';connect.textContent=row.status==='connected'?'Reconnect':'Connect';connect.disabled=row.status==='needs_setup'||row.status==='refreshing';connect.addEventListener('click',()=>connectSource(row.id));li.append(connect);
31
+ if(row.status==='connected'){
32
+ const remove=document.createElement('button');remove.type='button';remove.textContent='Disconnect';remove.className='quiet disconnect';remove.addEventListener('click',async()=>{const identity=stopQuestion();try{if(identity)await api('/api/queries/'+encodeURIComponent(identity),{method:'DELETE'});await api('/api/sources/'+encodeURIComponent(row.id),{method:'DELETE'});messages.replaceChildren();await session();say(row.name+' disconnected.');}catch{say('Could not disconnect the source. Refresh and try again.');}});li.append(remove);
33
+ }else ready=false;
34
+ $('sources').append(li);
35
+ }
36
+ if(rows.some(row=>['needs_reconnect','revoked','needs_setup'].includes(row.status))){stopQuestion();messages.replaceChildren();}$('send').disabled=!ready||busy;
37
+ }
38
+ async function session(fresh=false){
39
+ if(!fresh&&sessionTask?.epoch===epoch)return sessionTask.promise;
40
+ const task={epoch,serial:++sessionSerial};task.promise=(async()=>{const result=await api('/api/session');if(task.serial!==sessionSerial)return result;csrf=result.csrfToken;$('welcome').hidden=true;$('workspace').hidden=false;$('sign-out').hidden=false;renderSources(result.sources);return result;})();sessionTask=task;
41
+ try{return await task.promise;}finally{if(sessionTask===task)sessionTask=null;}
42
+ }
43
+ function nearBottom(){return messages.scrollHeight-messages.scrollTop-messages.clientHeight<80;}
44
+ function append(role,text,citations=[]){
45
+ const follow=nearBottom(),li=document.createElement('li'),label=document.createElement('span'),content=document.createElement('div');li.className=role;label.className='message-label';label.textContent=role==='user'?'You':'Company knowledge';content.textContent=text;li.append(label,content);
46
+ for(const citation of citations){
47
+ const block=document.createElement('div'),quote=document.createElement('blockquote');block.className='citation';quote.textContent=citation.quote;
48
+ try{const url=new URL(citation.url);if(url.protocol!=='https:'||!config.citationHosts.includes(url.hostname)||url.username||url.password)throw Error();const link=document.createElement('a');link.href=url.href;link.target='_blank';link.rel='noopener noreferrer';link.textContent=citation.title;block.append(link);}catch{const title=document.createElement('strong');title.textContent=citation.title;block.append(title);}
49
+ block.append(quote);li.append(block);
50
+ }
51
+ messages.append(li);$('intro').hidden=true;if(follow)messages.scrollTop=messages.scrollHeight;else $('new-answer').hidden=false;
52
+ }
53
+ async function connectSource(alias){
54
+ try{const result=await api('/api/sources/'+encodeURIComponent(alias)+'/connect',{method:'POST',data:{}}),url=new URL(result.authorizationUrl);if(!config.authorizationOrigins.includes(url.origin))throw Error();location.assign(url.href);}catch(error){if(!(error instanceof SessionChanged))say(publicMessage(error,'Could not open the source connection. Try again.'));}
55
+ }
56
+ $('sign-in').addEventListener('click',async()=>{try{await manager.clearStaleState();await manager.signinRedirect();}catch{say('Company sign-in is unavailable. Please try again shortly.');}});
57
+ $('sign-out').addEventListener('click',async()=>{let confirmed=false;try{await api('/api/session',{method:'DELETE'});confirmed=true;}catch{}finally{clearPrivate();await manager?.removeUser();say(confirmed?'Signed out of this workspace.':'Sign-out could not be confirmed. Reload this page and try again.');}});
58
+ $('new-answer').addEventListener('click',()=>{messages.scrollTop=messages.scrollHeight;$('new-answer').hidden=true;});
59
+ const queryErrors={source:'Reconnect your company sources, then ask again.',setup:'Your workspace owner needs to enable source access for your account.',signin:'Sign in again to continue.',unavailable:'Your workspace could not finish this answer. Please try again shortly.',answer:'The answer could not be verified against your current sources. Please try again.'};
60
+ async function runQuestion(question,existingId=null){
61
+ const generation=epoch,flow=++querySerial;busy=true;activeQuery=existingId;$('send').disabled=true;$('activity').hidden=false;$('cancel-question').hidden=false;append('user',question);$('question').value='';say('');
62
+ try{
63
+ if(!activeQuery){const submitted=await api('/api/queries',{method:'POST',data:{question,requestId:crypto.randomUUID()}});if(generation!==epoch)throw new SessionChanged();if(flow!==querySerial){await api('/api/queries/'+encodeURIComponent(submitted.id),{method:'DELETE'});return;}activeQuery=submitted.id;}
64
+ const identity=activeQuery,deadline=Date.now()+15*60*1000;
65
+ while(generation===epoch&&flow===querySerial){
66
+ if(Date.now()>deadline){await api('/api/queries/'+encodeURIComponent(identity),{method:'DELETE'});throw new WorkspaceError('This question could not finish in time. Please try again.');}
67
+ let status;
68
+ try{status=await api('/api/queries/'+encodeURIComponent(identity));}
69
+ catch(error){if(error.retryable){say(publicMessage(error,queryErrors.unavailable));await new Promise(resolve=>setTimeout(resolve,2000));continue;}throw error;}
70
+ if(generation!==epoch||flow!==querySerial)throw new SessionChanged();
71
+ if(status.status==='ready'){append('assistant',status.result.answer,status.result.citations);say('');break;}
72
+ if(status.status==='failed')throw new WorkspaceError(queryErrors[status.errorCode]||queryErrors.unavailable);
73
+ if(status.status==='cancelled'||status.status==='expired'){say(status.status==='cancelled'?'Question cancelled.':'This question expired. Please ask again.');break;}
74
+ await new Promise(resolve=>setTimeout(resolve,1200));
75
+ }
76
+ }
77
+ catch(error){if(generation===epoch&&flow===querySerial&&!(error instanceof SessionChanged))say(error.name==='AbortError'?'The connection was interrupted. Reload to resume your question.':publicMessage(error,'Could not verify an answer. Please try again.'));}
78
+ finally{if(generation===epoch&&flow===querySerial){busy=false;activeQuery=null;$('activity').hidden=true;$('cancel-question').hidden=true;if(csrf)try{await session(true);}catch(error){if(!(error instanceof SessionChanged)){clearPrivate();say(publicMessage(error,'We could not confirm access. Sign in again or retry shortly.'));}}}}
79
+ }
80
+ $('ask').addEventListener('submit',event=>{
81
+ event.preventDefault();if(busy)return;const question=$('question').value.trim();if(question)void runQuestion(question);
82
+ });
83
+ $('cancel-question').addEventListener('click',async()=>{
84
+ const generation=epoch,identity=stopQuestion();$('send').disabled=false;
85
+ try{if(identity)await api('/api/queries/'+encodeURIComponent(identity),{method:'DELETE'});if(generation===epoch)say('Question cancelled.');}
86
+ catch(error){if(generation===epoch)say(publicMessage(error,'Cancellation could not be confirmed. Please try again.'));}
87
+ });
88
+ window.addEventListener('pagehide',clearPrivate);
89
+ window.addEventListener('pageshow',event=>{if(event.persisted)session().catch(()=>{clearPrivate();say('Sign in to reopen your workspace.');});});
90
+ document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible'&&csrf)session().catch(error=>{if(!(error instanceof SessionChanged)){clearPrivate();say(publicMessage(error,'Access could not be confirmed. Sign in again.'));}});});
91
+ async function boot(){
92
+ try{
93
+ config=await(await fetch('/api/web-config',{cache:'no-store',credentials:'omit',redirect:'error'})).json();
94
+ const metadata={issuer:config.company.issuer,authorization_endpoint:config.company.authorizationEndpoint,token_endpoint:config.company.tokenEndpoint};
95
+ manager=new UserManager({authority:config.company.issuer,client_id:config.company.clientId,redirect_uri:location.origin+'/company-callback',response_type:'code',scope:config.company.scopes.join(' '),metadata,loadUserInfo:false,automaticSilentRenew:false,monitorSession:false,disablePKCE:false,requestTimeoutInSeconds:15,staleStateAgeInSeconds:300,userStore:new WebStorageStateStore({store:new InMemoryWebStorage()}),stateStore:new WebStorageStateStore({store:window.sessionStorage})});
96
+ if(location.pathname==='/company-callback'){
97
+ const callback=location.href;history.replaceState(null,'','/');let user;
98
+ try{user=await manager.signinRedirectCallback(callback);await api('/api/session',{method:'POST',data:{},bootstrapToken:user.access_token});}finally{await manager.removeUser();user=null;}
99
+ }else if(location.search){history.replaceState(null,'','/');}
100
+ const current=await session();say('');
101
+ if(current.sources.every(row=>row.status==='connected')){const recent=await api('/api/queries'),last=recent.queries.at(-1);if(last&&!busy)void runQuestion(last.question,last.id);}
102
+ }catch(error){clearPrivate();say(publicMessage(error,'Sign in with your company account to open your workspace.'));}
103
+ }
104
+ setInterval(()=>{if(csrf&&!busy&&document.visibilityState==='visible')session().catch(error=>{if(!(error instanceof SessionChanged)){clearPrivate();say(publicMessage(error,'Access could not be confirmed. Sign in again or retry shortly.'));}});},15000);
105
+ boot();
@@ -0,0 +1,29 @@
1
+ {
2
+ "entry": "src/runtime/enterprise-web-entry.js",
3
+ "entrySha256": "ac4c05c1e8c6cf859965b17c8cdd34b1f06d82387089dd060bf57b0051bd4e36",
4
+ "bundleSha256": "21e4a75bc0c1462b126e0027b147641e9076e8dc0dbe880be0a90b96d10a4c69",
5
+ "buildScriptSha256": "f236a1fdad4fa1eaafc74cab1b6fd1d30518178867d382cc6e604dee52c44f1a",
6
+ "noticesSha256": "b9d6d351aafd630fc3963fa404ab435befb58ab8983126b5219ae7db94ea7eed",
7
+ "packageLockSha256": "5fe4a9db2220a27fa7e4a0e66ba8fa563ee31361eb57fd15030cfe3a91678822",
8
+ "dependencies": [
9
+ {
10
+ "name": "oidc-client-ts",
11
+ "version": "3.5.0",
12
+ "license": "Apache-2.0",
13
+ "packageSha256": "302e06acbad7e35f2844dfc29a5a708b0b06f3d8b45df4ac6a9a32c5ec826228"
14
+ },
15
+ {
16
+ "name": "jwt-decode",
17
+ "version": "4.0.0",
18
+ "license": "MIT",
19
+ "packageSha256": "15cc76bd7effa3c5ce634c178e22cbfa76de58fa8ab7bef96d6ca2f53912df37"
20
+ },
21
+ {
22
+ "name": "esbuild",
23
+ "version": "0.25.12",
24
+ "license": "MIT",
25
+ "packageSha256": "cb7d5b1fe478f8cbaae566a86031b6fdf5f7d444354f35d1cb3cba9adf6d2935"
26
+ }
27
+ ],
28
+ "scope": "Pinned dependency bundle only; browser/runtime qualification is separate."
29
+ }
@@ -0,0 +1,229 @@
1
+ # oidc-client-ts
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "{}"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2018, Brock Allen, Dominick Baier
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
204
+
205
+
206
+
207
+ # jwt-decode
208
+
209
+ The MIT License (MIT)
210
+
211
+ Copyright (c) 2015 Auth0, Inc. <support@auth0.com> (http://auth0.com)
212
+
213
+ Permission is hereby granted, free of charge, to any person obtaining a copy
214
+ of this software and associated documentation files (the "Software"), to deal
215
+ in the Software without restriction, including without limitation the rights
216
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
217
+ copies of the Software, and to permit persons to whom the Software is
218
+ furnished to do so, subject to the following conditions:
219
+
220
+ The above copyright notice and this permission notice shall be included in all
221
+ copies or substantial portions of the Software.
222
+
223
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
224
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
225
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
226
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
227
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
228
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
229
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ :root{color-scheme:light;--pink:#F3A2B4;--rose:#8e3952;--ink:#182033;--muted:#627083;--line:#e3e7ee;--wash:#fbedf1}*{box-sizing:border-box}[hidden]{display:none!important}body{margin:0;background:#fafbfa;color:var(--ink);font:16px/1.55 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}main{max-width:1100px;margin:auto;padding:24px}header,.brand,.composer-actions{display:flex;align-items:center;gap:12px}header{justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:18px}.brand{font-size:19px}.brand-dot{width:15px;height:15px;background:var(--pink);border-radius:50%}h1{font-size:clamp(24px,3vw,36px);line-height:1.25;letter-spacing:-.025em}h2{font-size:17px;margin:0}.hint,#status{color:var(--muted);font-size:14px}button{font:inherit;font-weight:650;border:1px solid transparent;border-radius:12px;background:var(--pink);color:var(--ink);padding:11px 18px;cursor:pointer;min-height:44px}button:hover{background:#f7b6c4}button:disabled{opacity:.55;cursor:default}.quiet{background:#fff;border-color:var(--line);font-size:14px;padding:8px 13px}.quiet:hover{background:var(--wash)}button:focus-visible,textarea:focus-visible,a:focus-visible{outline:3px solid var(--rose);outline-offset:3px}#welcome{padding:48px 0 24px;max-width:700px}#workspace{display:grid;grid-template-columns:235px minmax(0,1fr);gap:32px;padding-top:24px}.sources-panel{border-right:1px solid var(--line);padding-right:24px}#sources{list-style:none;padding:0;margin:20px 0}#sources li{padding:14px 0;border-top:1px solid var(--line)}#sources strong{display:block}#sources p{font-size:13px;color:var(--muted);margin:6px 0 10px}#sources button{font-size:14px;padding:7px 12px}.disconnect{margin-left:6px}.conversation>h1{font-size:28px;margin-top:0}#intro{color:var(--muted)}#messages{list-style:none;padding:0;display:flex;flex-direction:column;gap:18px;max-height:55vh;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable}#messages li{padding:18px 20px;border:1px solid var(--line);border-radius:16px;background:#fff;white-space:pre-wrap;overflow-wrap:anywhere}#messages li.user{background:var(--wash);align-self:flex-end;max-width:90%}#messages li.assistant{align-self:stretch}.message-label{display:block;font-size:12px;color:var(--muted);font-weight:650;text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px}.citation{display:block;border-left:3px solid var(--pink);padding-left:12px;margin-top:15px;font-size:14px}.citation a{color:var(--rose);font-weight:650}.citation blockquote{margin:5px 0 0;color:var(--muted)}#ask{border:1px solid var(--line);background:#fff;border-radius:18px;padding:16px;margin-top:20px}#ask label{font-weight:650;font-size:14px}textarea{display:block;resize:vertical;min-height:100px;max-height:260px;width:100%;font:inherit;color:var(--ink);border:0;background:transparent;padding:10px 0;outline-offset:1px}textarea:focus-visible{outline:2px solid var(--rose);border-radius:5px}.composer-actions{justify-content:space-between;min-height:44px}.composer-actions>button{margin-left:auto}#activity{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:13px}#activity svg{animation:breathe 1.4s ease-in-out infinite}#status{min-height:24px}a{overflow-wrap:anywhere}@keyframes breathe{50%{opacity:.5;transform:scale(.92)}}@media(prefers-reduced-motion:reduce){#activity svg{animation:none}}@media(max-width:700px){main{padding:16px}#workspace{grid-template-columns:1fr;gap:20px}.sources-panel{border-right:0;border-bottom:1px solid var(--line);padding:0 0 12px}#sources{display:flex;gap:18px;flex-wrap:wrap;margin:10px 0}#sources li{border:0;flex:1;min-width:135px}#messages{max-height:45vh}#messages li{padding:15px}#welcome{padding-top:24px}}
2
+ #status:empty{display:none}footer{margin-top:20px}footer a{font-size:13px;color:var(--rose)}
3
+
4
+ .composer-actions{flex-wrap:wrap}#activity{flex:1 1 190px}@media(max-width:700px){#activity{flex-basis:100%}}
@@ -0,0 +1,8 @@
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Company knowledge</title><link rel="stylesheet" href="/assets/workspace.css"><script src="/assets/workspace.js" defer></script></head><body><main>
2
+ <header><div class="brand"><span class="brand-dot" aria-hidden="true"></span><strong>Company knowledge</strong></div><button id="sign-out" class="quiet" hidden>Sign out</button></header>
3
+ <section id="welcome"><h1>Answers from your company sources.</h1><p>Search the documents you have access to, with sources you can check.</p><button id="sign-in">Sign in with your company account</button></section>
4
+ <p id="status" role="status" aria-live="polite">Opening your workspace…</p>
5
+ <section id="workspace" hidden aria-label="Company knowledge workspace"><section class="sources-panel" aria-labelledby="sources-title"><h2 id="sources-title">Your sources</h2><p class="hint">Connect once. Access is checked when you ask.</p><ul id="sources"></ul></section>
6
+ <section class="conversation" aria-label="Questions and answers"><h1>What would you like to know?</h1><p id="intro">Ask a question about your connected company sources.</p><ol id="messages" aria-live="polite" aria-relevant="additions"></ol><button id="new-answer" class="quiet" hidden>See new answer</button>
7
+ <form id="ask"><label for="question">Your question</label><textarea id="question" rows="3" maxlength="1000" required placeholder="For example, what is our customer-data retention policy?"></textarea><div class="composer-actions"><span id="activity" hidden><svg viewBox="-150 -135 300 260" width="30" height="28" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><g fill="#F3A2B4"><path d="M7 -104 A41.2 41.2 0 0 1 78.8 -87.95 A40.71 40.71 0 0 1 124.2 -31.16 A38 38 0 0 1 116.93 36.3 A42.22 42.22 0 0 1 60.09 85.83 A29.75 29.75 0 0 1 7 84 Z"/><path d="M7 -104 A41.2 41.2 0 0 1 78.8 -87.95 A40.71 40.71 0 0 1 124.2 -31.16 A38 38 0 0 1 116.93 36.3 A42.22 42.22 0 0 1 60.09 85.83 A29.75 29.75 0 0 1 7 84 Z" transform="scale(-1 1)"/></g><g fill="#fff" stroke="#101314" stroke-width="11"><circle cx="-47" cy="26" r="35"/><circle cx="47" cy="26" r="35"/></g><g fill="#101314"><circle cx="-42" cy="21" r="10"/><circle cx="52" cy="21" r="10"/></g></svg>Checking current sources…</span><button id="cancel-question" class="quiet" type="button" hidden>Cancel</button><button id="send" type="submit">Ask</button></div></form></section></section>
8
+ <footer><small><a href="/assets/notices.txt">Open-source notices</a></small></footer><noscript>JavaScript is needed for company sign-in and source access checks.</noscript></main></body></html>