@sixb/app 0.1.11 → 0.1.12
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.
- package/LICENSE +2 -0
- package/README.md +25 -19
- package/assets/connector-icons/README.md +29 -0
- package/assets/connector-icons/ace-iot.ico +0 -0
- package/assets/connector-icons/companycam.png +0 -0
- package/assets/connector-icons/exa.png +0 -0
- package/assets/connector-icons/github.svg +1 -0
- package/assets/connector-icons/google.ico +0 -0
- package/assets/connector-icons/googleads.svg +29 -0
- package/assets/connector-icons/linkedin.svg +1 -0
- package/assets/connector-icons/mercury.svg +1 -0
- package/assets/connector-icons/meta.svg +1 -0
- package/assets/connector-icons/microsoft.ico +0 -0
- package/assets/connector-icons/notion.svg +1 -0
- package/assets/connector-icons/pandadoc.png +0 -0
- package/assets/connector-icons/pennylane.ico +0 -0
- package/assets/connector-icons/pipedrive.png +0 -0
- package/assets/connector-icons/plaud.png +0 -0
- package/assets/connector-icons/quickbooks.svg +1 -0
- package/assets/connector-icons/stripe.svg +1 -0
- package/assets/connector-icons/teamleader.ico +0 -0
- package/assets/connector-icons/tiktok.svg +1 -0
- package/assets/connector-icons/unipile.png +0 -0
- package/dist/agent/activity-label.d.ts +5 -0
- package/dist/agent/activity-label.d.ts.map +1 -0
- package/dist/agent/agent-chat.d.ts +24 -0
- package/dist/agent/agent-chat.d.ts.map +1 -0
- package/dist/agent/agent-context-provider.d.ts +9 -0
- package/dist/agent/agent-context-provider.d.ts.map +1 -0
- package/dist/agent/agent-execution-trace.d.ts +9 -0
- package/dist/agent/agent-execution-trace.d.ts.map +1 -0
- package/dist/agent/agent-panel.d.ts +27 -0
- package/dist/agent/agent-panel.d.ts.map +1 -0
- package/dist/agent/agent-surface-state.d.ts +22 -0
- package/dist/agent/agent-surface-state.d.ts.map +1 -0
- package/dist/agent/agent-surface.d.ts +46 -0
- package/dist/agent/agent-surface.d.ts.map +1 -0
- package/dist/agent/bash/bash-tool-view.d.ts +17 -0
- package/dist/agent/bash/bash-tool-view.d.ts.map +1 -0
- package/dist/agent/bash/data.d.ts +35 -0
- package/dist/agent/bash/data.d.ts.map +1 -0
- package/dist/agent/bash/interpret.d.ts +84 -0
- package/dist/agent/bash/interpret.d.ts.map +1 -0
- package/dist/agent/bash/renderers.d.ts +31 -0
- package/dist/agent/bash/renderers.d.ts.map +1 -0
- package/dist/agent/bash/shell.d.ts +16 -0
- package/dist/agent/bash/shell.d.ts.map +1 -0
- package/dist/agent/components/activity-status.d.ts +13 -0
- package/dist/agent/components/activity-status.d.ts.map +1 -0
- package/dist/agent/components/agent-thread-switcher.d.ts +16 -0
- package/dist/agent/components/agent-thread-switcher.d.ts.map +1 -0
- package/dist/agent/components/composer.d.ts +47 -0
- package/dist/agent/components/composer.d.ts.map +1 -0
- package/dist/agent/components/context-chips.d.ts +7 -0
- package/dist/agent/components/context-chips.d.ts.map +1 -0
- package/dist/agent/components/context-picker.d.ts +16 -0
- package/dist/agent/components/context-picker.d.ts.map +1 -0
- package/dist/agent/components/conversation-panel.d.ts +82 -0
- package/dist/agent/components/conversation-panel.d.ts.map +1 -0
- package/dist/agent/components/file-attachment-card.d.ts +8 -0
- package/dist/agent/components/file-attachment-card.d.ts.map +1 -0
- package/dist/agent/components/message-parts.d.ts +13 -0
- package/dist/agent/components/message-parts.d.ts.map +1 -0
- package/dist/agent/components/message-view.d.ts +58 -0
- package/dist/agent/components/message-view.d.ts.map +1 -0
- package/dist/agent/components/model-controls.d.ts +20 -0
- package/dist/agent/components/model-controls.d.ts.map +1 -0
- package/dist/agent/components/model-picker-row.d.ts +8 -0
- package/dist/agent/components/model-picker-row.d.ts.map +1 -0
- package/dist/agent/components/provider-logo.d.ts +6 -0
- package/dist/agent/components/provider-logo.d.ts.map +1 -0
- package/dist/agent/components/provider-logos.d.ts +3 -0
- package/dist/agent/components/provider-logos.d.ts.map +1 -0
- package/dist/agent/components/reasoning-effort-slider.d.ts +11 -0
- package/dist/agent/components/reasoning-effort-slider.d.ts.map +1 -0
- package/dist/agent/components/sandbox-recovery.d.ts +6 -0
- package/dist/agent/components/sandbox-recovery.d.ts.map +1 -0
- package/dist/agent/components/transcript.d.ts +36 -0
- package/dist/agent/components/transcript.d.ts.map +1 -0
- package/dist/agent/components/web-fetch-tool-view.d.ts +5 -0
- package/dist/agent/components/web-fetch-tool-view.d.ts.map +1 -0
- package/dist/agent/components/web-search-tool-view.d.ts +5 -0
- package/dist/agent/components/web-search-tool-view.d.ts.map +1 -0
- package/dist/agent/components/web-sources.d.ts +9 -0
- package/dist/agent/components/web-sources.d.ts.map +1 -0
- package/dist/agent/document-preview/classify.d.ts +4 -0
- package/dist/agent/document-preview/classify.d.ts.map +1 -0
- package/dist/agent/document-preview/content-policy.d.ts +10 -0
- package/dist/agent/document-preview/content-policy.d.ts.map +1 -0
- package/dist/agent/document-preview/content.d.ts +26 -0
- package/dist/agent/document-preview/content.d.ts.map +1 -0
- package/dist/agent/document-preview/delimited.d.ts +19 -0
- package/dist/agent/document-preview/delimited.d.ts.map +1 -0
- package/dist/agent/document-preview/document-preview-root.d.ts +24 -0
- package/dist/agent/document-preview/document-preview-root.d.ts.map +1 -0
- package/dist/agent/document-preview/file-size.d.ts +3 -0
- package/dist/agent/document-preview/file-size.d.ts.map +1 -0
- package/dist/agent/document-preview/html.d.ts +9 -0
- package/dist/agent/document-preview/html.d.ts.map +1 -0
- package/dist/agent/document-preview/persistence.d.ts +6 -0
- package/dist/agent/document-preview/persistence.d.ts.map +1 -0
- package/dist/agent/document-preview/presentation.d.ts +3 -0
- package/dist/agent/document-preview/presentation.d.ts.map +1 -0
- package/dist/agent/document-preview/rendering.d.ts +14 -0
- package/dist/agent/document-preview/rendering.d.ts.map +1 -0
- package/dist/agent/document-preview/source.d.ts +13 -0
- package/dist/agent/document-preview/source.d.ts.map +1 -0
- package/dist/agent/document-preview/state.d.ts +27 -0
- package/dist/agent/document-preview/state.d.ts.map +1 -0
- package/dist/agent/document-preview/types.d.ts +33 -0
- package/dist/agent/document-preview/types.d.ts.map +1 -0
- package/dist/agent/format.d.ts +12 -0
- package/dist/agent/format.d.ts.map +1 -0
- package/dist/agent/hooks/use-agent-conversation.d.ts +338 -0
- package/dist/agent/hooks/use-agent-conversation.d.ts.map +1 -0
- package/dist/agent/hooks/use-thread-stream.d.ts +22 -0
- package/dist/agent/hooks/use-thread-stream.d.ts.map +1 -0
- package/dist/agent/i18n/en.d.ts +589 -0
- package/dist/agent/i18n/en.d.ts.map +1 -0
- package/dist/agent/i18n/fr.d.ts +4 -0
- package/dist/agent/i18n/fr.d.ts.map +1 -0
- package/dist/agent/i18n/index.d.ts +1161 -0
- package/dist/agent/i18n/index.d.ts.map +1 -0
- package/dist/agent/live-run.d.ts +48 -0
- package/dist/agent/live-run.d.ts.map +1 -0
- package/dist/agent/model-selection.d.ts +33 -0
- package/dist/agent/model-selection.d.ts.map +1 -0
- package/dist/agent/object-context-title.d.ts +22 -0
- package/dist/agent/object-context-title.d.ts.map +1 -0
- package/dist/agent/parts.d.ts +42 -0
- package/dist/agent/parts.d.ts.map +1 -0
- package/dist/agent/react-router.d.ts +8 -0
- package/dist/agent/react-router.d.ts.map +1 -0
- package/dist/agent/read/interpret.d.ts +24 -0
- package/dist/agent/read/interpret.d.ts.map +1 -0
- package/dist/agent/read/read-tool-view.d.ts +5 -0
- package/dist/agent/read/read-tool-view.d.ts.map +1 -0
- package/dist/agent/requester-settings.d.ts +15 -0
- package/dist/agent/requester-settings.d.ts.map +1 -0
- package/dist/agent/run-presentation.d.ts +70 -0
- package/dist/agent/run-presentation.d.ts.map +1 -0
- package/dist/agent/thread-navigation.d.ts +5 -0
- package/dist/agent/thread-navigation.d.ts.map +1 -0
- package/dist/agent/types.d.ts +22 -0
- package/dist/agent/types.d.ts.map +1 -0
- package/dist/agent/utils/context-display.d.ts +5 -0
- package/dist/agent/utils/context-display.d.ts.map +1 -0
- package/dist/agent/utils/context-mention.d.ts +12 -0
- package/dist/agent/utils/context-mention.d.ts.map +1 -0
- package/dist/agent/utils/web-fetch.d.ts +4 -0
- package/dist/agent/utils/web-fetch.d.ts.map +1 -0
- package/dist/agent/utils/web-search.d.ts +20 -0
- package/dist/agent/utils/web-search.d.ts.map +1 -0
- package/dist/agent/view-file/interpret.d.ts +9 -0
- package/dist/agent/view-file/interpret.d.ts.map +1 -0
- package/dist/agent/view-file/view-file-tool-view.d.ts +9 -0
- package/dist/agent/view-file/view-file-tool-view.d.ts.map +1 -0
- package/dist/agent/workspace.d.ts +11 -0
- package/dist/agent/workspace.d.ts.map +1 -0
- package/dist/chunk-3a99tmwg.js +176 -0
- package/dist/chunk-3a99tmwg.js.map +10 -0
- package/dist/chunk-48pkffj6.js +20 -0
- package/dist/chunk-48pkffj6.js.map +10 -0
- package/dist/chunk-6n5pdqp0.js +115 -0
- package/dist/chunk-6n5pdqp0.js.map +11 -0
- package/dist/chunk-j97e06rg.js +10668 -0
- package/dist/chunk-j97e06rg.js.map +80 -0
- package/dist/chunk-md3p7qdt.js +379 -0
- package/dist/chunk-md3p7qdt.js.map +10 -0
- package/dist/chunk-shmw3f8t.js +251 -0
- package/dist/chunk-shmw3f8t.js.map +10 -0
- package/dist/chunk-yvhzn4ye.js +98 -0
- package/dist/chunk-yvhzn4ye.js.map +10 -0
- package/dist/chunk-zcxrt24m.js +148 -0
- package/dist/chunk-zcxrt24m.js.map +10 -0
- package/dist/codegen.d.ts +6 -4
- package/dist/codegen.d.ts.map +1 -1
- package/dist/createCustomApp.d.ts +14 -7
- package/dist/createCustomApp.d.ts.map +1 -1
- package/dist/index.d.ts +33 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +958 -2890
- package/dist/index.js.map +14 -13
- package/dist/locale-messages.d.ts +72 -6
- package/dist/locale-messages.d.ts.map +1 -1
- package/dist/locale.d.ts +73 -8
- package/dist/locale.d.ts.map +1 -1
- package/dist/locale.js +10 -19
- package/dist/locale.js.map +3 -4
- package/dist/metadata.d.ts.map +1 -1
- package/dist/pages/data/connectors.d.ts +5 -0
- package/dist/pages/data/connectors.d.ts.map +1 -0
- package/dist/pages/data/datasets.d.ts +30 -0
- package/dist/pages/data/datasets.d.ts.map +1 -0
- package/dist/pages/data/live-updates.d.ts +13 -0
- package/dist/pages/data/live-updates.d.ts.map +1 -0
- package/dist/pages/data/messages.d.ts +354 -0
- package/dist/pages/data/messages.d.ts.map +1 -0
- package/dist/pages/data/pipeline-canvas.d.ts +34 -0
- package/dist/pages/data/pipeline-canvas.d.ts.map +1 -0
- package/dist/pages/data/pipelines.d.ts +9 -0
- package/dist/pages/data/pipelines.d.ts.map +1 -0
- package/dist/pages/data/projections.d.ts +10 -0
- package/dist/pages/data/projections.d.ts.map +1 -0
- package/dist/pages/data/schema.d.ts +20 -0
- package/dist/pages/data/schema.d.ts.map +1 -0
- package/dist/pages/data/shared.d.ts +13 -0
- package/dist/pages/data/shared.d.ts.map +1 -0
- package/dist/pages/data/sync-button.d.ts +15 -0
- package/dist/pages/data/sync-button.d.ts.map +1 -0
- package/dist/pages/data/syncs.d.ts +5 -0
- package/dist/pages/data/syncs.d.ts.map +1 -0
- package/dist/pages/home.d.ts +6 -0
- package/dist/pages/home.d.ts.map +1 -0
- package/dist/pages/mosaic.d.ts +5 -0
- package/dist/pages/mosaic.d.ts.map +1 -0
- package/dist/pages/observability/action-run.d.ts +19 -0
- package/dist/pages/observability/action-run.d.ts.map +1 -0
- package/dist/pages/observability/ai-usage/calls.d.ts +27 -0
- package/dist/pages/observability/ai-usage/calls.d.ts.map +1 -0
- package/dist/pages/observability/ai-usage/charts.d.ts +23 -0
- package/dist/pages/observability/ai-usage/charts.d.ts.map +1 -0
- package/dist/pages/observability/ai-usage/format.d.ts +101 -0
- package/dist/pages/observability/ai-usage/format.d.ts.map +1 -0
- package/dist/pages/observability/ai-usage/limits.d.ts +12 -0
- package/dist/pages/observability/ai-usage/limits.d.ts.map +1 -0
- package/dist/pages/observability/ai-usage/messages.d.ts +431 -0
- package/dist/pages/observability/ai-usage/messages.d.ts.map +1 -0
- package/dist/pages/observability/ai-usage/page.d.ts +6 -0
- package/dist/pages/observability/ai-usage/page.d.ts.map +1 -0
- package/dist/pages/observability/live-updates.d.ts +3 -0
- package/dist/pages/observability/live-updates.d.ts.map +1 -0
- package/dist/pages/observability/logs.d.ts +11 -0
- package/dist/pages/observability/logs.d.ts.map +1 -0
- package/dist/pages/observability/messages.d.ts +329 -0
- package/dist/pages/observability/messages.d.ts.map +1 -0
- package/dist/pages/observability/runs.d.ts +7 -0
- package/dist/pages/observability/runs.d.ts.map +1 -0
- package/dist/pages/observability/workflow-run.d.ts +6 -0
- package/dist/pages/observability/workflow-run.d.ts.map +1 -0
- package/dist/pages/ontology/actions.d.ts +3 -0
- package/dist/pages/ontology/actions.d.ts.map +1 -0
- package/dist/pages/ontology/components/action-button.d.ts +12 -0
- package/dist/pages/ontology/components/action-button.d.ts.map +1 -0
- package/dist/pages/ontology/components/action-param-null-control.d.ts +7 -0
- package/dist/pages/ontology/components/action-param-null-control.d.ts.map +1 -0
- package/dist/pages/ontology/components/collection-toolbar.d.ts +21 -0
- package/dist/pages/ontology/components/collection-toolbar.d.ts.map +1 -0
- package/dist/pages/ontology/components/common.d.ts +16 -0
- package/dist/pages/ontology/components/common.d.ts.map +1 -0
- package/dist/pages/ontology/components/file-ref-upload-field.d.ts +13 -0
- package/dist/pages/ontology/components/file-ref-upload-field.d.ts.map +1 -0
- package/dist/pages/ontology/components/object-filter-popover.d.ts +9 -0
- package/dist/pages/ontology/components/object-filter-popover.d.ts.map +1 -0
- package/dist/pages/ontology/components/object-icon.d.ts +7 -0
- package/dist/pages/ontology/components/object-icon.d.ts.map +1 -0
- package/dist/pages/ontology/components/object-query-bar.d.ts +21 -0
- package/dist/pages/ontology/components/object-query-bar.d.ts.map +1 -0
- package/dist/pages/ontology/components/telemetry-chart.d.ts +18 -0
- package/dist/pages/ontology/components/telemetry-chart.d.ts.map +1 -0
- package/dist/pages/ontology/components/telemetry-grid.d.ts +19 -0
- package/dist/pages/ontology/components/telemetry-grid.d.ts.map +1 -0
- package/dist/pages/ontology/components/telemetry-tile.d.ts +18 -0
- package/dist/pages/ontology/components/telemetry-tile.d.ts.map +1 -0
- package/dist/pages/ontology/components/telemetry-value.d.ts +10 -0
- package/dist/pages/ontology/components/telemetry-value.d.ts.map +1 -0
- package/dist/pages/ontology/components/usage-bar.d.ts +12 -0
- package/dist/pages/ontology/components/usage-bar.d.ts.map +1 -0
- package/dist/pages/ontology/graph.d.ts +6 -0
- package/dist/pages/ontology/graph.d.ts.map +1 -0
- package/dist/pages/ontology/hooks/object-live-updates.d.ts +5 -0
- package/dist/pages/ontology/hooks/object-live-updates.d.ts.map +1 -0
- package/dist/pages/ontology/hooks/object-telemetry-updates.d.ts +8 -0
- package/dist/pages/ontology/hooks/object-telemetry-updates.d.ts.map +1 -0
- package/dist/pages/ontology/hooks/object-type-counts.d.ts +5 -0
- package/dist/pages/ontology/hooks/object-type-counts.d.ts.map +1 -0
- package/dist/pages/ontology/hooks/rule-live-updates.d.ts +9 -0
- package/dist/pages/ontology/hooks/rule-live-updates.d.ts.map +1 -0
- package/dist/pages/ontology/hooks/workflow-live-updates.d.ts +6 -0
- package/dist/pages/ontology/hooks/workflow-live-updates.d.ts.map +1 -0
- package/dist/pages/ontology/lib/action-params.d.ts +55 -0
- package/dist/pages/ontology/lib/action-params.d.ts.map +1 -0
- package/dist/pages/ontology/lib/format-value.d.ts +3 -0
- package/dist/pages/ontology/lib/format-value.d.ts.map +1 -0
- package/dist/pages/ontology/lib/labels.d.ts +3 -0
- package/dist/pages/ontology/lib/labels.d.ts.map +1 -0
- package/dist/pages/ontology/lib/live-update-keys.d.ts +15 -0
- package/dist/pages/ontology/lib/live-update-keys.d.ts.map +1 -0
- package/dist/pages/ontology/lib/object-query.d.ts +72 -0
- package/dist/pages/ontology/lib/object-query.d.ts.map +1 -0
- package/dist/pages/ontology/lib/ontology-graph-layout.d.ts +68 -0
- package/dist/pages/ontology/lib/ontology-graph-layout.d.ts.map +1 -0
- package/dist/pages/ontology/lib/ontology-graph-links.d.ts +4 -0
- package/dist/pages/ontology/lib/ontology-graph-links.d.ts.map +1 -0
- package/dist/pages/ontology/lib/telemetry-history.d.ts +10 -0
- package/dist/pages/ontology/lib/telemetry-history.d.ts.map +1 -0
- package/dist/pages/ontology/lib/time.d.ts +3 -0
- package/dist/pages/ontology/lib/time.d.ts.map +1 -0
- package/dist/pages/ontology/lib/user-preferences.d.ts +8 -0
- package/dist/pages/ontology/lib/user-preferences.d.ts.map +1 -0
- package/dist/pages/ontology/object-page.d.ts +7 -0
- package/dist/pages/ontology/object-page.d.ts.map +1 -0
- package/dist/pages/ontology/object-type.d.ts +3 -0
- package/dist/pages/ontology/object-type.d.ts.map +1 -0
- package/dist/pages/ontology/object-types.d.ts +7 -0
- package/dist/pages/ontology/object-types.d.ts.map +1 -0
- package/dist/pages/ontology/objects.d.ts +6 -0
- package/dist/pages/ontology/objects.d.ts.map +1 -0
- package/dist/pages/ontology/rules.d.ts +32 -0
- package/dist/pages/ontology/rules.d.ts.map +1 -0
- package/dist/pages/ontology/workflow.d.ts +6 -0
- package/dist/pages/ontology/workflow.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/agent-execution-panel.d.ts +17 -0
- package/dist/pages/ontology/workflows/agent-execution-panel.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/intervention-panel.d.ts +5 -0
- package/dist/pages/ontology/workflows/intervention-panel.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/node-execution-panel.d.ts +11 -0
- package/dist/pages/ontology/workflows/node-execution-panel.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/request-run-dialog.d.ts +5 -0
- package/dist/pages/ontology/workflows/request-run-dialog.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/run-debug-section.d.ts +11 -0
- package/dist/pages/ontology/workflows/run-debug-section.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/run-input-form.d.ts +18 -0
- package/dist/pages/ontology/workflows/run-input-form.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/run-progress.d.ts +15 -0
- package/dist/pages/ontology/workflows/run-progress.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/schema-shape.d.ts +10 -0
- package/dist/pages/ontology/workflows/schema-shape.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/status-badge.d.ts +5 -0
- package/dist/pages/ontology/workflows/status-badge.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/utils.d.ts +29 -0
- package/dist/pages/ontology/workflows/utils.d.ts.map +1 -0
- package/dist/pages/ontology/workflows/workflow-card.d.ts +5 -0
- package/dist/pages/ontology/workflows/workflow-card.d.ts.map +1 -0
- package/dist/pages/ontology/workflows.d.ts +3 -0
- package/dist/pages/ontology/workflows.d.ts.map +1 -0
- package/dist/pages/routes.d.ts +19 -0
- package/dist/pages/routes.d.ts.map +1 -0
- package/dist/pages/section-page.d.ts +91 -0
- package/dist/pages/section-page.d.ts.map +1 -0
- package/dist/pages/section-ui.d.ts +211 -0
- package/dist/pages/section-ui.d.ts.map +1 -0
- package/dist/pages/settings/controls.d.ts +94 -0
- package/dist/pages/settings/controls.d.ts.map +1 -0
- package/dist/pages/settings/developers.d.ts +3 -0
- package/dist/pages/settings/developers.d.ts.map +1 -0
- package/dist/pages/settings/members.d.ts +3 -0
- package/dist/pages/settings/members.d.ts.map +1 -0
- package/dist/pages/settings/messages.d.ts +538 -0
- package/dist/pages/settings/messages.d.ts.map +1 -0
- package/dist/pages/settings/personal.d.ts +6 -0
- package/dist/pages/settings/personal.d.ts.map +1 -0
- package/dist/pages/settings/service-accounts.d.ts +3 -0
- package/dist/pages/settings/service-accounts.d.ts.map +1 -0
- package/dist/pages/settings/sessions.d.ts +3 -0
- package/dist/pages/settings/sessions.d.ts.map +1 -0
- package/dist/pages/values.d.ts +77 -0
- package/dist/pages/values.d.ts.map +1 -0
- package/dist/pages.d.ts +42 -0
- package/dist/pages.d.ts.map +1 -0
- package/dist/pages.js +23931 -0
- package/dist/pages.js.map +85 -0
- package/dist/runtime.d.ts +0 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/sections/catalog.d.ts +37 -0
- package/dist/sections/catalog.d.ts.map +1 -0
- package/dist/sections/counts.d.ts +7 -0
- package/dist/sections/counts.d.ts.map +1 -0
- package/dist/sections/sections.d.ts +67 -0
- package/dist/sections/sections.d.ts.map +1 -0
- package/dist/server.d.ts +8 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2983 -0
- package/dist/server.js.map +19 -0
- package/dist/session.d.ts +18 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/shell/agent-dock.d.ts +7 -0
- package/dist/shell/agent-dock.d.ts.map +1 -0
- package/dist/shell/app-shell.d.ts +42 -0
- package/dist/shell/app-shell.d.ts.map +1 -0
- package/dist/shell/brand.d.ts +15 -0
- package/dist/shell/brand.d.ts.map +1 -0
- package/dist/shell/nav-items.d.ts +34 -0
- package/dist/shell/nav-items.d.ts.map +1 -0
- package/dist/shell/search-command.d.ts +12 -0
- package/dist/shell/search-command.d.ts.map +1 -0
- package/dist/shell/section-nav.d.ts +13 -0
- package/dist/shell/section-nav.d.ts.map +1 -0
- package/dist/shell/user-menu.d.ts +25 -0
- package/dist/shell/user-menu.d.ts.map +1 -0
- package/dist/tailwind.d.ts +4 -4
- package/dist/tailwind.d.ts.map +1 -1
- package/package.json +24 -21
- package/src/agent/activity-label.ts +63 -0
- package/src/agent/agent-chat.tsx +237 -0
- package/src/agent/agent-context-provider.tsx +92 -0
- package/src/agent/agent-execution-trace.tsx +316 -0
- package/src/agent/agent-panel.tsx +79 -0
- package/src/agent/agent-surface-state.ts +113 -0
- package/src/agent/agent-surface.tsx +363 -0
- package/src/agent/agent.css +231 -0
- package/src/agent/bash/bash-tool-view.tsx +288 -0
- package/src/agent/bash/data.ts +137 -0
- package/src/agent/bash/interpret.ts +769 -0
- package/src/agent/bash/renderers.tsx +503 -0
- package/src/agent/bash/shell.ts +195 -0
- package/src/agent/components/activity-status.tsx +86 -0
- package/src/agent/components/agent-thread-switcher.tsx +346 -0
- package/src/agent/components/composer.tsx +870 -0
- package/src/agent/components/context-chips.tsx +63 -0
- package/src/agent/components/context-picker.tsx +88 -0
- package/src/agent/components/conversation-panel.tsx +352 -0
- package/src/agent/components/file-attachment-card.tsx +137 -0
- package/src/agent/components/message-parts.tsx +280 -0
- package/src/agent/components/message-view.tsx +428 -0
- package/src/agent/components/model-controls.tsx +204 -0
- package/src/agent/components/model-picker-row.tsx +136 -0
- package/src/agent/components/provider-logo.tsx +31 -0
- package/src/agent/components/provider-logos.ts +24 -0
- package/src/agent/components/reasoning-effort-slider.tsx +121 -0
- package/src/agent/components/sandbox-recovery.tsx +49 -0
- package/src/agent/components/transcript.tsx +239 -0
- package/src/agent/components/web-fetch-tool-view.tsx +69 -0
- package/src/agent/components/web-search-tool-view.tsx +37 -0
- package/src/agent/components/web-sources.tsx +159 -0
- package/src/agent/document-preview/classify.ts +55 -0
- package/src/agent/document-preview/content-policy.ts +37 -0
- package/src/agent/document-preview/content.ts +82 -0
- package/src/agent/document-preview/delimited.ts +118 -0
- package/src/agent/document-preview/document-preview-root.tsx +1017 -0
- package/src/agent/document-preview/file-size.ts +26 -0
- package/src/agent/document-preview/html.ts +67 -0
- package/src/agent/document-preview/persistence.ts +115 -0
- package/src/agent/document-preview/presentation.ts +13 -0
- package/src/agent/document-preview/rendering.ts +48 -0
- package/src/agent/document-preview/source.ts +48 -0
- package/src/agent/document-preview/state.ts +77 -0
- package/src/agent/document-preview/types.ts +36 -0
- package/src/agent/format.ts +60 -0
- package/src/agent/hooks/use-agent-conversation.ts +536 -0
- package/src/agent/hooks/use-thread-stream.ts +121 -0
- package/src/agent/i18n/en.ts +542 -0
- package/src/agent/i18n/fr.ts +574 -0
- package/src/agent/i18n/index.ts +14 -0
- package/src/agent/live-run.ts +257 -0
- package/src/agent/model-selection.ts +88 -0
- package/src/agent/object-context-title.ts +57 -0
- package/src/agent/parts.ts +119 -0
- package/src/agent/react-router.tsx +84 -0
- package/src/agent/read/interpret.ts +101 -0
- package/src/agent/read/read-tool-view.tsx +92 -0
- package/src/agent/requester-settings.ts +55 -0
- package/src/agent/run-presentation.ts +211 -0
- package/src/agent/thread-navigation.ts +11 -0
- package/src/agent/types.ts +37 -0
- package/src/agent/utils/context-display.ts +72 -0
- package/src/agent/utils/context-mention.ts +28 -0
- package/src/agent/utils/web-fetch.ts +20 -0
- package/src/agent/utils/web-search.ts +106 -0
- package/src/agent/view-file/interpret.ts +22 -0
- package/src/agent/view-file/view-file-tool-view.tsx +120 -0
- package/src/{agents.ts → agent/workspace.ts} +4 -19
- package/src/codegen.ts +61 -79
- package/src/createCustomApp.ts +155 -67
- package/src/index.ts +52 -16
- package/src/locale-messages.ts +121 -12
- package/src/locale.ts +1 -2
- package/src/metadata.ts +35 -1
- package/src/pages/canvas.css +43 -0
- package/src/pages/data/connectors.tsx +317 -0
- package/src/pages/data/datasets.tsx +731 -0
- package/src/pages/data/live-updates.ts +71 -0
- package/src/pages/data/messages.ts +349 -0
- package/src/pages/data/pipeline-canvas.tsx +288 -0
- package/src/pages/data/pipelines.tsx +710 -0
- package/src/pages/data/projections.tsx +482 -0
- package/src/pages/data/schema.tsx +62 -0
- package/src/pages/data/shared.tsx +78 -0
- package/src/pages/data/sync-button.tsx +103 -0
- package/src/pages/data/syncs.tsx +326 -0
- package/src/pages/home.tsx +64 -0
- package/src/pages/mosaic.tsx +97 -0
- package/src/pages/observability/action-run.tsx +229 -0
- package/src/pages/observability/ai-usage/calls.tsx +541 -0
- package/src/pages/observability/ai-usage/charts.tsx +126 -0
- package/src/pages/observability/ai-usage/format.ts +276 -0
- package/src/pages/observability/ai-usage/limits.tsx +629 -0
- package/src/pages/observability/ai-usage/messages.ts +446 -0
- package/src/pages/observability/ai-usage/page.tsx +814 -0
- package/src/pages/observability/live-updates.ts +19 -0
- package/src/pages/observability/logs.tsx +617 -0
- package/src/pages/observability/messages.ts +336 -0
- package/src/pages/observability/runs.tsx +732 -0
- package/src/pages/observability/workflow-run.tsx +323 -0
- package/src/pages/ontology/actions.tsx +749 -0
- package/src/pages/ontology/components/action-button.tsx +355 -0
- package/src/pages/ontology/components/action-param-null-control.tsx +35 -0
- package/src/pages/ontology/components/collection-toolbar.tsx +61 -0
- package/src/pages/ontology/components/common.tsx +60 -0
- package/src/pages/ontology/components/file-ref-upload-field.tsx +279 -0
- package/src/pages/ontology/components/object-filter-popover.tsx +311 -0
- package/src/pages/ontology/components/object-icon.tsx +133 -0
- package/src/pages/ontology/components/object-query-bar.tsx +217 -0
- package/src/pages/ontology/components/telemetry-chart.tsx +392 -0
- package/src/pages/ontology/components/telemetry-grid.tsx +137 -0
- package/src/pages/ontology/components/telemetry-tile.tsx +164 -0
- package/src/pages/ontology/components/telemetry-value.tsx +91 -0
- package/src/pages/ontology/components/usage-bar.tsx +64 -0
- package/src/pages/ontology/graph.tsx +1283 -0
- package/src/pages/ontology/hooks/object-live-updates.ts +53 -0
- package/src/pages/ontology/hooks/object-telemetry-updates.ts +45 -0
- package/src/pages/ontology/hooks/object-type-counts.ts +27 -0
- package/src/pages/ontology/hooks/rule-live-updates.ts +28 -0
- package/src/pages/ontology/hooks/workflow-live-updates.ts +20 -0
- package/src/pages/ontology/lib/action-params.ts +231 -0
- package/src/pages/ontology/lib/format-value.ts +34 -0
- package/src/pages/ontology/lib/labels.ts +50 -0
- package/src/pages/ontology/lib/live-update-keys.ts +62 -0
- package/src/pages/ontology/lib/object-query.ts +372 -0
- package/src/pages/ontology/lib/ontology-graph-layout.ts +1004 -0
- package/src/pages/ontology/lib/ontology-graph-links.ts +15 -0
- package/src/pages/ontology/lib/telemetry-history.ts +56 -0
- package/src/pages/ontology/lib/time.ts +23 -0
- package/src/pages/ontology/lib/user-preferences.ts +52 -0
- package/src/pages/ontology/object-page.tsx +1029 -0
- package/src/pages/ontology/object-type.tsx +910 -0
- package/src/pages/ontology/object-types.tsx +240 -0
- package/src/pages/ontology/objects.tsx +938 -0
- package/src/pages/ontology/rules.tsx +805 -0
- package/src/pages/ontology/workflow.tsx +1485 -0
- package/src/pages/ontology/workflows/agent-execution-panel.tsx +340 -0
- package/src/pages/ontology/workflows/intervention-panel.tsx +261 -0
- package/src/pages/ontology/workflows/node-execution-panel.tsx +86 -0
- package/src/pages/ontology/workflows/request-run-dialog.tsx +197 -0
- package/src/pages/ontology/workflows/run-debug-section.tsx +54 -0
- package/src/pages/ontology/workflows/run-input-form.tsx +900 -0
- package/src/pages/ontology/workflows/run-progress.tsx +83 -0
- package/src/pages/ontology/workflows/schema-shape.tsx +206 -0
- package/src/pages/ontology/workflows/status-badge.tsx +15 -0
- package/src/pages/ontology/workflows/utils.ts +107 -0
- package/src/pages/ontology/workflows/workflow-card.tsx +48 -0
- package/src/pages/ontology/workflows.tsx +143 -0
- package/src/pages/routes.ts +48 -0
- package/src/pages/section-page.tsx +272 -0
- package/src/pages/section-ui.tsx +771 -0
- package/src/pages/settings/controls.tsx +721 -0
- package/src/pages/settings/developers.tsx +163 -0
- package/src/pages/settings/members.tsx +1018 -0
- package/src/pages/settings/messages.ts +551 -0
- package/src/pages/settings/personal.tsx +97 -0
- package/src/pages/settings/service-accounts.tsx +623 -0
- package/src/pages/settings/sessions.tsx +183 -0
- package/src/pages/values.tsx +700 -0
- package/src/pages.ts +56 -0
- package/src/runtime.ts +0 -3
- package/src/sections/catalog.ts +181 -0
- package/src/sections/counts.ts +33 -0
- package/src/sections/sections.tsx +257 -0
- package/src/server.ts +19 -0
- package/src/session.ts +29 -0
- package/src/shell/agent-dock.tsx +32 -0
- package/src/shell/app-shell.tsx +142 -0
- package/src/shell/brand.tsx +47 -0
- package/src/shell/nav-items.tsx +136 -0
- package/src/shell/search-command.tsx +158 -0
- package/src/shell/section-nav.tsx +61 -0
- package/src/shell/user-menu.tsx +206 -0
- package/src/tailwind.ts +4 -4
- package/dist/agents.d.ts +0 -11
- package/dist/agents.d.ts.map +0 -1
- package/dist/agents.js +0 -41
- package/dist/agents.js.map +0 -10
- package/dist/auth.js +0 -3
- package/dist/auth.js.map +0 -9
- package/dist/browser.d.ts +0 -3
- package/dist/browser.d.ts.map +0 -1
- package/dist/browser.js +0 -9
- package/dist/browser.js.map +0 -9
- package/dist/chunk-cftmy40z.js +0 -70
- package/dist/chunk-cftmy40z.js.map +0 -10
- package/dist/chunk-e1gj8c1a.js +0 -8
- package/dist/chunk-e1gj8c1a.js.map +0 -10
- package/src/browser.ts +0 -2
package/dist/server.js
ADDED
|
@@ -0,0 +1,2983 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
sectionCatalog,
|
|
4
|
+
sectionIds
|
|
5
|
+
} from "./chunk-zcxrt24m.js";
|
|
6
|
+
import {
|
|
7
|
+
en,
|
|
8
|
+
fr
|
|
9
|
+
} from "./chunk-3a99tmwg.js";
|
|
10
|
+
|
|
11
|
+
// src/createCustomApp.ts
|
|
12
|
+
import { randomBytes } from "crypto";
|
|
13
|
+
import { existsSync as existsSync2, watch } from "fs";
|
|
14
|
+
import { access as access2, cp, mkdir as mkdir4, readFile as readFile5, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
15
|
+
import { dirname as dirname3, isAbsolute, join as join7, normalize, relative as relative3, resolve as resolve3 } from "path";
|
|
16
|
+
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
17
|
+
|
|
18
|
+
// src/build.ts
|
|
19
|
+
import { existsSync } from "fs";
|
|
20
|
+
import { copyFile, mkdir, readFile, rm, writeFile } from "fs/promises";
|
|
21
|
+
import { basename, dirname, join, resolve } from "path";
|
|
22
|
+
import { promisify } from "util";
|
|
23
|
+
import {
|
|
24
|
+
brotliCompress as brotliCompressCallback,
|
|
25
|
+
gzip as gzipCallback,
|
|
26
|
+
constants as zlibConstants
|
|
27
|
+
} from "zlib";
|
|
28
|
+
var STATIC_ASSET_ORIGIN = "https://sixb-static.invalid";
|
|
29
|
+
var brotliCompress = promisify(brotliCompressCallback);
|
|
30
|
+
var gzip = promisify(gzipCallback);
|
|
31
|
+
var PRECOMPRESSION_CONCURRENCY = 4;
|
|
32
|
+
var SHARED_APP_SHELL_FILE_NAME = "shared-index.html";
|
|
33
|
+
async function buildApp(options) {
|
|
34
|
+
const outdir = options.outdir ?? join(process.cwd(), ".sixb", "dist", "app");
|
|
35
|
+
if (Boolean(options.sharedEntryPath) !== Boolean(options.sharedScriptEntryPath)) {
|
|
36
|
+
throw new Error("[SixbCustomApp] sharedEntryPath and sharedScriptEntryPath must be provided together.");
|
|
37
|
+
}
|
|
38
|
+
await rm(outdir, { recursive: true, force: true });
|
|
39
|
+
await mkdir(outdir, { recursive: true });
|
|
40
|
+
const result = await buildBrowserEntry(options.scriptEntryPath, outdir, "app");
|
|
41
|
+
if (!result.success) {
|
|
42
|
+
return {
|
|
43
|
+
success: false,
|
|
44
|
+
outdir,
|
|
45
|
+
logs: result.logs.map(String)
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const normalEntry = resolveBrowserEntry(result.outputs, "browser");
|
|
49
|
+
const sourceHtml = restoreAppStaticUrls(await readFile(options.entryPath, "utf-8"));
|
|
50
|
+
const sourceEntryPattern = /\s*<script\s+type=["']module["']\s+src=["']\.\/main\.tsx["']><\/script>/;
|
|
51
|
+
if (!sourceEntryPattern.test(sourceHtml)) {
|
|
52
|
+
throw new Error("[SixbCustomApp] Generated app shell is missing its ./main.tsx entry.");
|
|
53
|
+
}
|
|
54
|
+
const assetTags = [
|
|
55
|
+
...normalEntry.stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/${basename(stylesheet.path)}">`),
|
|
56
|
+
`<script type="module" crossorigin src="/${basename(normalEntry.script.path)}"></script>`
|
|
57
|
+
].join("");
|
|
58
|
+
const html = withLoadingShell(sourceHtml).replace(sourceEntryPattern, "").replace("</head>", ` ${assetTags}</head>`);
|
|
59
|
+
await writeFile(join(outdir, "index.html"), html, "utf-8");
|
|
60
|
+
const outputs = [...result.outputs];
|
|
61
|
+
if (options.sharedEntryPath && options.sharedScriptEntryPath) {
|
|
62
|
+
const sharedResult = await buildBrowserEntry(options.sharedScriptEntryPath, outdir, "shared");
|
|
63
|
+
if (!sharedResult.success) {
|
|
64
|
+
return {
|
|
65
|
+
success: false,
|
|
66
|
+
outdir,
|
|
67
|
+
logs: sharedResult.logs.map(String)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const sharedEntry = resolveBrowserEntry(sharedResult.outputs, "shared browser");
|
|
71
|
+
const sharedHtml = await renderSharedAppHtml(options.sharedEntryPath, sharedEntry);
|
|
72
|
+
await writeFile(join(outdir, SHARED_APP_SHELL_FILE_NAME), sharedHtml, "utf-8");
|
|
73
|
+
outputs.push(...sharedResult.outputs);
|
|
74
|
+
}
|
|
75
|
+
if (options.manifestPath) {
|
|
76
|
+
await copyFile(options.manifestPath, join(outdir, "app.webmanifest"));
|
|
77
|
+
}
|
|
78
|
+
await precompressBuildAssets(outputs);
|
|
79
|
+
return { success: true, outdir };
|
|
80
|
+
}
|
|
81
|
+
async function buildSharedAppDev(options) {
|
|
82
|
+
await rm(options.outdir, { recursive: true, force: true });
|
|
83
|
+
await mkdir(options.outdir, { recursive: true });
|
|
84
|
+
let result;
|
|
85
|
+
try {
|
|
86
|
+
result = await buildBrowserEntry(options.scriptEntryPath, options.outdir, "shared-dev", true);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
await rm(options.outdir, { recursive: true, force: true });
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
if (!result.success) {
|
|
92
|
+
await rm(options.outdir, { recursive: true, force: true });
|
|
93
|
+
throw new Error(`[SixbCustomApp] Failed to build the shared development shell: ${result.logs.map(String).join(`
|
|
94
|
+
`)}`);
|
|
95
|
+
}
|
|
96
|
+
const entry = resolveBrowserEntry(result.outputs, "shared development browser");
|
|
97
|
+
return {
|
|
98
|
+
assetPaths: result.outputs.map((output) => output.path),
|
|
99
|
+
html: await renderSharedAppHtml(options.entryPath, entry)
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
async function buildBrowserEntry(entrypoint, outdir, entryName, development = false) {
|
|
103
|
+
return await Bun.build({
|
|
104
|
+
entrypoints: [entrypoint],
|
|
105
|
+
outdir,
|
|
106
|
+
target: "browser",
|
|
107
|
+
conditions: ["bun"],
|
|
108
|
+
publicPath: "/",
|
|
109
|
+
minify: !development,
|
|
110
|
+
splitting: true,
|
|
111
|
+
naming: {
|
|
112
|
+
entry: `${entryName}-[hash].[ext]`,
|
|
113
|
+
chunk: "chunk-[name]-[hash].[ext]",
|
|
114
|
+
asset: "asset-[name]-[hash].[ext]"
|
|
115
|
+
},
|
|
116
|
+
plugins: [extensionlessSourceImportPlugin],
|
|
117
|
+
define: { "process.env.NODE_ENV": development ? '"development"' : '"production"' },
|
|
118
|
+
sourcemap: development ? "inline" : "external"
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
async function renderSharedAppHtml(entryPath, entry) {
|
|
122
|
+
const sourceHtml = restoreAppStaticUrls(await readFile(entryPath, "utf-8"));
|
|
123
|
+
const sourceEntryPattern = /const \{ startSharedApp \} = await import\((["'])\.\/shared-main\.tsx\1\)\s+startSharedApp\(bootstrap\)/;
|
|
124
|
+
if (!sourceEntryPattern.test(sourceHtml)) {
|
|
125
|
+
throw new Error("[SixbCustomApp] Generated shared app shell is missing its ./shared-main.tsx import.");
|
|
126
|
+
}
|
|
127
|
+
const stylesheetUrls = entry.stylesheets.map((stylesheet) => `/${basename(stylesheet.path)}`);
|
|
128
|
+
const bootstrap = [
|
|
129
|
+
`const { startSharedApp } = await import(${JSON.stringify(`/${basename(entry.script.path)}`)})`,
|
|
130
|
+
...stylesheetUrls.length > 0 ? [
|
|
131
|
+
" startSharedApp(bootstrap, {",
|
|
132
|
+
" async loadAppStyles() {",
|
|
133
|
+
" await Promise.all(",
|
|
134
|
+
` ${JSON.stringify(stylesheetUrls)}.map((href) => new Promise((resolve) => {`,
|
|
135
|
+
' const link = document.createElement("link")',
|
|
136
|
+
' link.rel = "stylesheet"',
|
|
137
|
+
' link.crossOrigin = "anonymous"',
|
|
138
|
+
' link.addEventListener("load", resolve, { once: true })',
|
|
139
|
+
' link.addEventListener("error", resolve, { once: true })',
|
|
140
|
+
" link.href = href",
|
|
141
|
+
" document.head.append(link)",
|
|
142
|
+
" }))",
|
|
143
|
+
" )",
|
|
144
|
+
" },",
|
|
145
|
+
" })"
|
|
146
|
+
] : [" startSharedApp(bootstrap)"]
|
|
147
|
+
].join(`
|
|
148
|
+
`);
|
|
149
|
+
return withLoadingShell(sourceHtml).replace(sourceEntryPattern, bootstrap);
|
|
150
|
+
}
|
|
151
|
+
function resolveBrowserEntry(outputs, label) {
|
|
152
|
+
const script = outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
|
|
153
|
+
const stylesheets = outputs.filter((output) => output.type.startsWith("text/css"));
|
|
154
|
+
if (!script || stylesheets.length > 1) {
|
|
155
|
+
throw new Error(`[SixbCustomApp] Expected one ${label} entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
|
|
156
|
+
}
|
|
157
|
+
return { script, stylesheets };
|
|
158
|
+
}
|
|
159
|
+
async function buildAuthExperience(options) {
|
|
160
|
+
const outdir = resolve(options.outdir);
|
|
161
|
+
const assetsDir = join(outdir, "assets");
|
|
162
|
+
await rm(outdir, { recursive: true, force: true });
|
|
163
|
+
await mkdir(assetsDir, { recursive: true });
|
|
164
|
+
const result = await Bun.build({
|
|
165
|
+
entrypoints: [options.scriptEntryPath],
|
|
166
|
+
outdir: assetsDir,
|
|
167
|
+
target: "browser",
|
|
168
|
+
conditions: ["bun"],
|
|
169
|
+
publicPath: "/auth/assets/",
|
|
170
|
+
minify: true,
|
|
171
|
+
splitting: true,
|
|
172
|
+
naming: {
|
|
173
|
+
entry: "auth-[hash].[ext]",
|
|
174
|
+
chunk: "chunk-[name]-[hash].[ext]",
|
|
175
|
+
asset: "asset-[name]-[hash].[ext]"
|
|
176
|
+
},
|
|
177
|
+
plugins: [extensionlessSourceImportPlugin],
|
|
178
|
+
define: { "process.env.NODE_ENV": '"production"' },
|
|
179
|
+
sourcemap: "external"
|
|
180
|
+
});
|
|
181
|
+
if (!result.success) {
|
|
182
|
+
return {
|
|
183
|
+
success: false,
|
|
184
|
+
outdir,
|
|
185
|
+
logs: result.logs.map(String)
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
const script = result.outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
|
|
189
|
+
const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"));
|
|
190
|
+
if (!script || stylesheets.length > 1) {
|
|
191
|
+
throw new Error(`[SixbCustomApp] Expected one auth entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
|
|
192
|
+
}
|
|
193
|
+
const sourceHtml = await readFile(options.entryPath, "utf-8");
|
|
194
|
+
const sourceEntryPattern = /\s*<script\s+type=["']module["']\s+src=["']\.\/auth-main\.tsx["']><\/script>/;
|
|
195
|
+
if (!sourceEntryPattern.test(sourceHtml)) {
|
|
196
|
+
throw new Error("[SixbCustomApp] Generated auth shell is missing its ./auth-main.tsx entry.");
|
|
197
|
+
}
|
|
198
|
+
const assetTags = [
|
|
199
|
+
...stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/auth/assets/${basename(stylesheet.path)}">`),
|
|
200
|
+
`<script type="module" crossorigin src="/auth/assets/${basename(script.path)}"></script>`
|
|
201
|
+
].join("");
|
|
202
|
+
const html = sourceHtml.replace(sourceEntryPattern, "").replace("</head>", ` ${assetTags}</head>`);
|
|
203
|
+
await writeFile(join(outdir, "index.html"), html, "utf-8");
|
|
204
|
+
await precompressBuildAssets(result.outputs);
|
|
205
|
+
return { success: true, outdir };
|
|
206
|
+
}
|
|
207
|
+
async function prepareAppHtmlBundleEntry(entryPath) {
|
|
208
|
+
const html = await readFile(entryPath, "utf-8");
|
|
209
|
+
const bundleHtml = html.replace(/(<link\s+rel=["'](?:manifest|icon|apple-touch-icon)["']\s+href=["'])(\/[^"']*)(["'][^>]*>)/g, `$1${STATIC_ASSET_ORIGIN}$2$3`);
|
|
210
|
+
const entryName = basename(entryPath, ".html");
|
|
211
|
+
const bundleEntryPath = join(dirname(entryPath), `${entryName}.sixb-bundle.html`);
|
|
212
|
+
await writeFile(bundleEntryPath, bundleHtml, "utf-8");
|
|
213
|
+
return bundleEntryPath;
|
|
214
|
+
}
|
|
215
|
+
function restoreAppStaticUrls(html) {
|
|
216
|
+
return html.replaceAll(STATIC_ASSET_ORIGIN, "");
|
|
217
|
+
}
|
|
218
|
+
function withLoadingShell(html) {
|
|
219
|
+
const styles = `<style data-sixb-loading-shell>
|
|
220
|
+
.sixb-loading-shell{position:fixed;inset:0;display:grid;place-items:center;background:#fff;color:#71717a}
|
|
221
|
+
.sixb-loading-spinner{width:1.25rem;height:1.25rem;border:2px solid currentColor;border-right-color:transparent;border-radius:9999px;animation:sixb-loading-spin .7s linear infinite}
|
|
222
|
+
@media(prefers-color-scheme:dark){.sixb-loading-shell{background:#09090b;color:#a1a1aa}}
|
|
223
|
+
@media(prefers-reduced-motion:reduce){.sixb-loading-spinner{animation-duration:1.5s}}
|
|
224
|
+
@keyframes sixb-loading-spin{to{transform:rotate(360deg)}}
|
|
225
|
+
</style>`;
|
|
226
|
+
const root = '<div id="root"><div class="sixb-loading-shell" role="status" aria-label="Loading application"><span class="sixb-loading-spinner" aria-hidden="true"></span></div></div>';
|
|
227
|
+
if (!html.includes('<div id="root"></div>') || !html.includes("</head>")) {
|
|
228
|
+
throw new Error("[SixbCustomApp] Generated app shell is missing its root or head element.");
|
|
229
|
+
}
|
|
230
|
+
return html.replace("</head>", `${styles}
|
|
231
|
+
</head>`).replace('<div id="root"></div>', root);
|
|
232
|
+
}
|
|
233
|
+
var extensionlessSourceImportPlugin = {
|
|
234
|
+
name: "sixb-extensionless-source-imports",
|
|
235
|
+
setup(build) {
|
|
236
|
+
build.onResolve({ filter: /^\.\.?\/(?:.*\/)?[^/.]+$/ }, (args) => {
|
|
237
|
+
const base = resolve(dirname(args.importer), args.path);
|
|
238
|
+
for (const candidate of [
|
|
239
|
+
`${base}.ts`,
|
|
240
|
+
`${base}.tsx`,
|
|
241
|
+
`${base}.js`,
|
|
242
|
+
`${base}.jsx`,
|
|
243
|
+
join(base, "index.ts"),
|
|
244
|
+
join(base, "index.tsx"),
|
|
245
|
+
join(base, "index.js"),
|
|
246
|
+
join(base, "index.jsx")
|
|
247
|
+
]) {
|
|
248
|
+
if (existsSync(candidate))
|
|
249
|
+
return { path: candidate };
|
|
250
|
+
}
|
|
251
|
+
return;
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
async function precompressBuildAssets(outputs) {
|
|
256
|
+
const paths = [
|
|
257
|
+
...new Set(outputs.filter((output) => output.type.startsWith("text/javascript") || output.type.startsWith("text/css")).map((output) => output.path))
|
|
258
|
+
];
|
|
259
|
+
let cursor = 0;
|
|
260
|
+
const worker = async () => {
|
|
261
|
+
while (cursor < paths.length) {
|
|
262
|
+
const path = paths[cursor++];
|
|
263
|
+
const bytes = await Bun.file(path).arrayBuffer();
|
|
264
|
+
const [brotli, gzipped] = await Promise.all([
|
|
265
|
+
brotliCompress(bytes, {
|
|
266
|
+
params: {
|
|
267
|
+
[zlibConstants.BROTLI_PARAM_QUALITY]: 5
|
|
268
|
+
}
|
|
269
|
+
}),
|
|
270
|
+
gzip(bytes, { level: 9 })
|
|
271
|
+
]);
|
|
272
|
+
await Promise.all([writeFile(`${path}.br`, brotli), writeFile(`${path}.gz`, gzipped)]);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
await Promise.all(Array.from({ length: Math.min(PRECOMPRESSION_CONCURRENCY, paths.length) }, worker));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/codegen.ts
|
|
279
|
+
import { access, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
|
|
280
|
+
import { join as join4, relative as relative2, resolve as resolve2 } from "path";
|
|
281
|
+
|
|
282
|
+
// src/manifest.ts
|
|
283
|
+
function renderAppManifest(metadata) {
|
|
284
|
+
const manifest = {
|
|
285
|
+
id: "/",
|
|
286
|
+
name: metadata.title,
|
|
287
|
+
...metadata.description ? { description: metadata.description } : {},
|
|
288
|
+
start_url: "/",
|
|
289
|
+
scope: "/",
|
|
290
|
+
display: "standalone",
|
|
291
|
+
theme_color: metadata.themeColor,
|
|
292
|
+
background_color: metadata.backgroundColor,
|
|
293
|
+
...metadata.icons.length > 0 ? { icons: metadata.icons } : {}
|
|
294
|
+
};
|
|
295
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
296
|
+
`;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/metadata.ts
|
|
300
|
+
import { createHash } from "crypto";
|
|
301
|
+
import { readFile as readFile2, stat } from "fs/promises";
|
|
302
|
+
import { createRequire } from "module";
|
|
303
|
+
import { extname, join as join2 } from "path";
|
|
304
|
+
import { pathToFileURL } from "url";
|
|
305
|
+
var metadataRequire = createRequire(import.meta.url);
|
|
306
|
+
var metadataFields = [
|
|
307
|
+
"title",
|
|
308
|
+
"description",
|
|
309
|
+
"favicon",
|
|
310
|
+
"themeColor",
|
|
311
|
+
"backgroundColor"
|
|
312
|
+
];
|
|
313
|
+
async function resolveAppMetadata(options) {
|
|
314
|
+
const configured = await loadConfiguredMetadata(options.layoutPath);
|
|
315
|
+
validateMetadata(configured, options.layoutPath);
|
|
316
|
+
const conventionalFaviconPath = join2(options.publicDir, "favicon.svg");
|
|
317
|
+
const favicon = configured.favicon ?? (await fileExists(conventionalFaviconPath) ? "/favicon.svg" : undefined);
|
|
318
|
+
const themeColor = configured.themeColor ?? configured.backgroundColor ?? "#ffffff";
|
|
319
|
+
const backgroundColor = configured.backgroundColor ?? themeColor;
|
|
320
|
+
const icons = [];
|
|
321
|
+
if (await fileExists(join2(options.publicDir, "icon-192.png"))) {
|
|
322
|
+
icons.push({
|
|
323
|
+
src: "/icon-192.png",
|
|
324
|
+
sizes: "192x192",
|
|
325
|
+
type: "image/png",
|
|
326
|
+
purpose: "any"
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
if (await fileExists(join2(options.publicDir, "icon-512.png"))) {
|
|
330
|
+
icons.push({
|
|
331
|
+
src: "/icon-512.png",
|
|
332
|
+
sizes: "512x512",
|
|
333
|
+
type: "image/png",
|
|
334
|
+
purpose: "any"
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
if (await fileExists(join2(options.publicDir, "icon-maskable-512.png"))) {
|
|
338
|
+
icons.push({
|
|
339
|
+
src: "/icon-maskable-512.png",
|
|
340
|
+
sizes: "512x512",
|
|
341
|
+
type: "image/png",
|
|
342
|
+
purpose: "maskable"
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
const hasStandardIcon = icons.some((icon) => icon.purpose === "any");
|
|
346
|
+
if (!hasStandardIcon && favicon) {
|
|
347
|
+
const type = inferImageMimeType(favicon);
|
|
348
|
+
if (type) {
|
|
349
|
+
icons.push({
|
|
350
|
+
src: favicon,
|
|
351
|
+
...type === "image/svg+xml" ? { sizes: "any" } : {},
|
|
352
|
+
type,
|
|
353
|
+
purpose: "any"
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
title: configured.title ?? "Sixb",
|
|
359
|
+
...configured.description ? { description: configured.description } : {},
|
|
360
|
+
...favicon ? { favicon } : {},
|
|
361
|
+
themeColor,
|
|
362
|
+
backgroundColor,
|
|
363
|
+
...await fileExists(join2(options.publicDir, "apple-touch-icon.png")) ? { appleTouchIcon: "/apple-touch-icon.png" } : {},
|
|
364
|
+
icons
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
async function loadConfiguredMetadata(layoutPath) {
|
|
368
|
+
if (!await fileExists(layoutPath)) {
|
|
369
|
+
return {};
|
|
370
|
+
}
|
|
371
|
+
try {
|
|
372
|
+
const sourceHash = createHash("sha256").update(await readFile2(layoutPath)).digest("hex");
|
|
373
|
+
const url = pathToFileURL(layoutPath);
|
|
374
|
+
delete metadataRequire.cache[metadataRequire.resolve(layoutPath)];
|
|
375
|
+
url.searchParams.set("sixb-metadata", sourceHash);
|
|
376
|
+
const layoutModule = await import(url.href);
|
|
377
|
+
validateVisibility(layoutModule.visibility, layoutPath);
|
|
378
|
+
if (layoutModule.metadata === undefined) {
|
|
379
|
+
return {};
|
|
380
|
+
}
|
|
381
|
+
if (typeof layoutModule.metadata !== "object" || layoutModule.metadata === null || Array.isArray(layoutModule.metadata)) {
|
|
382
|
+
throw metadataError(layoutPath, "the named metadata export must be an object");
|
|
383
|
+
}
|
|
384
|
+
return layoutModule.metadata;
|
|
385
|
+
} catch (error) {
|
|
386
|
+
if (error instanceof Error && error.message.startsWith("[SixbCustomApp]")) {
|
|
387
|
+
throw error;
|
|
388
|
+
}
|
|
389
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
390
|
+
throw new Error(`[SixbCustomApp] Could not load metadata from ${layoutPath}: ${detail}. App metadata is build-time configuration, so app/layout.tsx must be import-safe in Bun and must not access window or document at module scope.`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function validateMetadata(metadata, layoutPath) {
|
|
394
|
+
for (const field of metadataFields) {
|
|
395
|
+
const value = metadata[field];
|
|
396
|
+
if (value !== undefined && (typeof value !== "string" || value.trim().length === 0)) {
|
|
397
|
+
throw metadataError(layoutPath, `metadata.${field} must be a non-empty string when provided`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
function validateVisibility(visibility, layoutPath) {
|
|
402
|
+
if (visibility === undefined)
|
|
403
|
+
return;
|
|
404
|
+
const fail = (detail) => new Error(`[SixbCustomApp] Invalid visibility in ${layoutPath}: ${detail}`);
|
|
405
|
+
if (typeof visibility !== "object" || visibility === null || Array.isArray(visibility)) {
|
|
406
|
+
throw fail("the named visibility export must be an object");
|
|
407
|
+
}
|
|
408
|
+
for (const [section, groups] of Object.entries(visibility)) {
|
|
409
|
+
if (!sectionIds.includes(section)) {
|
|
410
|
+
throw fail(`'${section}' is not a built-in section. Sections: ${sectionIds.join(", ")}.`);
|
|
411
|
+
}
|
|
412
|
+
const valid = Array.isArray(groups) && groups.every((group) => typeof group === "object" && group !== null && group.kind === "group" && typeof group.id === "string");
|
|
413
|
+
if (!valid) {
|
|
414
|
+
throw fail(`visibility.${section} must be a list of groups from defineGroup, imported from @sixb/core/security`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function metadataError(layoutPath, detail) {
|
|
419
|
+
return new Error(`[SixbCustomApp] Invalid app metadata in ${layoutPath}: ${detail}`);
|
|
420
|
+
}
|
|
421
|
+
function inferImageMimeType(url) {
|
|
422
|
+
if (url.startsWith("data:")) {
|
|
423
|
+
const match = /^data:(image\/[a-z0-9.+-]+)/i.exec(url);
|
|
424
|
+
return match?.[1]?.toLowerCase();
|
|
425
|
+
}
|
|
426
|
+
let pathname = url;
|
|
427
|
+
try {
|
|
428
|
+
pathname = new URL(url, "https://sixb.invalid").pathname;
|
|
429
|
+
} catch {}
|
|
430
|
+
switch (extname(pathname).toLowerCase()) {
|
|
431
|
+
case ".svg":
|
|
432
|
+
return "image/svg+xml";
|
|
433
|
+
case ".png":
|
|
434
|
+
return "image/png";
|
|
435
|
+
case ".ico":
|
|
436
|
+
return "image/x-icon";
|
|
437
|
+
case ".jpg":
|
|
438
|
+
case ".jpeg":
|
|
439
|
+
return "image/jpeg";
|
|
440
|
+
case ".webp":
|
|
441
|
+
return "image/webp";
|
|
442
|
+
case ".avif":
|
|
443
|
+
return "image/avif";
|
|
444
|
+
default:
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
async function fileExists(path) {
|
|
449
|
+
try {
|
|
450
|
+
return (await stat(path)).isFile();
|
|
451
|
+
} catch {
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// src/runtime.ts
|
|
457
|
+
function collectPublicEnv() {
|
|
458
|
+
return Object.fromEntries(Object.entries(process.env).filter((entry) => entry[0].startsWith("SIXB_PUBLIC_") && entry[1] !== undefined));
|
|
459
|
+
}
|
|
460
|
+
function renderCustomAppRuntimeScript(config) {
|
|
461
|
+
const safeConfig = JSON.stringify(config).replaceAll("<", "\\u003c");
|
|
462
|
+
return `<script>window.__SIXB_RUNTIME__ = ${safeConfig};</script>`;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// src/scanner.ts
|
|
466
|
+
import { readdir } from "fs/promises";
|
|
467
|
+
import { join as join3, relative } from "path";
|
|
468
|
+
var dynamicSegmentPattern = /^\[([\w-]+)\]$/;
|
|
469
|
+
var reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb", "/shared"];
|
|
470
|
+
var reservedRoutePaths = new Set(["/app.webmanifest"]);
|
|
471
|
+
async function scanAppRoutes(appDir) {
|
|
472
|
+
const pages = [];
|
|
473
|
+
const layouts = [];
|
|
474
|
+
await walkDir(appDir, appDir, pages, layouts);
|
|
475
|
+
pages.sort(compareRouteModules);
|
|
476
|
+
layouts.sort(compareRouteModules);
|
|
477
|
+
return { pages, layouts };
|
|
478
|
+
}
|
|
479
|
+
function routePatternKey(path) {
|
|
480
|
+
if (path === "/")
|
|
481
|
+
return "/";
|
|
482
|
+
const segments = routeSegments(path).map((segment) => segment.startsWith(":") ? ":" : segment.toLowerCase());
|
|
483
|
+
return `/${segments.join("/")}`;
|
|
484
|
+
}
|
|
485
|
+
async function walkDir(dir, appDir, pages, layouts) {
|
|
486
|
+
const entries = await readDirectory(dir);
|
|
487
|
+
if (!entries)
|
|
488
|
+
return;
|
|
489
|
+
const visibleEntries = entries.filter((entry) => !String(entry.name).startsWith("_")).sort((a, b) => compareText(String(a.name), String(b.name)));
|
|
490
|
+
const relativeDir = normalizeRelativePath(relative(appDir, dir));
|
|
491
|
+
validateChildDirectories(visibleEntries, relativeDir);
|
|
492
|
+
const pageEntries = visibleEntries.filter((entry) => entry.isFile() && (entry.name === "page.tsx" || entry.name === "page.ts"));
|
|
493
|
+
if (pageEntries.length > 1) {
|
|
494
|
+
const modules = pageEntries.map((entry) => displayAppPath(join3(relativeDir, entry.name)));
|
|
495
|
+
throw new Error(`[SixbCustomApp] Conflicting page modules for route '${directoryRoutePath(relativeDir)}': ${modules.join(" and ")}. Keep exactly one of page.tsx or page.ts.`);
|
|
496
|
+
}
|
|
497
|
+
const pageEntry = pageEntries[0];
|
|
498
|
+
if (pageEntry) {
|
|
499
|
+
const relativePath = normalizeRelativePath(join3(relativeDir, pageEntry.name));
|
|
500
|
+
const path = directoryRoutePath(relativeDir);
|
|
501
|
+
assertRouteIsAvailable(path, relativePath);
|
|
502
|
+
pages.push({ path, filePath: join3(dir, pageEntry.name), relativePath });
|
|
503
|
+
}
|
|
504
|
+
if (relativeDir) {
|
|
505
|
+
const layoutEntry = visibleEntries.find((entry) => entry.isFile() && entry.name === "layout.tsx");
|
|
506
|
+
if (layoutEntry) {
|
|
507
|
+
layouts.push({
|
|
508
|
+
path: directoryRoutePath(relativeDir),
|
|
509
|
+
filePath: join3(dir, layoutEntry.name),
|
|
510
|
+
relativePath: normalizeRelativePath(join3(relativeDir, layoutEntry.name))
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
for (const entry of visibleEntries) {
|
|
515
|
+
if (!entry.isDirectory())
|
|
516
|
+
continue;
|
|
517
|
+
if (!relativeDir && entry.name === "public")
|
|
518
|
+
continue;
|
|
519
|
+
await walkDir(join3(dir, entry.name), appDir, pages, layouts);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
async function readDirectory(dir) {
|
|
523
|
+
try {
|
|
524
|
+
return await readdir(dir, { withFileTypes: true });
|
|
525
|
+
} catch (error) {
|
|
526
|
+
if (isNotFoundError(error))
|
|
527
|
+
return null;
|
|
528
|
+
throw error;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function validateChildDirectories(entries, relativeDir) {
|
|
532
|
+
const claimedSegments = new Map;
|
|
533
|
+
for (const entry of entries) {
|
|
534
|
+
if (!entry.isDirectory())
|
|
535
|
+
continue;
|
|
536
|
+
if (!relativeDir && entry.name.toLowerCase() === "shared") {
|
|
537
|
+
throw new Error("[SixbCustomApp] app/shared is reserved for framework-managed shared links. " + "Move this page to another route.");
|
|
538
|
+
}
|
|
539
|
+
const segment = routeSegment(entry.name, join3(relativeDir, entry.name));
|
|
540
|
+
const key = segment.startsWith(":") ? ":" : segment.toLowerCase();
|
|
541
|
+
const existing = claimedSegments.get(key);
|
|
542
|
+
if (existing && existing !== entry.name) {
|
|
543
|
+
const parent = relativeDir ? displayAppPath(relativeDir) : "app/";
|
|
544
|
+
throw new Error(`[SixbCustomApp] Ambiguous route directories '${existing}' and '${entry.name}' under ${parent}. They match the same URL segment.`);
|
|
545
|
+
}
|
|
546
|
+
claimedSegments.set(key, entry.name);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
function directoryRoutePath(relativeDir) {
|
|
550
|
+
if (!relativeDir)
|
|
551
|
+
return "/";
|
|
552
|
+
return `/${relativeDir.split("/").map((segment) => routeSegment(segment, relativeDir)).join("/")}`;
|
|
553
|
+
}
|
|
554
|
+
function routeSegment(segment, relativePath) {
|
|
555
|
+
const dynamic = dynamicSegmentPattern.exec(segment);
|
|
556
|
+
if (dynamic)
|
|
557
|
+
return `:${dynamic[1]}`;
|
|
558
|
+
if (segment.includes("[") || segment.includes("]")) {
|
|
559
|
+
throw new Error(`[SixbCustomApp] Invalid dynamic route directory ${displayAppPath(relativePath)}. Use one name such as '[id]'; catch-all and partial dynamic segments are not supported.`);
|
|
560
|
+
}
|
|
561
|
+
if (segment.includes("(") || segment.includes(")")) {
|
|
562
|
+
throw new Error(`[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Route groups are not supported yet; use a normal directory name.`);
|
|
563
|
+
}
|
|
564
|
+
if (/[:*?]/.test(segment)) {
|
|
565
|
+
throw new Error(`[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Use '[name]' for a dynamic segment; ':', '*' and '?' are reserved by React Router.`);
|
|
566
|
+
}
|
|
567
|
+
return segment;
|
|
568
|
+
}
|
|
569
|
+
function assertRouteIsAvailable(path, relativePath) {
|
|
570
|
+
const normalizedPath = path.toLowerCase();
|
|
571
|
+
const reserved = reservedRoutePaths.has(normalizedPath) || reservedRoutePrefixes.some((prefix) => normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`));
|
|
572
|
+
if (!reserved)
|
|
573
|
+
return;
|
|
574
|
+
throw new Error(`[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, /shared, and /app.webmanifest.`);
|
|
575
|
+
}
|
|
576
|
+
function routeSegments(path) {
|
|
577
|
+
return path === "/" ? [] : path.replace(/^\/+|\/+$/g, "").split("/");
|
|
578
|
+
}
|
|
579
|
+
function normalizeRelativePath(path) {
|
|
580
|
+
return path.split("\\").join("/").replace(/^\.\/$/, "");
|
|
581
|
+
}
|
|
582
|
+
function displayAppPath(path) {
|
|
583
|
+
const normalized = normalizeRelativePath(path);
|
|
584
|
+
return normalized ? `app/${normalized}` : "app/";
|
|
585
|
+
}
|
|
586
|
+
function compareRouteModules(a, b) {
|
|
587
|
+
return compareText(a.path, b.path) || compareText(a.relativePath, b.relativePath);
|
|
588
|
+
}
|
|
589
|
+
function compareText(a, b) {
|
|
590
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
591
|
+
}
|
|
592
|
+
function isNotFoundError(error) {
|
|
593
|
+
if (!(error instanceof Error))
|
|
594
|
+
return false;
|
|
595
|
+
const code = error.code;
|
|
596
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// src/codegen.ts
|
|
600
|
+
function sharedUnavailableTranslations() {
|
|
601
|
+
return { en: en.shared.unavailableDetail, fr: fr.shared.unavailableDetail };
|
|
602
|
+
}
|
|
603
|
+
var AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__";
|
|
604
|
+
function assertNoReservedSharedRoutes(routes) {
|
|
605
|
+
const reservedRoute = routes.find((route) => route.path === "/shared" || route.path.startsWith("/shared/"));
|
|
606
|
+
if (!reservedRoute)
|
|
607
|
+
return;
|
|
608
|
+
throw new Error(`[SixbCustomApp] ${reservedRoute.relativePath} maps to the reserved ${JSON.stringify(reservedRoute.path)} route. Shared links reuse ordinary app pages; move this page outside app/shared/.`);
|
|
609
|
+
}
|
|
610
|
+
async function generateRouteManifest(routes, generatedDir, options = {}) {
|
|
611
|
+
assertNoReservedSharedRoutes(routes);
|
|
612
|
+
await mkdir2(generatedDir, { recursive: true });
|
|
613
|
+
const pages = [...routes].sort(compareRouteModules2);
|
|
614
|
+
const pageImports = pages.map((route, index) => {
|
|
615
|
+
const rel = relativeTo(generatedDir, route.filePath);
|
|
616
|
+
return `import Page${index} from ${JSON.stringify(rel)}`;
|
|
617
|
+
}).join(`
|
|
618
|
+
`);
|
|
619
|
+
const projectRoutePatterns = new Set(pages.map((route) => routePatternKey(route.path)));
|
|
620
|
+
const builtInRoutes = (options.builtInRoutes ?? []).filter((route) => !projectRoutePatterns.has(routePatternKey(route.path)));
|
|
621
|
+
const builtInImports = builtInRoutes.map((route, index) => `import { ${route.exportName} as BuiltInPage${index} } from ${JSON.stringify(route.moduleSpecifier)}`).join(`
|
|
622
|
+
`);
|
|
623
|
+
const routePatterns = [...pages, ...builtInRoutes].map((route) => routePatternKey(route.path));
|
|
624
|
+
const layouts = [...options.layouts ?? []].filter((layout) => {
|
|
625
|
+
const layoutPattern = routePatternKey(layout.path);
|
|
626
|
+
return routePatterns.some((routePattern) => routePattern === layoutPattern || routePattern.startsWith(`${layoutPattern}/`));
|
|
627
|
+
}).sort(compareRouteModules2);
|
|
628
|
+
const layoutImports = layouts.map((layout, index) => {
|
|
629
|
+
const rel = relativeTo(generatedDir, layout.filePath);
|
|
630
|
+
return `import Layout${index} from ${JSON.stringify(rel)}`;
|
|
631
|
+
}).join(`
|
|
632
|
+
`);
|
|
633
|
+
const tree = createRouteTree();
|
|
634
|
+
for (const [index, layout] of layouts.entries()) {
|
|
635
|
+
insertRouteLayout(tree, layout, `Layout${index}`);
|
|
636
|
+
}
|
|
637
|
+
for (const [index, route] of pages.entries()) {
|
|
638
|
+
insertRoutePage(tree, route.path, `Page${index}`, route.relativePath);
|
|
639
|
+
}
|
|
640
|
+
for (const [index, route] of builtInRoutes.entries()) {
|
|
641
|
+
insertRoutePage(tree, route.path, `BuiltInPage${index}`, `${route.moduleSpecifier} (${route.path})`);
|
|
642
|
+
}
|
|
643
|
+
const importEntries = [
|
|
644
|
+
'import { createElement } from "react"',
|
|
645
|
+
layouts.length > 0 ? 'import { Outlet, type RouteObject } from "react-router-dom"' : 'import type { RouteObject } from "react-router-dom"',
|
|
646
|
+
pageImports,
|
|
647
|
+
builtInImports,
|
|
648
|
+
layoutImports
|
|
649
|
+
].filter(Boolean).join(`
|
|
650
|
+
`);
|
|
651
|
+
const routePaths = [
|
|
652
|
+
...pages.map((route) => route.path),
|
|
653
|
+
...builtInRoutes.map((route) => route.path)
|
|
654
|
+
];
|
|
655
|
+
const content = `${importEntries}
|
|
656
|
+
|
|
657
|
+
export const routePaths = ${JSON.stringify(routePaths, null, 2)} as const
|
|
658
|
+
|
|
659
|
+
export const routes = [
|
|
660
|
+
${renderRootRouteObjects(tree)}
|
|
661
|
+
] satisfies RouteObject[]
|
|
662
|
+
`;
|
|
663
|
+
const outPath = join4(generatedDir, "routes.ts");
|
|
664
|
+
await writeFileIfChanged(outPath, content);
|
|
665
|
+
return outPath;
|
|
666
|
+
}
|
|
667
|
+
function createRouteTree(segment = "") {
|
|
668
|
+
return { segment, children: new Map };
|
|
669
|
+
}
|
|
670
|
+
function insertRouteLayout(root, layout, componentName) {
|
|
671
|
+
if (layout.path === "/") {
|
|
672
|
+
throw new Error(`[SixbCustomApp] Root layout ${layout.relativePath} must remain the global app wrapper.`);
|
|
673
|
+
}
|
|
674
|
+
const node = resolveRouteNode(root, layout.path, layout.relativePath);
|
|
675
|
+
if (node.layout) {
|
|
676
|
+
throw new Error(`[SixbCustomApp] Conflicting layouts '${node.layout.source}' and '${layout.relativePath}' own route '${layout.path}'.`);
|
|
677
|
+
}
|
|
678
|
+
node.layout = { componentName, source: layout.relativePath };
|
|
679
|
+
}
|
|
680
|
+
function insertRoutePage(root, path, componentName, source) {
|
|
681
|
+
const node = resolveRouteNode(root, path, source);
|
|
682
|
+
if (node.page) {
|
|
683
|
+
throw new Error(`[SixbCustomApp] Conflicting pages '${node.page.source}' and '${source}' match route '${path}'.`);
|
|
684
|
+
}
|
|
685
|
+
node.page = { componentName, source };
|
|
686
|
+
}
|
|
687
|
+
function resolveRouteNode(root, path, source) {
|
|
688
|
+
let node = root;
|
|
689
|
+
for (const segment of splitRoutePath(path)) {
|
|
690
|
+
const key = segment.startsWith(":") ? ":" : segment.toLowerCase();
|
|
691
|
+
const existing = node.children.get(key);
|
|
692
|
+
if (existing) {
|
|
693
|
+
if (existing.segment.startsWith(":") && segment.startsWith(":") && existing.segment !== segment) {
|
|
694
|
+
throw new Error(`[SixbCustomApp] Route '${source}' uses dynamic segment '${segment}', but '${existing.segment}' already owns the same route position. Use one parameter name consistently.`);
|
|
695
|
+
}
|
|
696
|
+
node = existing;
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
const child = createRouteTree(segment);
|
|
700
|
+
node.children.set(key, child);
|
|
701
|
+
node = child;
|
|
702
|
+
}
|
|
703
|
+
return node;
|
|
704
|
+
}
|
|
705
|
+
function renderRootRouteObjects(root) {
|
|
706
|
+
const lines = [];
|
|
707
|
+
if (root.page) {
|
|
708
|
+
lines.push(` { path: "/", element: createElement(${root.page.componentName}) },`);
|
|
709
|
+
}
|
|
710
|
+
for (const child of sortedRenderableChildren(root)) {
|
|
711
|
+
lines.push(...renderRouteNode(child, 1));
|
|
712
|
+
}
|
|
713
|
+
return lines.join(`
|
|
714
|
+
`);
|
|
715
|
+
}
|
|
716
|
+
function renderRouteNode(node, depth) {
|
|
717
|
+
const indent = " ".repeat(depth);
|
|
718
|
+
const children = sortedRenderableChildren(node);
|
|
719
|
+
if (!node.layout && node.page && children.length === 0) {
|
|
720
|
+
return [
|
|
721
|
+
`${indent}{ path: ${JSON.stringify(node.segment)}, element: createElement(${node.page.componentName}) },`
|
|
722
|
+
];
|
|
723
|
+
}
|
|
724
|
+
const lines = [`${indent}{`, `${indent} path: ${JSON.stringify(node.segment)},`];
|
|
725
|
+
if (node.layout) {
|
|
726
|
+
lines.push(`${indent} element: createElement(${node.layout.componentName}, { children: createElement(Outlet) }),`);
|
|
727
|
+
}
|
|
728
|
+
lines.push(`${indent} children: [`);
|
|
729
|
+
if (node.page) {
|
|
730
|
+
lines.push(`${indent} { index: true, element: createElement(${node.page.componentName}) },`);
|
|
731
|
+
}
|
|
732
|
+
for (const child of children) {
|
|
733
|
+
lines.push(...renderRouteNode(child, depth + 2));
|
|
734
|
+
}
|
|
735
|
+
lines.push(`${indent} ],`, `${indent}},`);
|
|
736
|
+
return lines;
|
|
737
|
+
}
|
|
738
|
+
function sortedRenderableChildren(node) {
|
|
739
|
+
return [...node.children.values()].filter(hasPageDescendant).sort((a, b) => {
|
|
740
|
+
const aDynamic = a.segment.startsWith(":");
|
|
741
|
+
const bDynamic = b.segment.startsWith(":");
|
|
742
|
+
if (aDynamic !== bDynamic)
|
|
743
|
+
return aDynamic ? 1 : -1;
|
|
744
|
+
return compareText2(a.segment, b.segment);
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
function hasPageDescendant(node) {
|
|
748
|
+
if (node.page)
|
|
749
|
+
return true;
|
|
750
|
+
for (const child of node.children.values()) {
|
|
751
|
+
if (hasPageDescendant(child))
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
return false;
|
|
755
|
+
}
|
|
756
|
+
function splitRoutePath(path) {
|
|
757
|
+
if (path === "/")
|
|
758
|
+
return [];
|
|
759
|
+
if (!path.startsWith("/")) {
|
|
760
|
+
throw new Error(`[SixbCustomApp] Route path '${path}' must start with '/'.`);
|
|
761
|
+
}
|
|
762
|
+
const segments = path.slice(1).split("/");
|
|
763
|
+
if (segments.some((segment) => !segment)) {
|
|
764
|
+
throw new Error(`[SixbCustomApp] Route path '${path}' contains an empty segment.`);
|
|
765
|
+
}
|
|
766
|
+
return segments;
|
|
767
|
+
}
|
|
768
|
+
function compareRouteModules2(a, b) {
|
|
769
|
+
return compareText2(a.path, b.path) || compareText2(a.relativePath, b.relativePath);
|
|
770
|
+
}
|
|
771
|
+
function compareText2(a, b) {
|
|
772
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
773
|
+
}
|
|
774
|
+
async function generateAuthExperienceEntry(projectRoot, generatedDir, options = {}) {
|
|
775
|
+
await mkdir2(generatedDir, { recursive: true });
|
|
776
|
+
const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join4(projectRoot, "app");
|
|
777
|
+
const authPath = join4(appDir, "auth.tsx");
|
|
778
|
+
if (!await fileExists2(authPath)) {
|
|
779
|
+
return null;
|
|
780
|
+
}
|
|
781
|
+
const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join4(appDir, "public");
|
|
782
|
+
const layoutPath = join4(appDir, "layout.tsx");
|
|
783
|
+
const globalsCssPath = join4(appDir, "globals.css");
|
|
784
|
+
const metadata = await resolveAppMetadata({ layoutPath, publicDir });
|
|
785
|
+
const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
|
|
786
|
+
const stylesheetImport = stylesheetPath ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}` : "";
|
|
787
|
+
const authRel = relativeTo(generatedDir, authPath);
|
|
788
|
+
const mainContent = `import React from "react"
|
|
789
|
+
import { createRoot } from "react-dom/client"
|
|
790
|
+
import type {
|
|
791
|
+
AuthExperienceActions,
|
|
792
|
+
AuthExperienceState,
|
|
793
|
+
} from "@sixb/app"
|
|
794
|
+
import AuthExperience from ${JSON.stringify(authRel)}
|
|
795
|
+
${stylesheetImport}
|
|
796
|
+
|
|
797
|
+
interface AuthExperienceBootstrap {
|
|
798
|
+
readonly state: AuthExperienceState
|
|
799
|
+
readonly signInUrl: string
|
|
800
|
+
readonly submission?: {
|
|
801
|
+
readonly kind: "requestMagicLink" | "confirmSignIn"
|
|
802
|
+
readonly action: string
|
|
803
|
+
readonly fields: Readonly<Record<string, string>>
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const root = document.getElementById("root")
|
|
808
|
+
if (!root) {
|
|
809
|
+
throw new Error("[SixbApp] Could not find the auth experience root element.")
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
const encodedBootstrap = root.dataset.sixbAuth
|
|
813
|
+
if (!encodedBootstrap) {
|
|
814
|
+
throw new Error("[SixbApp] Auth experience bootstrap is missing.")
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const bootstrap = decodeBootstrap(encodedBootstrap)
|
|
818
|
+
const actions: AuthExperienceActions = {
|
|
819
|
+
requestMagicLink(email) {
|
|
820
|
+
submit("requestMagicLink", { email })
|
|
821
|
+
},
|
|
822
|
+
confirmSignIn() {
|
|
823
|
+
submit("confirmSignIn")
|
|
824
|
+
},
|
|
825
|
+
restartSignIn() {
|
|
826
|
+
window.location.assign(bootstrap.signInUrl)
|
|
827
|
+
},
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function submit(
|
|
831
|
+
kind: NonNullable<AuthExperienceBootstrap["submission"]>["kind"],
|
|
832
|
+
additionalFields: Readonly<Record<string, string>> = {}
|
|
833
|
+
): void {
|
|
834
|
+
const submission = bootstrap.submission
|
|
835
|
+
if (!submission || submission.kind !== kind) {
|
|
836
|
+
throw new Error("[SixbApp] Auth action '" + kind + "' is not available in this state.")
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
const form = document.createElement("form")
|
|
840
|
+
form.method = "post"
|
|
841
|
+
form.action = submission.action
|
|
842
|
+
form.hidden = true
|
|
843
|
+
for (const [name, value] of Object.entries({ ...submission.fields, ...additionalFields })) {
|
|
844
|
+
const input = document.createElement("input")
|
|
845
|
+
input.type = "hidden"
|
|
846
|
+
input.name = name
|
|
847
|
+
input.value = value
|
|
848
|
+
form.append(input)
|
|
849
|
+
}
|
|
850
|
+
document.body.append(form)
|
|
851
|
+
form.submit()
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function decodeBootstrap(value: string): AuthExperienceBootstrap {
|
|
855
|
+
const base64 = value.replaceAll("-", "+").replaceAll("_", "/")
|
|
856
|
+
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
|
|
857
|
+
const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0))
|
|
858
|
+
return JSON.parse(new TextDecoder().decode(bytes)) as AuthExperienceBootstrap
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
|
|
862
|
+
`;
|
|
863
|
+
const mainPath = join4(generatedDir, "auth-main.tsx");
|
|
864
|
+
await writeFileIfChanged(mainPath, mainContent);
|
|
865
|
+
const htmlContent = `<!DOCTYPE html>
|
|
866
|
+
<html lang="en">
|
|
867
|
+
<head>
|
|
868
|
+
<meta charset="UTF-8" />
|
|
869
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
|
870
|
+
${renderAuthMetadataHead(metadata)}
|
|
871
|
+
<style>
|
|
872
|
+
* { box-sizing: border-box; }
|
|
873
|
+
html, body, #root { margin: 0; min-height: 100%; }
|
|
874
|
+
body, #root { min-height: 100vh; min-height: 100dvh; }
|
|
875
|
+
</style>
|
|
876
|
+
</head>
|
|
877
|
+
<body>
|
|
878
|
+
<div id="root" data-sixb-auth="${AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER}"></div>
|
|
879
|
+
<script type="module" src="./auth-main.tsx"></script>
|
|
880
|
+
</body>
|
|
881
|
+
</html>
|
|
882
|
+
`;
|
|
883
|
+
const htmlPath = join4(generatedDir, "auth-index.html");
|
|
884
|
+
await writeFileIfChanged(htmlPath, htmlContent);
|
|
885
|
+
return { htmlPath, mainPath };
|
|
886
|
+
}
|
|
887
|
+
async function generateAppEntry(projectRoot, generatedDir, options = {}) {
|
|
888
|
+
await mkdir2(generatedDir, { recursive: true });
|
|
889
|
+
const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join4(projectRoot, "app");
|
|
890
|
+
const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join4(appDir, "public");
|
|
891
|
+
const globalsCssPath = join4(appDir, "globals.css");
|
|
892
|
+
const layoutPath = join4(appDir, "layout.tsx");
|
|
893
|
+
const metadata = await resolveAppMetadata({ layoutPath, publicDir });
|
|
894
|
+
const manifestPath = join4(generatedDir, "app.webmanifest");
|
|
895
|
+
await writeFileIfChanged(manifestPath, renderAppManifest(metadata));
|
|
896
|
+
const layoutRel = relativeTo(generatedDir, layoutPath);
|
|
897
|
+
const hasLayout = await fileExists2(layoutPath);
|
|
898
|
+
const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
|
|
899
|
+
const stylesheetPaths = [
|
|
900
|
+
...options.frameworkStylesheetPaths ?? [],
|
|
901
|
+
...stylesheetPath ? [stylesheetPath] : []
|
|
902
|
+
];
|
|
903
|
+
const globalsCssImport = stylesheetPaths.map((path) => `import ${JSON.stringify(relativeTo(generatedDir, path))}`).join(`
|
|
904
|
+
`);
|
|
905
|
+
const sections = options.sections ?? false;
|
|
906
|
+
const layoutImport = !hasLayout ? "" : sections ? `import RootLayout, * as rootLayoutModule from ${JSON.stringify(layoutRel)}
|
|
907
|
+
` : `import RootLayout from ${JSON.stringify(layoutRel)}
|
|
908
|
+
`;
|
|
909
|
+
const defaultShell = sections && !hasLayout && !options.projectPages;
|
|
910
|
+
const sectionsImport = sections ? `import ${defaultShell ? "{ AppShell, type AppVisibility }" : "type { AppVisibility }"} from "@sixb/app"
|
|
911
|
+
import { SectionsProvider } from "@sixb/app/pages"
|
|
912
|
+
` : "";
|
|
913
|
+
const sectionsSetup = !sections ? "" : hasLayout ? `const visibility = Reflect.get(rootLayoutModule, "visibility") as AppVisibility | undefined` : "const visibility = undefined";
|
|
914
|
+
const sectionsStart = sections ? `<SectionsProvider visibility={visibility} enabled={!basename}>` : "";
|
|
915
|
+
const sectionsEnd = sections ? "</SectionsProvider>" : "";
|
|
916
|
+
const layoutWrapperStart = hasLayout ? "<RootLayout>" : defaultShell ? "<AppShell>" : "<>";
|
|
917
|
+
const layoutWrapperEnd = hasLayout ? "</RootLayout>" : defaultShell ? "</AppShell>" : "</>";
|
|
918
|
+
const runtimeConfigScript = options.apiBaseUrl ? renderCustomAppRuntimeScript({
|
|
919
|
+
api: { baseUrl: options.apiBaseUrl },
|
|
920
|
+
auth: { enabled: options.authEnabled ?? true }
|
|
921
|
+
}) : "";
|
|
922
|
+
const runtimeContent = `import React from "react"
|
|
923
|
+
import { createRoot, type Root } from "react-dom/client"
|
|
924
|
+
import type { GetAuthSessionResponse } from "@sixb/client"
|
|
925
|
+
import {
|
|
926
|
+
BrowserRouter,
|
|
927
|
+
matchPath,
|
|
928
|
+
useLocation,
|
|
929
|
+
useNavigate,
|
|
930
|
+
useRoutes,
|
|
931
|
+
} from "react-router-dom"
|
|
932
|
+
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"
|
|
933
|
+
import { isSixbApiError } from "@sixb/client/browser"
|
|
934
|
+
import {
|
|
935
|
+
getAuthSessionQueryKey,
|
|
936
|
+
getProjectInfoOptions,
|
|
937
|
+
SixbEventsProvider,
|
|
938
|
+
} from "@sixb/client/hooks"
|
|
939
|
+
import { LocaleProvider, useAppMessages } from "@sixb/app/locale"
|
|
940
|
+
${sectionsImport}import { routePaths, routes } from "./routes"
|
|
941
|
+
${globalsCssImport}
|
|
942
|
+
${layoutImport}
|
|
943
|
+
|
|
944
|
+
interface CustomAppHotData {
|
|
945
|
+
root?: Root
|
|
946
|
+
queryClient?: QueryClient
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
export interface StartAppOptions {
|
|
950
|
+
readonly basename?: string
|
|
951
|
+
/** The session the bootstrap already loaded, so useCurrentUser does not fetch it again. */
|
|
952
|
+
readonly session?: GetAuthSessionResponse
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
if (import.meta.hot) import.meta.hot.accept()
|
|
956
|
+
|
|
957
|
+
const queryClient = getQueryClient()
|
|
958
|
+
|
|
959
|
+
function getRoot(): Root {
|
|
960
|
+
const element = document.getElementById("root")
|
|
961
|
+
if (!element) {
|
|
962
|
+
throw new Error("[SixbApp] Could not find the root element.")
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
if (import.meta.hot) {
|
|
966
|
+
const data = import.meta.hot.data as CustomAppHotData
|
|
967
|
+
data.root ??= createRoot(element)
|
|
968
|
+
return data.root
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
return createRoot(element)
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
function getQueryClient(): QueryClient {
|
|
975
|
+
if (import.meta.hot) {
|
|
976
|
+
const data = import.meta.hot.data as CustomAppHotData
|
|
977
|
+
data.queryClient ??= createQueryClient()
|
|
978
|
+
return data.queryClient
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
return createQueryClient()
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
function createQueryClient(): QueryClient {
|
|
985
|
+
return new QueryClient({
|
|
986
|
+
defaultOptions: {
|
|
987
|
+
queries: {
|
|
988
|
+
refetchOnWindowFocus: false,
|
|
989
|
+
retry: 1,
|
|
990
|
+
},
|
|
991
|
+
},
|
|
992
|
+
})
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
const RESERVED_PATH_PREFIXES = ["/api", "/auth", "/ws", "/docs", "/shared"]
|
|
996
|
+
|
|
997
|
+
function isReservedPath(pathname: string) {
|
|
998
|
+
return RESERVED_PATH_PREFIXES.some(
|
|
999
|
+
(prefix) => pathname === prefix || pathname.startsWith(prefix + "/")
|
|
1000
|
+
)
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
function isSharedTransportPath(pathname: string): boolean {
|
|
1004
|
+
return pathname === "/shared" || pathname.startsWith("/shared/")
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function primaryNavigationAnchor(event: MouseEvent): HTMLAnchorElement | null {
|
|
1008
|
+
if (event.defaultPrevented) return null
|
|
1009
|
+
if (event.button !== 0) return null
|
|
1010
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null
|
|
1011
|
+
|
|
1012
|
+
const target = event.target
|
|
1013
|
+
if (!(target instanceof Element)) return null
|
|
1014
|
+
const anchor = target.closest("a")
|
|
1015
|
+
if (!(anchor instanceof HTMLAnchorElement)) return null
|
|
1016
|
+
if (anchor.target && anchor.target !== "_self") return null
|
|
1017
|
+
if (anchor.hasAttribute("download")) return null
|
|
1018
|
+
if (anchor.relList.contains("external")) return null
|
|
1019
|
+
if (!anchor.getAttribute("href")) return null
|
|
1020
|
+
return anchor
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// A React Router <Link> mutates the current document before effects can reload it. Capture shared
|
|
1024
|
+
// transport clicks first so an OIDC document never acquires a bearer fragment.
|
|
1025
|
+
function SharedDocumentLinkInterceptor({ basename }: { readonly basename?: string }) {
|
|
1026
|
+
React.useLayoutEffect(() => {
|
|
1027
|
+
function onClick(event: MouseEvent) {
|
|
1028
|
+
const anchor = primaryNavigationAnchor(event)
|
|
1029
|
+
if (!anchor) return
|
|
1030
|
+
|
|
1031
|
+
const url = new URL(anchor.href, window.location.href)
|
|
1032
|
+
if (url.origin !== window.location.origin) return
|
|
1033
|
+
const appPath = pathInsideApp(url.pathname, basename)
|
|
1034
|
+
if (!isSharedTransportPath(appPath)) return
|
|
1035
|
+
|
|
1036
|
+
// React Router prefixes an absolute <Link to="/shared/..."> with the current basename.
|
|
1037
|
+
// Rebuild the transport URL from the path inside the app so switching grants does not nest
|
|
1038
|
+
// the new link beneath /shared/:currentGrantId.
|
|
1039
|
+
const documentUrl = new URL(appPath + url.search + url.hash, url.origin)
|
|
1040
|
+
|
|
1041
|
+
event.preventDefault()
|
|
1042
|
+
event.stopImmediatePropagation()
|
|
1043
|
+
window.location.assign(documentUrl.href)
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
document.addEventListener("click", onClick, true)
|
|
1047
|
+
return () => document.removeEventListener("click", onClick, true)
|
|
1048
|
+
}, [basename])
|
|
1049
|
+
|
|
1050
|
+
return null
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
// Makes plain same-origin <a href="/..."> clicks navigate client-side, so app
|
|
1054
|
+
// authors get SPA navigation without remembering react-router's <Link>.
|
|
1055
|
+
// Deliberately conservative: anything unusual falls through to the browser.
|
|
1056
|
+
function InternalLinkInterceptor({ basename }: { readonly basename?: string }) {
|
|
1057
|
+
const navigate = useNavigate()
|
|
1058
|
+
|
|
1059
|
+
React.useEffect(() => {
|
|
1060
|
+
function onClick(event: MouseEvent) {
|
|
1061
|
+
const anchor = primaryNavigationAnchor(event)
|
|
1062
|
+
if (!anchor) return
|
|
1063
|
+
|
|
1064
|
+
const url = new URL(anchor.href, window.location.href)
|
|
1065
|
+
if (url.origin !== window.location.origin) return
|
|
1066
|
+
const appPath = pathInsideApp(url.pathname, basename)
|
|
1067
|
+
if (isReservedPath(appPath)) return
|
|
1068
|
+
// Only intercept destinations the app actually routes; anything else may
|
|
1069
|
+
// be a real server resource and keeps native navigation.
|
|
1070
|
+
if (!routePaths.some((path) => matchPath(path, appPath))) return
|
|
1071
|
+
// Same-document hash links keep native scroll behavior.
|
|
1072
|
+
if (
|
|
1073
|
+
url.hash &&
|
|
1074
|
+
url.pathname === window.location.pathname &&
|
|
1075
|
+
url.search === window.location.search
|
|
1076
|
+
) {
|
|
1077
|
+
return
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
event.preventDefault()
|
|
1081
|
+
navigate(appPath + url.search + url.hash)
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
document.addEventListener("click", onClick)
|
|
1085
|
+
return () => document.removeEventListener("click", onClick)
|
|
1086
|
+
}, [basename, navigate])
|
|
1087
|
+
|
|
1088
|
+
return null
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
function pathInsideApp(pathname: string, basename: string | undefined): string {
|
|
1092
|
+
if (
|
|
1093
|
+
basename &&
|
|
1094
|
+
(pathname === basename || pathname.startsWith(basename.endsWith("/") ? basename : basename + "/"))
|
|
1095
|
+
) {
|
|
1096
|
+
return pathname.slice(basename.length) || "/"
|
|
1097
|
+
}
|
|
1098
|
+
return pathname
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
// Programmatic React Router navigation cannot be blocked by BrowserRouter. Gate the ordinary page
|
|
1102
|
+
// tree while forcing the new document so no route can run under the previous OIDC authority.
|
|
1103
|
+
function SharedDocumentBoundary({ children }: { readonly children: React.ReactNode }) {
|
|
1104
|
+
const location = useLocation()
|
|
1105
|
+
const crossingBoundary = isSharedTransportPath(location.pathname)
|
|
1106
|
+
|
|
1107
|
+
React.useLayoutEffect(() => {
|
|
1108
|
+
if (crossingBoundary) window.location.reload()
|
|
1109
|
+
}, [crossingBoundary])
|
|
1110
|
+
|
|
1111
|
+
return crossingBoundary ? null : children
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// Shared presentational fallback used by the not-found view and the error
|
|
1115
|
+
// boundary. Styled with @sixb/ui design tokens (var(--token)) so it adopts the
|
|
1116
|
+
// app's theme when those tokens are loaded, but every token has a hardcoded
|
|
1117
|
+
// fallback so it stays self-contained and readable when they are not. The
|
|
1118
|
+
// background/foreground pair is always set together so text stays legible
|
|
1119
|
+
// regardless of the surrounding app's background.
|
|
1120
|
+
function AppFallback({
|
|
1121
|
+
title,
|
|
1122
|
+
detail,
|
|
1123
|
+
showReload = true,
|
|
1124
|
+
action,
|
|
1125
|
+
}: {
|
|
1126
|
+
title: string
|
|
1127
|
+
detail: string
|
|
1128
|
+
showReload?: boolean
|
|
1129
|
+
action?: React.ReactNode
|
|
1130
|
+
}) {
|
|
1131
|
+
const messages = useAppMessages()
|
|
1132
|
+
return (
|
|
1133
|
+
<div
|
|
1134
|
+
role="alert"
|
|
1135
|
+
style={{
|
|
1136
|
+
minHeight: "100dvh",
|
|
1137
|
+
display: "flex",
|
|
1138
|
+
flexDirection: "column",
|
|
1139
|
+
alignItems: "center",
|
|
1140
|
+
justifyContent: "center",
|
|
1141
|
+
gap: "1rem",
|
|
1142
|
+
padding: "2rem",
|
|
1143
|
+
textAlign: "center",
|
|
1144
|
+
fontFamily:
|
|
1145
|
+
"var(--font-sans, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif)",
|
|
1146
|
+
background: "var(--background, #ffffff)",
|
|
1147
|
+
color: "var(--foreground, #1f2933)",
|
|
1148
|
+
}}
|
|
1149
|
+
>
|
|
1150
|
+
<h1 style={{ margin: 0, fontSize: "1.5rem", fontWeight: 600 }}>{title}</h1>
|
|
1151
|
+
<p style={{ margin: 0, maxWidth: "32rem", color: "var(--muted-foreground, #52606d)" }}>
|
|
1152
|
+
{detail}
|
|
1153
|
+
</p>
|
|
1154
|
+
<div style={{ display: "flex", gap: "0.75rem" }}>
|
|
1155
|
+
{action ?? (
|
|
1156
|
+
<>
|
|
1157
|
+
<a
|
|
1158
|
+
href="/"
|
|
1159
|
+
style={{
|
|
1160
|
+
padding: "0.5rem 1rem",
|
|
1161
|
+
borderRadius: "var(--radius, 0.5rem)",
|
|
1162
|
+
background: "var(--primary, #1f2933)",
|
|
1163
|
+
color: "var(--primary-foreground, #ffffff)",
|
|
1164
|
+
textDecoration: "none",
|
|
1165
|
+
}}
|
|
1166
|
+
>
|
|
1167
|
+
{messages.goHome}
|
|
1168
|
+
</a>
|
|
1169
|
+
{showReload ? (
|
|
1170
|
+
<button
|
|
1171
|
+
type="button"
|
|
1172
|
+
onClick={() => window.location.reload()}
|
|
1173
|
+
style={{
|
|
1174
|
+
padding: "0.5rem 1rem",
|
|
1175
|
+
borderRadius: "var(--radius, 0.5rem)",
|
|
1176
|
+
border: "1px solid var(--border, #cbd2d9)",
|
|
1177
|
+
background: "transparent",
|
|
1178
|
+
color: "inherit",
|
|
1179
|
+
cursor: "pointer",
|
|
1180
|
+
}}
|
|
1181
|
+
>
|
|
1182
|
+
{messages.reload}
|
|
1183
|
+
</button>
|
|
1184
|
+
) : null}
|
|
1185
|
+
</>
|
|
1186
|
+
)}
|
|
1187
|
+
</div>
|
|
1188
|
+
</div>
|
|
1189
|
+
)
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
// The not-found view. Rendered both for unmatched client routes (the catch-all
|
|
1193
|
+
// route below) and for an expected 404 surfaced through a query. Apps will be
|
|
1194
|
+
// able to override this via app/not-found.tsx.
|
|
1195
|
+
function NotFoundView() {
|
|
1196
|
+
const messages = useAppMessages().notFound
|
|
1197
|
+
return (
|
|
1198
|
+
<AppFallback
|
|
1199
|
+
title={messages.title}
|
|
1200
|
+
detail={messages.detail}
|
|
1201
|
+
showReload={false}
|
|
1202
|
+
/>
|
|
1203
|
+
)
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
// Last-resort safety net so an uncaught render throw (a 404 surfaced through a
|
|
1207
|
+
// suspense/throwOnError query, a bug, a failed import) shows a fallback instead
|
|
1208
|
+
// of a blank page and a console error. A missing object is an expected state,
|
|
1209
|
+
// so a 404 reuses the not-found view rather than the generic crash screen.
|
|
1210
|
+
// Apps will be able to override this via app/error.tsx.
|
|
1211
|
+
function AppErrorFallback({
|
|
1212
|
+
error,
|
|
1213
|
+
hideErrorDetails,
|
|
1214
|
+
}: {
|
|
1215
|
+
error: unknown
|
|
1216
|
+
hideErrorDetails: boolean
|
|
1217
|
+
}) {
|
|
1218
|
+
const messages = useAppMessages().error
|
|
1219
|
+
if (isSixbApiError(error) && error.status === 404) {
|
|
1220
|
+
return <NotFoundView />
|
|
1221
|
+
}
|
|
1222
|
+
return (
|
|
1223
|
+
<AppFallback
|
|
1224
|
+
title={messages.title}
|
|
1225
|
+
detail={
|
|
1226
|
+
hideErrorDetails
|
|
1227
|
+
? messages.sharedDetail
|
|
1228
|
+
: error instanceof Error
|
|
1229
|
+
? error.message
|
|
1230
|
+
: String(error)
|
|
1231
|
+
}
|
|
1232
|
+
/>
|
|
1233
|
+
)
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
class AppErrorBoundary extends React.Component<
|
|
1237
|
+
{ resetKey: string; hideErrorDetails: boolean; children: React.ReactNode },
|
|
1238
|
+
{ error: unknown }
|
|
1239
|
+
> {
|
|
1240
|
+
state: { error: unknown } = { error: null }
|
|
1241
|
+
|
|
1242
|
+
static getDerivedStateFromError(error: unknown) {
|
|
1243
|
+
return { error }
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
componentDidCatch(error: unknown) {
|
|
1247
|
+
if (this.props.hideErrorDetails) {
|
|
1248
|
+
console.error("[SixbApp] A shared page failed to render.")
|
|
1249
|
+
} else {
|
|
1250
|
+
console.error("[SixbApp] Uncaught render error:", error)
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
// Clear the error when the route changes so navigating away (or an in-app
|
|
1255
|
+
// link) recovers without a full reload.
|
|
1256
|
+
componentDidUpdate(prevProps: { resetKey: string }) {
|
|
1257
|
+
if (this.state.error !== null && prevProps.resetKey !== this.props.resetKey) {
|
|
1258
|
+
this.setState({ error: null })
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
render() {
|
|
1263
|
+
if (this.state.error !== null) {
|
|
1264
|
+
return (
|
|
1265
|
+
<AppErrorFallback
|
|
1266
|
+
error={this.state.error}
|
|
1267
|
+
hideErrorDetails={this.props.hideErrorDetails}
|
|
1268
|
+
/>
|
|
1269
|
+
)
|
|
1270
|
+
}
|
|
1271
|
+
return this.props.children
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
function RoutedErrorBoundary({
|
|
1276
|
+
children,
|
|
1277
|
+
hideErrorDetails,
|
|
1278
|
+
}: {
|
|
1279
|
+
children: React.ReactNode
|
|
1280
|
+
hideErrorDetails: boolean
|
|
1281
|
+
}) {
|
|
1282
|
+
const location = useLocation()
|
|
1283
|
+
return (
|
|
1284
|
+
<AppErrorBoundary
|
|
1285
|
+
resetKey={location.pathname + location.search}
|
|
1286
|
+
hideErrorDetails={hideErrorDetails}
|
|
1287
|
+
>
|
|
1288
|
+
{children}
|
|
1289
|
+
</AppErrorBoundary>
|
|
1290
|
+
)
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
const appRoutes = [...routes, { path: "*", element: <NotFoundView /> }]
|
|
1294
|
+
${sectionsSetup}
|
|
1295
|
+
|
|
1296
|
+
function AppRoutes() {
|
|
1297
|
+
return useRoutes(appRoutes)
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
function RoutedApp({ hideErrorDetails }: { readonly hideErrorDetails: boolean }) {
|
|
1301
|
+
return (
|
|
1302
|
+
<RoutedErrorBoundary hideErrorDetails={hideErrorDetails}>
|
|
1303
|
+
${layoutWrapperStart}
|
|
1304
|
+
<AppRoutes />
|
|
1305
|
+
${layoutWrapperEnd}
|
|
1306
|
+
</RoutedErrorBoundary>
|
|
1307
|
+
)
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// Project settings do not change while the app runs: never refetch or collect them. Built on use:
|
|
1311
|
+
// the query key captures the API base URL, which the bootstrap configures after this module loads.
|
|
1312
|
+
function projectInfoQuery() {
|
|
1313
|
+
return {
|
|
1314
|
+
...getProjectInfoOptions(),
|
|
1315
|
+
staleTime: Number.POSITIVE_INFINITY,
|
|
1316
|
+
gcTime: Number.POSITIVE_INFINITY,
|
|
1317
|
+
retry: false,
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
// Framework text follows the reader's browser languages and falls back to the project's. A shared
|
|
1322
|
+
// link's grant cannot read project settings, so it keeps the browser's languages alone.
|
|
1323
|
+
function ProjectLocale({
|
|
1324
|
+
shared,
|
|
1325
|
+
children,
|
|
1326
|
+
}: {
|
|
1327
|
+
readonly shared: boolean
|
|
1328
|
+
readonly children: React.ReactNode
|
|
1329
|
+
}) {
|
|
1330
|
+
const { data: project } = useQuery({ ...projectInfoQuery(), enabled: !shared })
|
|
1331
|
+
return <LocaleProvider fallbackLocale={project?.locale}>{children}</LocaleProvider>
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
function App({ basename }: StartAppOptions) {
|
|
1335
|
+
return (
|
|
1336
|
+
<QueryClientProvider client={queryClient}>
|
|
1337
|
+
{/* One event socket for every live page, opened only once something subscribes. */}
|
|
1338
|
+
<SixbEventsProvider>
|
|
1339
|
+
<ProjectLocale shared={Boolean(basename)}>
|
|
1340
|
+
${sectionsStart}
|
|
1341
|
+
<BrowserRouter basename={basename}>
|
|
1342
|
+
<SharedDocumentLinkInterceptor basename={basename} />
|
|
1343
|
+
<InternalLinkInterceptor basename={basename} />
|
|
1344
|
+
{basename ? (
|
|
1345
|
+
<RoutedApp hideErrorDetails />
|
|
1346
|
+
) : (
|
|
1347
|
+
<SharedDocumentBoundary>
|
|
1348
|
+
<RoutedApp hideErrorDetails={false} />
|
|
1349
|
+
</SharedDocumentBoundary>
|
|
1350
|
+
)}
|
|
1351
|
+
</BrowserRouter>
|
|
1352
|
+
${sectionsEnd}
|
|
1353
|
+
</ProjectLocale>
|
|
1354
|
+
</SixbEventsProvider>
|
|
1355
|
+
</QueryClientProvider>
|
|
1356
|
+
)
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
export function startApp(options: StartAppOptions = {}) {
|
|
1360
|
+
if (options.session) queryClient.setQueryData(getAuthSessionQueryKey(), options.session)
|
|
1361
|
+
// The HTML is built without loading the project: declare the project's language on the document
|
|
1362
|
+
// as soon as the API answers, without waiting for the page tree to render.
|
|
1363
|
+
if (!options.basename) {
|
|
1364
|
+
void queryClient.fetchQuery(projectInfoQuery()).then(
|
|
1365
|
+
(project) => {
|
|
1366
|
+
document.documentElement.lang = project.locale
|
|
1367
|
+
},
|
|
1368
|
+
() => undefined
|
|
1369
|
+
)
|
|
1370
|
+
}
|
|
1371
|
+
getRoot().render(<App basename={options.basename} />)
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// Without a session the project's locale is unknown: this speaks the browser's language.
|
|
1375
|
+
export function renderApiUnavailable(apiBaseUrl: string) {
|
|
1376
|
+
getRoot().render(
|
|
1377
|
+
<LocaleProvider>
|
|
1378
|
+
<ApiUnavailableView apiBaseUrl={apiBaseUrl} />
|
|
1379
|
+
</LocaleProvider>
|
|
1380
|
+
)
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
function ApiUnavailableView({ apiBaseUrl }: { readonly apiBaseUrl: string }) {
|
|
1384
|
+
const messages = useAppMessages()
|
|
1385
|
+
return (
|
|
1386
|
+
<AppFallback
|
|
1387
|
+
title={messages.apiUnavailable.title}
|
|
1388
|
+
detail={messages.apiUnavailable.detail(apiBaseUrl)}
|
|
1389
|
+
action={
|
|
1390
|
+
<button
|
|
1391
|
+
type="button"
|
|
1392
|
+
onClick={() => window.location.reload()}
|
|
1393
|
+
style={{
|
|
1394
|
+
padding: "0.5rem 1rem",
|
|
1395
|
+
borderRadius: "var(--radius, 0.5rem)",
|
|
1396
|
+
border: "1px solid var(--border, #cbd2d9)",
|
|
1397
|
+
background: "transparent",
|
|
1398
|
+
color: "inherit",
|
|
1399
|
+
cursor: "pointer",
|
|
1400
|
+
}}
|
|
1401
|
+
>
|
|
1402
|
+
{messages.retry}
|
|
1403
|
+
</button>
|
|
1404
|
+
}
|
|
1405
|
+
/>
|
|
1406
|
+
)
|
|
1407
|
+
}
|
|
1408
|
+
`;
|
|
1409
|
+
const runtimePath = join4(generatedDir, "app-runtime.tsx");
|
|
1410
|
+
await writeFileIfChanged(runtimePath, runtimeContent);
|
|
1411
|
+
const mainContent = `import {
|
|
1412
|
+
configureSixbBrowserClient,
|
|
1413
|
+
readSixbBrowserRuntimeConfig,
|
|
1414
|
+
requireSixbBrowserAuthSession,
|
|
1415
|
+
} from "@sixb/client/browser"
|
|
1416
|
+
import { renderApiUnavailable, startApp } from "./app-runtime"
|
|
1417
|
+
|
|
1418
|
+
const runtimeConfig = readSixbBrowserRuntimeConfig()
|
|
1419
|
+
const browserClient = configureSixbBrowserClient(runtimeConfig)
|
|
1420
|
+
|
|
1421
|
+
if (import.meta.hot) {
|
|
1422
|
+
import.meta.hot.accept()
|
|
1423
|
+
import.meta.hot.dispose(() => browserClient.dispose())
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
// Without the API's answer the app can neither render nor send the user to sign in.
|
|
1427
|
+
const authSession = runtimeConfig.auth.enabled
|
|
1428
|
+
? await requireSixbBrowserAuthSession(runtimeConfig, browserClient).catch((error: unknown) => {
|
|
1429
|
+
console.error("[SixbCustomApp] Could not load the session from the API:", error)
|
|
1430
|
+
return "unavailable" as const
|
|
1431
|
+
})
|
|
1432
|
+
: null
|
|
1433
|
+
|
|
1434
|
+
if (authSession === "unavailable") {
|
|
1435
|
+
renderApiUnavailable(runtimeConfig.api.baseUrl)
|
|
1436
|
+
} else if (
|
|
1437
|
+
!runtimeConfig.auth.enabled ||
|
|
1438
|
+
(authSession?.authenticated === false && authSession.authEnabled === false) ||
|
|
1439
|
+
authSession?.authenticated === true
|
|
1440
|
+
) {
|
|
1441
|
+
startApp({ session: authSession ?? undefined })
|
|
1442
|
+
}
|
|
1443
|
+
`;
|
|
1444
|
+
const mainPath = join4(generatedDir, "main.tsx");
|
|
1445
|
+
await writeFileIfChanged(mainPath, mainContent);
|
|
1446
|
+
const sharedMainContent = `import { browserAppLocale, browserAppMessages } from "@sixb/app/locale"
|
|
1447
|
+
import {
|
|
1448
|
+
configureSixbSharedBrowserClient,
|
|
1449
|
+
isSixbApiError,
|
|
1450
|
+
readSixbBrowserRuntimeConfig,
|
|
1451
|
+
type SixbSharedBrowserClientController,
|
|
1452
|
+
} from "@sixb/client/browser"
|
|
1453
|
+
|
|
1454
|
+
export interface SharedAppBootstrap {
|
|
1455
|
+
readonly basename: string
|
|
1456
|
+
readonly grantId: string
|
|
1457
|
+
readonly requestedPath: string
|
|
1458
|
+
readonly secret: string | null
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
export interface SharedAppStartOptions {
|
|
1462
|
+
readonly loadAppStyles?: () => Promise<void>
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
let activeController: SixbSharedBrowserClientController | null = null
|
|
1466
|
+
|
|
1467
|
+
if (import.meta.hot) {
|
|
1468
|
+
import.meta.hot.accept()
|
|
1469
|
+
import.meta.hot.dispose(() => {
|
|
1470
|
+
activeController?.dispose()
|
|
1471
|
+
activeController = null
|
|
1472
|
+
})
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
export function startSharedApp(
|
|
1476
|
+
bootstrap: SharedAppBootstrap,
|
|
1477
|
+
options: SharedAppStartOptions = {}
|
|
1478
|
+
): void {
|
|
1479
|
+
// A shared link speaks the reader's language: the grant cannot read the project's.
|
|
1480
|
+
document.documentElement.lang = browserAppLocale()
|
|
1481
|
+
if (!isValidBootstrap(bootstrap)) {
|
|
1482
|
+
renderSharedFallback("unavailable")
|
|
1483
|
+
return
|
|
1484
|
+
}
|
|
1485
|
+
const { basename, grantId } = bootstrap
|
|
1486
|
+
let loadAppStyles = options.loadAppStyles
|
|
1487
|
+
|
|
1488
|
+
activeController?.dispose()
|
|
1489
|
+
let controller: SixbSharedBrowserClientController
|
|
1490
|
+
try {
|
|
1491
|
+
const runtimeConfig = readSixbBrowserRuntimeConfig({ authEnabled: false })
|
|
1492
|
+
controller = configureSixbSharedBrowserClient(runtimeConfig, {
|
|
1493
|
+
grantId,
|
|
1494
|
+
})
|
|
1495
|
+
activeController = controller
|
|
1496
|
+
} catch {
|
|
1497
|
+
renderSharedFallback("unavailable")
|
|
1498
|
+
return
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
let secret = bootstrap.secret
|
|
1502
|
+
let canonicalDestinationPath: string | null = null
|
|
1503
|
+
let appStylesLoaded = false
|
|
1504
|
+
let pending = false
|
|
1505
|
+
|
|
1506
|
+
const open = async () => {
|
|
1507
|
+
if (pending) return
|
|
1508
|
+
pending = true
|
|
1509
|
+
renderSharedFallback("loading")
|
|
1510
|
+
|
|
1511
|
+
try {
|
|
1512
|
+
const exchangedSecret = secret !== null
|
|
1513
|
+
const session = await controller.establish(secret)
|
|
1514
|
+
// Once a server session exists the one-time link credential must not survive a retry.
|
|
1515
|
+
secret = null
|
|
1516
|
+
if (exchangedSecret) canonicalDestinationPath = session.destinationPath
|
|
1517
|
+
// Keep the trusted destination pending until this document is canonical or a hard
|
|
1518
|
+
// navigation to it has started. Application code never imports under the caller's path.
|
|
1519
|
+
if (canonicalDestinationPath !== null) {
|
|
1520
|
+
try {
|
|
1521
|
+
if (!canonicalizeInitialDestination(basename, canonicalDestinationPath)) return
|
|
1522
|
+
} catch (error) {
|
|
1523
|
+
// Both same-document canonicalization and the hard-navigation fallback failed. Retire
|
|
1524
|
+
// the newly established session before showing a terminal error so a reload cannot
|
|
1525
|
+
// restore it under the caller-controlled path.
|
|
1526
|
+
await controller.signOut().catch(() => undefined)
|
|
1527
|
+
controller.dispose()
|
|
1528
|
+
if (activeController === controller) activeController = null
|
|
1529
|
+
throw error
|
|
1530
|
+
}
|
|
1531
|
+
canonicalDestinationPath = null
|
|
1532
|
+
}
|
|
1533
|
+
if (!appStylesLoaded) {
|
|
1534
|
+
await loadAppStyles?.()
|
|
1535
|
+
loadAppStyles = undefined
|
|
1536
|
+
appStylesLoaded = true
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
const { startApp } = await import("./app-runtime")
|
|
1540
|
+
startApp({ basename })
|
|
1541
|
+
} catch (error) {
|
|
1542
|
+
if (isRetryableSharedFailure(error)) {
|
|
1543
|
+
console.error("[SixbSharedApp] Shared access could not be opened; retry is available.")
|
|
1544
|
+
renderSharedFallback("retryable", () => void open())
|
|
1545
|
+
} else {
|
|
1546
|
+
renderSharedFallback("unavailable")
|
|
1547
|
+
}
|
|
1548
|
+
} finally {
|
|
1549
|
+
pending = false
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
void open()
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
function isValidBootstrap(value: SharedAppBootstrap): boolean {
|
|
1557
|
+
return (
|
|
1558
|
+
typeof value.grantId === "string" &&
|
|
1559
|
+
value.basename === "/shared/" + encodeURIComponent(value.grantId) &&
|
|
1560
|
+
value.requestedPath.startsWith("/") &&
|
|
1561
|
+
(value.secret === null || typeof value.secret === "string")
|
|
1562
|
+
)
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
function canonicalizeInitialDestination(basename: string, destinationPath: string): boolean {
|
|
1566
|
+
const canonicalPath = basename + destinationPath
|
|
1567
|
+
if (
|
|
1568
|
+
window.location.pathname !== canonicalPath ||
|
|
1569
|
+
window.location.search !== "" ||
|
|
1570
|
+
window.location.hash !== ""
|
|
1571
|
+
) {
|
|
1572
|
+
try {
|
|
1573
|
+
window.history.replaceState(window.history.state, "", canonicalPath)
|
|
1574
|
+
} catch {
|
|
1575
|
+
// Preserve the authority boundary even when a browser or embedding policy denies History
|
|
1576
|
+
// mutation: a fresh document at the trusted server destination is still safe.
|
|
1577
|
+
window.location.replace(canonicalPath)
|
|
1578
|
+
return false
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
return true
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
function isRetryableSharedFailure(error: unknown): boolean {
|
|
1585
|
+
if (error instanceof TypeError) return true
|
|
1586
|
+
return (
|
|
1587
|
+
isSixbApiError(error) &&
|
|
1588
|
+
(error.status === 408 || error.status === 429 || error.status >= 500)
|
|
1589
|
+
)
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
function renderSharedFallback(
|
|
1593
|
+
state: "loading" | "retryable" | "unavailable",
|
|
1594
|
+
retry?: () => void
|
|
1595
|
+
): void {
|
|
1596
|
+
const root = document.getElementById("root")
|
|
1597
|
+
if (!root) return
|
|
1598
|
+
|
|
1599
|
+
const main = document.createElement("main")
|
|
1600
|
+
main.setAttribute("role", state === "loading" ? "status" : "alert")
|
|
1601
|
+
main.style.cssText =
|
|
1602
|
+
"min-height:100dvh;display:flex;flex-direction:column;align-items:center;" +
|
|
1603
|
+
"justify-content:center;gap:.75rem;padding:2rem;text-align:center;" +
|
|
1604
|
+
"font-family:system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"
|
|
1605
|
+
|
|
1606
|
+
const messages = browserAppMessages().shared
|
|
1607
|
+
const title = document.createElement("h1")
|
|
1608
|
+
title.style.cssText = "margin:0;font-size:1.5rem"
|
|
1609
|
+
title.textContent =
|
|
1610
|
+
state === "loading"
|
|
1611
|
+
? messages.opening
|
|
1612
|
+
: state === "retryable"
|
|
1613
|
+
? messages.retryableTitle
|
|
1614
|
+
: messages.unavailableTitle
|
|
1615
|
+
const detail = document.createElement("p")
|
|
1616
|
+
detail.style.cssText = "margin:0;max-width:32rem"
|
|
1617
|
+
detail.textContent =
|
|
1618
|
+
state === "loading"
|
|
1619
|
+
? messages.verifying
|
|
1620
|
+
: state === "retryable"
|
|
1621
|
+
? messages.retryableDetail
|
|
1622
|
+
: messages.unavailableDetail
|
|
1623
|
+
main.append(title, detail)
|
|
1624
|
+
|
|
1625
|
+
if (retry) {
|
|
1626
|
+
const button = document.createElement("button")
|
|
1627
|
+
button.type = "button"
|
|
1628
|
+
button.textContent = messages.tryAgain
|
|
1629
|
+
button.style.cssText =
|
|
1630
|
+
"margin-top:.25rem;padding:.625rem 1rem;border:1px solid currentColor;" +
|
|
1631
|
+
"border-radius:.375rem;background:transparent;color:inherit;cursor:pointer;font:inherit"
|
|
1632
|
+
button.addEventListener("click", retry, { once: true })
|
|
1633
|
+
main.append(button)
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
root.replaceChildren(main)
|
|
1637
|
+
}
|
|
1638
|
+
`;
|
|
1639
|
+
const sharedMainPath = join4(generatedDir, "shared-main.tsx");
|
|
1640
|
+
await writeFileIfChanged(sharedMainPath, sharedMainContent);
|
|
1641
|
+
const metadataHead = renderMetadataHead(metadata);
|
|
1642
|
+
const htmlContent = `<!DOCTYPE html>
|
|
1643
|
+
<html lang="en">
|
|
1644
|
+
<head>
|
|
1645
|
+
<meta charset="UTF-8" />
|
|
1646
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
|
1647
|
+
${metadataHead}
|
|
1648
|
+
${runtimeConfigScript}
|
|
1649
|
+
<style>
|
|
1650
|
+
* {
|
|
1651
|
+
box-sizing: border-box;
|
|
1652
|
+
}
|
|
1653
|
+
html,
|
|
1654
|
+
body,
|
|
1655
|
+
#root {
|
|
1656
|
+
margin: 0;
|
|
1657
|
+
min-height: 100%;
|
|
1658
|
+
}
|
|
1659
|
+
body,
|
|
1660
|
+
#root {
|
|
1661
|
+
min-height: 100vh;
|
|
1662
|
+
min-height: 100dvh;
|
|
1663
|
+
}
|
|
1664
|
+
@media (display-mode: standalone) {
|
|
1665
|
+
html,
|
|
1666
|
+
body {
|
|
1667
|
+
overscroll-behavior: none;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
</style>
|
|
1671
|
+
</head>
|
|
1672
|
+
<body>
|
|
1673
|
+
<div id="root"></div>
|
|
1674
|
+
<script type="module" src="./main.tsx"></script>
|
|
1675
|
+
</body>
|
|
1676
|
+
</html>
|
|
1677
|
+
`;
|
|
1678
|
+
const htmlPath = join4(generatedDir, "index.html");
|
|
1679
|
+
await writeFileIfChanged(htmlPath, htmlContent);
|
|
1680
|
+
const sharedRuntimeConfigScript = options.apiBaseUrl ? renderCustomAppRuntimeScript({
|
|
1681
|
+
api: { baseUrl: options.apiBaseUrl },
|
|
1682
|
+
auth: { enabled: false }
|
|
1683
|
+
}) : "";
|
|
1684
|
+
const sharedHtmlContent = `<!DOCTYPE html>
|
|
1685
|
+
<html lang="en">
|
|
1686
|
+
<head>
|
|
1687
|
+
<meta charset="UTF-8" />
|
|
1688
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
|
1689
|
+
<meta name="robots" content="noindex, nofollow, noarchive" />
|
|
1690
|
+
<meta name="referrer" content="no-referrer" />
|
|
1691
|
+
${renderSharedMetadataHead(metadata)}
|
|
1692
|
+
${sharedRuntimeConfigScript}
|
|
1693
|
+
<style>
|
|
1694
|
+
* { box-sizing: border-box; }
|
|
1695
|
+
html, body, #root { margin: 0; min-height: 100%; }
|
|
1696
|
+
body, #root { min-height: 100vh; min-height: 100dvh; }
|
|
1697
|
+
</style>
|
|
1698
|
+
</head>
|
|
1699
|
+
<body>
|
|
1700
|
+
<div id="root"></div>
|
|
1701
|
+
<script>
|
|
1702
|
+
function renderUnavailable() {
|
|
1703
|
+
const root = document.getElementById("root")
|
|
1704
|
+
if (!root) return
|
|
1705
|
+
const main = document.createElement("main")
|
|
1706
|
+
main.setAttribute("role", "alert")
|
|
1707
|
+
main.style.cssText =
|
|
1708
|
+
"min-height:100dvh;display:grid;place-items:center;padding:2rem;text-align:center;" +
|
|
1709
|
+
"font-family:system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"
|
|
1710
|
+
const message = document.createElement("p")
|
|
1711
|
+
// Inline and dependency-free: the translations travel with the page.
|
|
1712
|
+
const translations = ${JSON.stringify(sharedUnavailableTranslations())}
|
|
1713
|
+
const language = (navigator.languages || [navigator.language])
|
|
1714
|
+
.map((tag) => String(tag).split("-")[0].toLowerCase())
|
|
1715
|
+
.find((tag) => tag in translations)
|
|
1716
|
+
document.documentElement.lang = language || "en"
|
|
1717
|
+
message.textContent = translations[language || "en"]
|
|
1718
|
+
main.append(message)
|
|
1719
|
+
root.replaceChildren(main)
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
function consumeBootstrap() {
|
|
1723
|
+
const rawFragment = window.location.hash.startsWith("#")
|
|
1724
|
+
? window.location.hash.slice(1)
|
|
1725
|
+
: window.location.hash
|
|
1726
|
+
// Only the canonical 32-byte bearer belongs to the transport. Ordinary page anchors must
|
|
1727
|
+
// remain intact when an established shared session is reloaded.
|
|
1728
|
+
const secret = /^[A-Za-z0-9_-]{43}$/.test(rawFragment) ? rawFragment : null
|
|
1729
|
+
if (secret !== null) {
|
|
1730
|
+
try {
|
|
1731
|
+
window.history.replaceState(
|
|
1732
|
+
window.history.state,
|
|
1733
|
+
"",
|
|
1734
|
+
window.location.pathname + window.location.search
|
|
1735
|
+
)
|
|
1736
|
+
} catch {
|
|
1737
|
+
return null
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
const match = /^\\/shared\\/([^/]+)(\\/.*)?$/.exec(window.location.pathname)
|
|
1742
|
+
if (!match) return null
|
|
1743
|
+
let grantId
|
|
1744
|
+
try {
|
|
1745
|
+
grantId = decodeURIComponent(match[1])
|
|
1746
|
+
} catch {
|
|
1747
|
+
return null
|
|
1748
|
+
}
|
|
1749
|
+
if (encodeURIComponent(grantId) !== match[1]) return null
|
|
1750
|
+
return {
|
|
1751
|
+
basename: "/shared/" + match[1],
|
|
1752
|
+
grantId,
|
|
1753
|
+
requestedPath: match[2] ?? "/",
|
|
1754
|
+
secret,
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
async function bootstrapSharedApp() {
|
|
1759
|
+
const bootstrap = consumeBootstrap()
|
|
1760
|
+
if (!bootstrap) {
|
|
1761
|
+
renderUnavailable()
|
|
1762
|
+
return
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
try {
|
|
1766
|
+
const { startSharedApp } = await import("./shared-main.tsx")
|
|
1767
|
+
startSharedApp(bootstrap)
|
|
1768
|
+
} catch {
|
|
1769
|
+
console.error("[SixbSharedApp] Shared application bootstrap failed.")
|
|
1770
|
+
renderUnavailable()
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
void bootstrapSharedApp()
|
|
1775
|
+
</script>
|
|
1776
|
+
</body>
|
|
1777
|
+
</html>
|
|
1778
|
+
`;
|
|
1779
|
+
const sharedHtmlPath = join4(generatedDir, "shared-index.html");
|
|
1780
|
+
await writeFileIfChanged(sharedHtmlPath, sharedHtmlContent);
|
|
1781
|
+
return {
|
|
1782
|
+
htmlPath,
|
|
1783
|
+
mainPath,
|
|
1784
|
+
manifestPath,
|
|
1785
|
+
runtimePath,
|
|
1786
|
+
sharedHtmlPath,
|
|
1787
|
+
sharedMainPath
|
|
1788
|
+
};
|
|
1789
|
+
}
|
|
1790
|
+
function renderSharedMetadataHead(metadata) {
|
|
1791
|
+
return [
|
|
1792
|
+
` <title>${escapeHtmlText(metadata.title)}</title>`,
|
|
1793
|
+
...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
|
|
1794
|
+
` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`
|
|
1795
|
+
].join(`
|
|
1796
|
+
`);
|
|
1797
|
+
}
|
|
1798
|
+
function renderMetadataHead(metadata) {
|
|
1799
|
+
const tags = [
|
|
1800
|
+
` <title>${escapeHtmlText(metadata.title)}</title>`,
|
|
1801
|
+
...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
|
|
1802
|
+
` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
|
|
1803
|
+
' <link rel="manifest" href="/app.webmanifest" />',
|
|
1804
|
+
...metadata.favicon ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`] : [],
|
|
1805
|
+
...metadata.appleTouchIcon ? [` <link rel="apple-touch-icon" href="${metadata.appleTouchIcon}" />`] : []
|
|
1806
|
+
];
|
|
1807
|
+
return tags.join(`
|
|
1808
|
+
`);
|
|
1809
|
+
}
|
|
1810
|
+
function renderAuthMetadataHead(metadata) {
|
|
1811
|
+
const tags = [
|
|
1812
|
+
` <title>${escapeHtmlText(metadata.title)}</title>`,
|
|
1813
|
+
...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
|
|
1814
|
+
` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
|
|
1815
|
+
...metadata.favicon && /^(?:https?:|data:)/.test(metadata.favicon) ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`] : []
|
|
1816
|
+
];
|
|
1817
|
+
return tags.join(`
|
|
1818
|
+
`);
|
|
1819
|
+
}
|
|
1820
|
+
function escapeHtmlText(value) {
|
|
1821
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
1822
|
+
}
|
|
1823
|
+
function escapeHtmlAttribute(value) {
|
|
1824
|
+
return escapeHtmlText(value).replaceAll('"', """).replaceAll("'", "'");
|
|
1825
|
+
}
|
|
1826
|
+
async function writeFileIfChanged(path, content) {
|
|
1827
|
+
try {
|
|
1828
|
+
if (await readFile3(path, "utf-8") === content) {
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
} catch (error) {
|
|
1832
|
+
if (!isFileNotFoundError(error)) {
|
|
1833
|
+
throw error;
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
await writeFile2(path, content, "utf-8");
|
|
1837
|
+
}
|
|
1838
|
+
function isFileNotFoundError(error) {
|
|
1839
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
1840
|
+
}
|
|
1841
|
+
function relativeTo(from, to) {
|
|
1842
|
+
let rel = relative2(from, to);
|
|
1843
|
+
if (!rel.startsWith("."))
|
|
1844
|
+
rel = `./${rel}`;
|
|
1845
|
+
return rel;
|
|
1846
|
+
}
|
|
1847
|
+
async function fileExists2(path) {
|
|
1848
|
+
try {
|
|
1849
|
+
await access(path);
|
|
1850
|
+
return true;
|
|
1851
|
+
} catch {
|
|
1852
|
+
return false;
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
// src/dev-reload.ts
|
|
1857
|
+
function devReloadResponse(request) {
|
|
1858
|
+
const generation = process.env.SIXB_DEV_GENERATION;
|
|
1859
|
+
const headers = new Headers({
|
|
1860
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
1861
|
+
"cache-control": "no-store"
|
|
1862
|
+
});
|
|
1863
|
+
if (generation && process.env.SIXB_DEV_READY === "1") {
|
|
1864
|
+
headers.set("x-sixb-dev-generation", generation);
|
|
1865
|
+
}
|
|
1866
|
+
if (request.method === "HEAD")
|
|
1867
|
+
return new Response(null, { headers });
|
|
1868
|
+
const script = generation ? `(() => {
|
|
1869
|
+
if (window.__sixbDevReload) return;
|
|
1870
|
+
window.__sixbDevReload = true;
|
|
1871
|
+
const generation = ${JSON.stringify(generation).replaceAll("<", "\\u003c")};
|
|
1872
|
+
let timer;
|
|
1873
|
+
let checking = false;
|
|
1874
|
+
let finished = false;
|
|
1875
|
+
let failures = 0;
|
|
1876
|
+
const hidden = () => document.visibilityState === "hidden";
|
|
1877
|
+
function schedule(delay) {
|
|
1878
|
+
clearTimeout(timer);
|
|
1879
|
+
timer = setTimeout(poll, delay);
|
|
1880
|
+
}
|
|
1881
|
+
async function poll() {
|
|
1882
|
+
if (checking || finished) return;
|
|
1883
|
+
if (hidden()) { schedule(15000); return; }
|
|
1884
|
+
checking = true;
|
|
1885
|
+
try {
|
|
1886
|
+
const response = await fetch("/__sixb/dev-reload.js", {
|
|
1887
|
+
method: "HEAD", cache: "no-store", signal: AbortSignal.timeout(3000)
|
|
1888
|
+
});
|
|
1889
|
+
const next = response.headers.get("x-sixb-dev-generation");
|
|
1890
|
+
if (response.ok && next && next !== generation) {
|
|
1891
|
+
finished = true;
|
|
1892
|
+
document.removeEventListener("visibilitychange", visible);
|
|
1893
|
+
location.reload();
|
|
1894
|
+
return;
|
|
1895
|
+
}
|
|
1896
|
+
failures = response.ok && next ? 0 : Math.min(failures + 1, 4);
|
|
1897
|
+
} catch { failures = Math.min(failures + 1, 4); }
|
|
1898
|
+
finally { checking = false; }
|
|
1899
|
+
schedule(Math.min(1000 * 2 ** failures, 10000));
|
|
1900
|
+
}
|
|
1901
|
+
function visible() {
|
|
1902
|
+
if (!hidden()) { clearTimeout(timer); void poll(); }
|
|
1903
|
+
}
|
|
1904
|
+
document.addEventListener("visibilitychange", visible);
|
|
1905
|
+
void poll();
|
|
1906
|
+
})();` : "";
|
|
1907
|
+
return new Response(script, { headers });
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
// src/styles.ts
|
|
1911
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
1912
|
+
import { join as join6 } from "path";
|
|
1913
|
+
|
|
1914
|
+
// src/tailwind.ts
|
|
1915
|
+
import { mkdir as mkdir3 } from "fs/promises";
|
|
1916
|
+
import { dirname as dirname2, join as join5 } from "path";
|
|
1917
|
+
function resolveTailwindCliEntry(resolveFrom) {
|
|
1918
|
+
try {
|
|
1919
|
+
const packageJsonPath = Bun.resolveSync("@tailwindcss/cli/package.json", resolveFrom);
|
|
1920
|
+
return join5(dirname2(packageJsonPath), "dist", "index.mjs");
|
|
1921
|
+
} catch {
|
|
1922
|
+
return null;
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
function createTailwindCssCompiler(options) {
|
|
1926
|
+
const cwd = options.cwd ?? dirname2(options.inputPath);
|
|
1927
|
+
const resolveFrom = options.resolveFrom ?? cwd;
|
|
1928
|
+
const label = options.label ?? "[SixbTailwind]";
|
|
1929
|
+
const debounceMs = options.debounceMs ?? 50;
|
|
1930
|
+
const timeoutMs = options.timeoutMs ?? 60000;
|
|
1931
|
+
const onError = options.onError ?? ((error) => console.error(`${label} ${error.message}`));
|
|
1932
|
+
let chain = Promise.resolve();
|
|
1933
|
+
let timer = null;
|
|
1934
|
+
let stopped = false;
|
|
1935
|
+
let activeProcess = null;
|
|
1936
|
+
async function runCompile() {
|
|
1937
|
+
if (stopped)
|
|
1938
|
+
return;
|
|
1939
|
+
const cliEntry = resolveTailwindCliEntry(resolveFrom);
|
|
1940
|
+
if (!cliEntry) {
|
|
1941
|
+
throw new Error(`${label} Tailwind CSS build requires '@tailwindcss/cli'. Install it with: bun add tailwindcss @tailwindcss/cli`);
|
|
1942
|
+
}
|
|
1943
|
+
await mkdir3(dirname2(options.outputPath), { recursive: true });
|
|
1944
|
+
if (stopped)
|
|
1945
|
+
return;
|
|
1946
|
+
const args = [process.execPath, cliEntry, "-i", options.inputPath, "-o", options.outputPath];
|
|
1947
|
+
if (options.minify) {
|
|
1948
|
+
args.push("--minify");
|
|
1949
|
+
}
|
|
1950
|
+
const proc = Bun.spawn(args, {
|
|
1951
|
+
cwd,
|
|
1952
|
+
stdout: "ignore",
|
|
1953
|
+
stderr: "pipe"
|
|
1954
|
+
});
|
|
1955
|
+
activeProcess = proc;
|
|
1956
|
+
const stderr = new Response(proc.stderr).text().catch(() => "");
|
|
1957
|
+
let timeout;
|
|
1958
|
+
const timedOut = new Promise((resolve) => {
|
|
1959
|
+
timeout = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
1960
|
+
});
|
|
1961
|
+
try {
|
|
1962
|
+
const outcome = await Promise.race([proc.exited, timedOut]);
|
|
1963
|
+
if (stopped)
|
|
1964
|
+
return;
|
|
1965
|
+
if (outcome === "timeout") {
|
|
1966
|
+
proc.kill("SIGKILL");
|
|
1967
|
+
await proc.exited;
|
|
1968
|
+
throw new Error(`${label} Tailwind CSS build did not finish within ${timeoutMs}ms and was killed. ` + `Check ${options.inputPath} and the sources Tailwind scans from ${cwd}.`);
|
|
1969
|
+
}
|
|
1970
|
+
if (outcome !== 0) {
|
|
1971
|
+
throw new Error(`${label} Tailwind CSS build failed: ${(await stderr).trim()}`);
|
|
1972
|
+
}
|
|
1973
|
+
} finally {
|
|
1974
|
+
clearTimeout(timeout);
|
|
1975
|
+
activeProcess = null;
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
function compile() {
|
|
1979
|
+
stopped = false;
|
|
1980
|
+
const build = chain.then(() => runCompile());
|
|
1981
|
+
chain = build.then(() => {}, () => {});
|
|
1982
|
+
return build;
|
|
1983
|
+
}
|
|
1984
|
+
return {
|
|
1985
|
+
compile,
|
|
1986
|
+
schedule() {
|
|
1987
|
+
if (stopped)
|
|
1988
|
+
return;
|
|
1989
|
+
if (timer) {
|
|
1990
|
+
clearTimeout(timer);
|
|
1991
|
+
}
|
|
1992
|
+
timer = setTimeout(() => {
|
|
1993
|
+
timer = null;
|
|
1994
|
+
compile().catch((error) => {
|
|
1995
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
1996
|
+
});
|
|
1997
|
+
}, debounceMs);
|
|
1998
|
+
},
|
|
1999
|
+
async stop() {
|
|
2000
|
+
stopped = true;
|
|
2001
|
+
if (timer) {
|
|
2002
|
+
clearTimeout(timer);
|
|
2003
|
+
timer = null;
|
|
2004
|
+
}
|
|
2005
|
+
activeProcess?.kill("SIGKILL");
|
|
2006
|
+
await chain;
|
|
2007
|
+
}
|
|
2008
|
+
};
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
// src/styles.ts
|
|
2012
|
+
async function resolveCustomAppStylesheet(input) {
|
|
2013
|
+
const sourcePath = join6(input.appDir, "globals.css");
|
|
2014
|
+
let css;
|
|
2015
|
+
try {
|
|
2016
|
+
css = await readFile4(sourcePath, "utf-8");
|
|
2017
|
+
} catch {
|
|
2018
|
+
return { kind: "none" };
|
|
2019
|
+
}
|
|
2020
|
+
if (!usesTailwind(css)) {
|
|
2021
|
+
return { kind: "static", path: sourcePath };
|
|
2022
|
+
}
|
|
2023
|
+
if (!resolveTailwindCliEntry(input.rootDir)) {
|
|
2024
|
+
throw new Error("[SixbCustomApp] app/globals.css uses Tailwind features but '@tailwindcss/cli' is not installed. Install it with: bun add tailwindcss @tailwindcss/cli");
|
|
2025
|
+
}
|
|
2026
|
+
return {
|
|
2027
|
+
kind: "tailwind",
|
|
2028
|
+
sourcePath,
|
|
2029
|
+
outputPath: join6(input.generatedDir, "app.css")
|
|
2030
|
+
};
|
|
2031
|
+
}
|
|
2032
|
+
var TAILWIND_AT_RULES = /@(?:tailwind|source|theme|plugin|config|utility|custom-variant|variant|apply)\b/;
|
|
2033
|
+
function usesTailwind(css) {
|
|
2034
|
+
const stripped = css.replace(/\/\*[\s\S]*?\*\//g, "");
|
|
2035
|
+
if (TAILWIND_AT_RULES.test(stripped)) {
|
|
2036
|
+
return true;
|
|
2037
|
+
}
|
|
2038
|
+
for (const match of stripped.matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)) {
|
|
2039
|
+
const specifier = match[1];
|
|
2040
|
+
if (!specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.startsWith("#") && !/^(?:https?:|data:)/.test(specifier)) {
|
|
2041
|
+
return true;
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
return false;
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
// src/createCustomApp.ts
|
|
2048
|
+
var packageRoot = resolve3(import.meta.dir, "..");
|
|
2049
|
+
var builtInAgentRoutePaths = ["/agents", "/agents/new/:agentId", "/agents/:threadId"];
|
|
2050
|
+
var shellSourcePath = join7(packageRoot, "src", "shell");
|
|
2051
|
+
var builtInPageModule = "@sixb/app/pages";
|
|
2052
|
+
var builtInPageSourcePath = join7(packageRoot, "src", "pages");
|
|
2053
|
+
var builtInPageStylesheetPath = join7(packageRoot, "src", "pages", "canvas.css");
|
|
2054
|
+
var agentStylesheetPath = join7(packageRoot, "src", "agent", "agent.css");
|
|
2055
|
+
var customAppManifestRoute = "/app.webmanifest";
|
|
2056
|
+
var internalAppShellRoute = "/__sixb/generated/app-shell";
|
|
2057
|
+
var frameworkAssetsRoute = "/__sixb/assets";
|
|
2058
|
+
var frameworkAssetsDir = join7(packageRoot, "assets");
|
|
2059
|
+
var internalSharedAppShellRoute = "/__sixb/generated/shared-app-shell";
|
|
2060
|
+
async function createCustomApp(options) {
|
|
2061
|
+
const rootDir = resolve3(options.rootDir);
|
|
2062
|
+
const appDir = options.appDir ? resolve3(rootDir, options.appDir) : resolve3(rootDir, "app");
|
|
2063
|
+
const generatedDir = resolve3(rootDir, options.generatedDir ?? join7(".sixb", "generated"));
|
|
2064
|
+
const publicDir = options.publicDir ? resolve3(rootDir, options.publicDir) : resolve3(appDir, "public");
|
|
2065
|
+
const apiBaseUrl = options.apiBaseUrl;
|
|
2066
|
+
const authEnabled = options.authEnabled ?? true;
|
|
2067
|
+
const builtInPagesEnabled = options.builtInPages ?? true;
|
|
2068
|
+
async function scanRoutes() {
|
|
2069
|
+
return [...(await scanAppRoutes(appDir)).pages];
|
|
2070
|
+
}
|
|
2071
|
+
function servesApp(routes) {
|
|
2072
|
+
return routes.length > 0 || builtInPagesEnabled;
|
|
2073
|
+
}
|
|
2074
|
+
let tailwindCompiler = null;
|
|
2075
|
+
let tailwindCompilerKey = null;
|
|
2076
|
+
let authTailwindCompiler = null;
|
|
2077
|
+
let frameworkCssCompiler = null;
|
|
2078
|
+
async function prepareStylesheet(stylesheet) {
|
|
2079
|
+
stylesheet ??= await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
|
|
2080
|
+
if (stylesheet.kind !== "tailwind") {
|
|
2081
|
+
return stylesheet;
|
|
2082
|
+
}
|
|
2083
|
+
await compileAppTailwindStylesheet(stylesheet.sourcePath, stylesheet.outputPath);
|
|
2084
|
+
return stylesheet;
|
|
2085
|
+
}
|
|
2086
|
+
async function compileAppTailwindStylesheet(inputPath, outputPath) {
|
|
2087
|
+
const key = `${inputPath}\x00${outputPath}`;
|
|
2088
|
+
if (tailwindCompilerKey !== key) {
|
|
2089
|
+
await tailwindCompiler?.stop();
|
|
2090
|
+
tailwindCompiler = createTailwindCssCompiler({
|
|
2091
|
+
inputPath,
|
|
2092
|
+
outputPath,
|
|
2093
|
+
cwd: appDir,
|
|
2094
|
+
resolveFrom: rootDir,
|
|
2095
|
+
label: "[SixbCustomApp]"
|
|
2096
|
+
});
|
|
2097
|
+
tailwindCompilerKey = key;
|
|
2098
|
+
}
|
|
2099
|
+
const compiler = tailwindCompiler;
|
|
2100
|
+
if (!compiler) {
|
|
2101
|
+
throw new Error("[SixbCustomApp] Tailwind CSS compiler was not initialized");
|
|
2102
|
+
}
|
|
2103
|
+
await compiler.compile();
|
|
2104
|
+
}
|
|
2105
|
+
async function prepareCombinedStylesheet(stylesheet) {
|
|
2106
|
+
const inputPath = join7(generatedDir, "app.input.css");
|
|
2107
|
+
const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot);
|
|
2108
|
+
await writeFileIfChanged2(inputPath, [
|
|
2109
|
+
`@import ${JSON.stringify(uiGlobalsPath)};`,
|
|
2110
|
+
`@source ${JSON.stringify(shellSourcePath)};`,
|
|
2111
|
+
`@source ${JSON.stringify(builtInPageSourcePath)};`,
|
|
2112
|
+
`@import ${JSON.stringify(builtInPageStylesheetPath)};`,
|
|
2113
|
+
`@import ${JSON.stringify(stylesheet.sourcePath)};`,
|
|
2114
|
+
`@import ${JSON.stringify(agentStylesheetPath)};`,
|
|
2115
|
+
""
|
|
2116
|
+
].join(`
|
|
2117
|
+
`));
|
|
2118
|
+
await compileAppTailwindStylesheet(inputPath, stylesheet.outputPath);
|
|
2119
|
+
return stylesheet.outputPath;
|
|
2120
|
+
}
|
|
2121
|
+
async function prepareStylesheets(builtInRoutes) {
|
|
2122
|
+
const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
|
|
2123
|
+
if (stylesheet.kind === "tailwind" && builtInRoutes.length > 0) {
|
|
2124
|
+
return {
|
|
2125
|
+
stylesheetPath: await prepareCombinedStylesheet(stylesheet),
|
|
2126
|
+
frameworkStylesheetPaths: []
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
const preparedStylesheet = await prepareStylesheet(stylesheet);
|
|
2130
|
+
const frameworkStylesheetPath = await prepareFrameworkStylesheet(builtInRoutes);
|
|
2131
|
+
return {
|
|
2132
|
+
frameworkStylesheetPaths: frameworkStylesheetPath ? [frameworkStylesheetPath] : [],
|
|
2133
|
+
stylesheetPath: preparedStylesheet.kind === "none" ? null : preparedStylesheet.kind === "static" ? preparedStylesheet.path : preparedStylesheet.outputPath
|
|
2134
|
+
};
|
|
2135
|
+
}
|
|
2136
|
+
async function prepareFrameworkStylesheet(builtInRoutes) {
|
|
2137
|
+
if (builtInRoutes.length === 0) {
|
|
2138
|
+
return null;
|
|
2139
|
+
}
|
|
2140
|
+
const inputPath = join7(generatedDir, "framework.input.css");
|
|
2141
|
+
const outputPath = join7(generatedDir, "framework.css");
|
|
2142
|
+
const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot);
|
|
2143
|
+
await writeFileIfChanged2(inputPath, [
|
|
2144
|
+
`@import ${JSON.stringify(uiGlobalsPath)};`,
|
|
2145
|
+
`@source ${JSON.stringify(shellSourcePath)};`,
|
|
2146
|
+
`@source ${JSON.stringify(builtInPageSourcePath)};`,
|
|
2147
|
+
`@import ${JSON.stringify(builtInPageStylesheetPath)};`,
|
|
2148
|
+
`@import ${JSON.stringify(agentStylesheetPath)};`,
|
|
2149
|
+
""
|
|
2150
|
+
].join(`
|
|
2151
|
+
`));
|
|
2152
|
+
frameworkCssCompiler ??= createTailwindCssCompiler({
|
|
2153
|
+
inputPath,
|
|
2154
|
+
outputPath,
|
|
2155
|
+
cwd: packageRoot,
|
|
2156
|
+
resolveFrom: packageRoot,
|
|
2157
|
+
label: "[SixbCustomApp]"
|
|
2158
|
+
});
|
|
2159
|
+
await frameworkCssCompiler.compile();
|
|
2160
|
+
return outputPath;
|
|
2161
|
+
}
|
|
2162
|
+
async function prepareGeneratedApp() {
|
|
2163
|
+
assertAppPackagesInstalled(rootDir);
|
|
2164
|
+
const discovery = await scanAppRoutes(appDir);
|
|
2165
|
+
const routes = [...discovery.pages];
|
|
2166
|
+
if (!servesApp(routes)) {
|
|
2167
|
+
throw new Error(`[SixbCustomApp] No app routes found in ${appDir}`);
|
|
2168
|
+
}
|
|
2169
|
+
const builtInRoutes = builtInPagesEnabled ? builtInRoutesFor(routes) : [];
|
|
2170
|
+
const stylesheets = await prepareStylesheets(builtInRoutes);
|
|
2171
|
+
await generateRouteManifest(routes, generatedDir, {
|
|
2172
|
+
builtInRoutes,
|
|
2173
|
+
layouts: discovery.layouts
|
|
2174
|
+
});
|
|
2175
|
+
const entry = await generateAppEntry(rootDir, generatedDir, {
|
|
2176
|
+
apiBaseUrl,
|
|
2177
|
+
authEnabled,
|
|
2178
|
+
appDir,
|
|
2179
|
+
publicDir,
|
|
2180
|
+
frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
|
|
2181
|
+
stylesheetPath: stylesheets.stylesheetPath,
|
|
2182
|
+
sections: builtInPagesEnabled,
|
|
2183
|
+
projectPages: routes.length > 0
|
|
2184
|
+
});
|
|
2185
|
+
return { ...entry, routes };
|
|
2186
|
+
}
|
|
2187
|
+
async function prepareAuthExperience(authOptions = {}) {
|
|
2188
|
+
const outdir = authOptions.outdir ? resolve3(rootDir, authOptions.outdir) : join7(generatedDir, "auth");
|
|
2189
|
+
if (!await pathExists(join7(appDir, "auth.tsx"))) {
|
|
2190
|
+
await rm2(outdir, { recursive: true, force: true });
|
|
2191
|
+
return null;
|
|
2192
|
+
}
|
|
2193
|
+
const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
|
|
2194
|
+
let stylesheetPath;
|
|
2195
|
+
if (stylesheet.kind === "none") {
|
|
2196
|
+
stylesheetPath = null;
|
|
2197
|
+
} else if (stylesheet.kind === "static") {
|
|
2198
|
+
stylesheetPath = stylesheet.path;
|
|
2199
|
+
} else {
|
|
2200
|
+
const outputPath = join7(generatedDir, "auth.css");
|
|
2201
|
+
authTailwindCompiler ??= createTailwindCssCompiler({
|
|
2202
|
+
inputPath: stylesheet.sourcePath,
|
|
2203
|
+
outputPath,
|
|
2204
|
+
cwd: appDir,
|
|
2205
|
+
resolveFrom: rootDir,
|
|
2206
|
+
label: "[SixbCustomApp]"
|
|
2207
|
+
});
|
|
2208
|
+
await authTailwindCompiler.compile();
|
|
2209
|
+
stylesheetPath = outputPath;
|
|
2210
|
+
}
|
|
2211
|
+
const entry = await generateAuthExperienceEntry(rootDir, generatedDir, {
|
|
2212
|
+
appDir,
|
|
2213
|
+
publicDir,
|
|
2214
|
+
stylesheetPath
|
|
2215
|
+
});
|
|
2216
|
+
if (!entry) {
|
|
2217
|
+
return null;
|
|
2218
|
+
}
|
|
2219
|
+
const result = await buildAuthExperience({
|
|
2220
|
+
entryPath: entry.htmlPath,
|
|
2221
|
+
scriptEntryPath: entry.mainPath,
|
|
2222
|
+
outdir
|
|
2223
|
+
});
|
|
2224
|
+
if (!result.success) {
|
|
2225
|
+
throw new Error(`[SixbCustomApp] Failed to build the auth experience: ${(result.logs ?? []).join(`
|
|
2226
|
+
`)}`);
|
|
2227
|
+
}
|
|
2228
|
+
return { outdir: result.outdir };
|
|
2229
|
+
}
|
|
2230
|
+
return {
|
|
2231
|
+
async scanRoutes() {
|
|
2232
|
+
return await scanRoutes();
|
|
2233
|
+
},
|
|
2234
|
+
async prepareAuthExperience(options) {
|
|
2235
|
+
return await prepareAuthExperience(options);
|
|
2236
|
+
},
|
|
2237
|
+
async dev(devOptions = {}) {
|
|
2238
|
+
const publicEnv = collectPublicEnv();
|
|
2239
|
+
const withRuntime = (html) => injectRuntimeConfig(html, { apiBaseUrl, authEnabled, publicEnv });
|
|
2240
|
+
const host = devOptions.host ?? "0.0.0.0";
|
|
2241
|
+
const port = devOptions.port ?? 3000;
|
|
2242
|
+
const { htmlPath, manifestPath, sharedHtmlPath, sharedMainPath } = await prepareGeneratedApp();
|
|
2243
|
+
await prepareAuthExperience();
|
|
2244
|
+
let htmlImportVersion = 0;
|
|
2245
|
+
let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion);
|
|
2246
|
+
const sharedDevRoot = join7(generatedDir, "shared-dev");
|
|
2247
|
+
await rm2(sharedDevRoot, { recursive: true, force: true });
|
|
2248
|
+
let sharedBuildVersion = 0;
|
|
2249
|
+
let sharedSourceVersion = 0;
|
|
2250
|
+
let sharedBuiltSourceVersion = -1;
|
|
2251
|
+
let sharedBuild = null;
|
|
2252
|
+
let sharedBuildPromise = null;
|
|
2253
|
+
let sharedAssetRoutes = {};
|
|
2254
|
+
let stopping = false;
|
|
2255
|
+
const privateAppShellRoute = `${internalAppShellRoute}-${randomBytes(18).toString("base64url")}`;
|
|
2256
|
+
const publicRoutes = await pathExists(publicDir) ? await createPublicRoutes(publicDir) : {};
|
|
2257
|
+
let internalOrigin = "";
|
|
2258
|
+
let server = null;
|
|
2259
|
+
const serveOptions = (bundle) => ({
|
|
2260
|
+
port,
|
|
2261
|
+
hostname: host,
|
|
2262
|
+
development: true,
|
|
2263
|
+
routes: {
|
|
2264
|
+
...publicRoutes,
|
|
2265
|
+
...sharedAssetRoutes,
|
|
2266
|
+
...reservedSixbRoutes(),
|
|
2267
|
+
"/__sixb/dev-reload.js": getHeadRoute(devReloadResponse),
|
|
2268
|
+
[`${frameworkAssetsRoute}/*`]: getHeadRoute((request) => frameworkAssetResponse(request, new URL(request.url).pathname)),
|
|
2269
|
+
[customAppManifestRoute]: manifestRoute(manifestPath),
|
|
2270
|
+
[privateAppShellRoute]: htmlBundleRoute(bundle),
|
|
2271
|
+
...sharedAppDevRoutes(async () => injectRuntimeConfig((await ensureSharedBuild()).html, {
|
|
2272
|
+
apiBaseUrl,
|
|
2273
|
+
authEnabled: false,
|
|
2274
|
+
publicEnv
|
|
2275
|
+
}), apiBaseUrl),
|
|
2276
|
+
"/": spaHtmlRoute(() => internalOrigin, {
|
|
2277
|
+
shellRoute: privateAppShellRoute,
|
|
2278
|
+
transformHtml: withRuntime
|
|
2279
|
+
}),
|
|
2280
|
+
"/*": spaHtmlRoute(() => internalOrigin, {
|
|
2281
|
+
shellRoute: privateAppShellRoute,
|
|
2282
|
+
transformHtml: withRuntime
|
|
2283
|
+
})
|
|
2284
|
+
}
|
|
2285
|
+
});
|
|
2286
|
+
async function ensureSharedBuild() {
|
|
2287
|
+
if (stopping) {
|
|
2288
|
+
throw new Error("[SixbCustomApp] Shared development build requested while stopping.");
|
|
2289
|
+
}
|
|
2290
|
+
if (sharedBuild && sharedBuiltSourceVersion === sharedSourceVersion) {
|
|
2291
|
+
return sharedBuild;
|
|
2292
|
+
}
|
|
2293
|
+
if (sharedBuildPromise) {
|
|
2294
|
+
await sharedBuildPromise;
|
|
2295
|
+
return await ensureSharedBuild();
|
|
2296
|
+
}
|
|
2297
|
+
const sourceVersion = sharedSourceVersion;
|
|
2298
|
+
const outdir = join7(sharedDevRoot, String(sharedBuildVersion++));
|
|
2299
|
+
const build = buildSharedAppDev({
|
|
2300
|
+
entryPath: sharedHtmlPath,
|
|
2301
|
+
outdir,
|
|
2302
|
+
scriptEntryPath: sharedMainPath
|
|
2303
|
+
}).then((result) => {
|
|
2304
|
+
sharedAssetRoutes = {
|
|
2305
|
+
...sharedAssetRoutes,
|
|
2306
|
+
...createGeneratedAssetRoutes(outdir, result.assetPaths)
|
|
2307
|
+
};
|
|
2308
|
+
sharedBuild = result;
|
|
2309
|
+
sharedBuiltSourceVersion = sourceVersion;
|
|
2310
|
+
server?.reload(serveOptions(htmlBundle));
|
|
2311
|
+
return result;
|
|
2312
|
+
}).finally(() => {
|
|
2313
|
+
sharedBuildPromise = null;
|
|
2314
|
+
});
|
|
2315
|
+
sharedBuildPromise = build;
|
|
2316
|
+
const result = await build;
|
|
2317
|
+
if (!stopping && sourceVersion !== sharedSourceVersion) {
|
|
2318
|
+
return await ensureSharedBuild();
|
|
2319
|
+
}
|
|
2320
|
+
return result;
|
|
2321
|
+
}
|
|
2322
|
+
server = Bun.serve(serveOptions(htmlBundle));
|
|
2323
|
+
internalOrigin = devServerInternalOrigin(host, server.port ?? port);
|
|
2324
|
+
let rebuildTimer = null;
|
|
2325
|
+
let rebuildChain = Promise.resolve();
|
|
2326
|
+
const enqueueRebuild = () => {
|
|
2327
|
+
rebuildChain = rebuildChain.then(async () => {
|
|
2328
|
+
const { htmlPath: nextHtmlPath } = await prepareGeneratedApp();
|
|
2329
|
+
await prepareAuthExperience();
|
|
2330
|
+
htmlImportVersion++;
|
|
2331
|
+
htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion);
|
|
2332
|
+
sharedSourceVersion++;
|
|
2333
|
+
server?.reload(serveOptions(htmlBundle));
|
|
2334
|
+
}).catch((error) => {
|
|
2335
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2336
|
+
console.error(`[SixbCustomApp] Rebuild failed: ${message}`);
|
|
2337
|
+
});
|
|
2338
|
+
};
|
|
2339
|
+
const watcher = await pathExists(appDir) ? watch(appDir, { recursive: true }, (_eventType, filename) => {
|
|
2340
|
+
if (!filename)
|
|
2341
|
+
return;
|
|
2342
|
+
if (!/\.(ts|tsx|css)$/.test(String(filename)))
|
|
2343
|
+
return;
|
|
2344
|
+
if (rebuildTimer) {
|
|
2345
|
+
clearTimeout(rebuildTimer);
|
|
2346
|
+
}
|
|
2347
|
+
rebuildTimer = setTimeout(() => {
|
|
2348
|
+
rebuildTimer = null;
|
|
2349
|
+
enqueueRebuild();
|
|
2350
|
+
}, 80);
|
|
2351
|
+
}) : null;
|
|
2352
|
+
watcher?.on("error", (error) => {
|
|
2353
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2354
|
+
console.error(`[SixbCustomApp] Stopped watching ${appDir}: ${message}. ` + "Serving the last build; restart to resume hot reload.");
|
|
2355
|
+
});
|
|
2356
|
+
const displayHost = host === "0.0.0.0" ? "localhost" : host;
|
|
2357
|
+
return {
|
|
2358
|
+
host,
|
|
2359
|
+
port,
|
|
2360
|
+
url: `http://${displayHost}:${port}`,
|
|
2361
|
+
watchesSources: watcher !== null,
|
|
2362
|
+
async stop() {
|
|
2363
|
+
stopping = true;
|
|
2364
|
+
if (rebuildTimer) {
|
|
2365
|
+
clearTimeout(rebuildTimer);
|
|
2366
|
+
rebuildTimer = null;
|
|
2367
|
+
}
|
|
2368
|
+
watcher?.close();
|
|
2369
|
+
await rebuildChain;
|
|
2370
|
+
await tailwindCompiler?.stop();
|
|
2371
|
+
await authTailwindCompiler?.stop();
|
|
2372
|
+
await frameworkCssCompiler?.stop();
|
|
2373
|
+
const activeServer = server;
|
|
2374
|
+
server = null;
|
|
2375
|
+
activeServer?.stop(true);
|
|
2376
|
+
await sharedBuildPromise?.catch(() => {});
|
|
2377
|
+
await rm2(sharedDevRoot, { recursive: true, force: true });
|
|
2378
|
+
}
|
|
2379
|
+
};
|
|
2380
|
+
},
|
|
2381
|
+
async build(buildOptions = {}) {
|
|
2382
|
+
const outdir = resolve3(rootDir, buildOptions.outdir ?? join7(".sixb", "dist", "app"));
|
|
2383
|
+
const { htmlPath, mainPath, manifestPath, sharedHtmlPath, sharedMainPath } = await prepareGeneratedApp();
|
|
2384
|
+
const result = await buildApp({
|
|
2385
|
+
entryPath: htmlPath,
|
|
2386
|
+
scriptEntryPath: mainPath,
|
|
2387
|
+
sharedEntryPath: sharedHtmlPath,
|
|
2388
|
+
sharedScriptEntryPath: sharedMainPath,
|
|
2389
|
+
manifestPath,
|
|
2390
|
+
outdir
|
|
2391
|
+
});
|
|
2392
|
+
if (result.success) {
|
|
2393
|
+
await prepareAuthExperience({ outdir: join7(outdir, "auth") });
|
|
2394
|
+
}
|
|
2395
|
+
if (result.success && await pathExists(publicDir)) {
|
|
2396
|
+
await cp(publicDir, outdir, {
|
|
2397
|
+
recursive: true,
|
|
2398
|
+
force: true,
|
|
2399
|
+
filter: (source) => {
|
|
2400
|
+
const resolvedSource = resolve3(source);
|
|
2401
|
+
return resolvedSource !== join7(publicDir, "app.webmanifest") && resolvedSource !== join7(publicDir, SHARED_APP_SHELL_FILE_NAME) && resolvedSource !== join7(publicDir, "auth");
|
|
2402
|
+
}
|
|
2403
|
+
});
|
|
2404
|
+
}
|
|
2405
|
+
return result;
|
|
2406
|
+
},
|
|
2407
|
+
async start(startOptions = {}) {
|
|
2408
|
+
const publicEnv = collectPublicEnv();
|
|
2409
|
+
const host = startOptions.host ?? "0.0.0.0";
|
|
2410
|
+
const port = startOptions.port ?? 3000;
|
|
2411
|
+
const outdir = resolve3(rootDir, startOptions.outdir ?? join7(".sixb", "dist", "app"));
|
|
2412
|
+
const indexPath = join7(outdir, "index.html");
|
|
2413
|
+
const sharedIndexPath = join7(outdir, SHARED_APP_SHELL_FILE_NAME);
|
|
2414
|
+
if (!await pathExists(indexPath)) {
|
|
2415
|
+
throw new Error(`[SixbCustomApp] No built app found in ${outdir}`);
|
|
2416
|
+
}
|
|
2417
|
+
if (!await pathExists(sharedIndexPath)) {
|
|
2418
|
+
throw new Error(`[SixbCustomApp] Built app in ${outdir} is missing ${SHARED_APP_SHELL_FILE_NAME}; rebuild required.`);
|
|
2419
|
+
}
|
|
2420
|
+
const indexHtml = injectRuntimeConfig(await Bun.file(indexPath).text(), {
|
|
2421
|
+
apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
|
|
2422
|
+
authEnabled: startOptions.authEnabled ?? authEnabled,
|
|
2423
|
+
publicEnv
|
|
2424
|
+
});
|
|
2425
|
+
const sharedIndexHtml = injectRuntimeConfig(await Bun.file(sharedIndexPath).text(), {
|
|
2426
|
+
apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
|
|
2427
|
+
authEnabled: false,
|
|
2428
|
+
publicEnv
|
|
2429
|
+
});
|
|
2430
|
+
const runtimeApiBaseUrl = startOptions.apiBaseUrl ?? apiBaseUrl;
|
|
2431
|
+
const server = Bun.serve({
|
|
2432
|
+
port,
|
|
2433
|
+
hostname: host,
|
|
2434
|
+
development: false,
|
|
2435
|
+
async fetch(req) {
|
|
2436
|
+
const url = new URL(req.url);
|
|
2437
|
+
if (isReservedSixbRoute(url.pathname)) {
|
|
2438
|
+
return notFoundResponse();
|
|
2439
|
+
}
|
|
2440
|
+
if (isFrameworkPrivateRoute(url.pathname)) {
|
|
2441
|
+
return notFoundResponse();
|
|
2442
|
+
}
|
|
2443
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
2444
|
+
return notFoundResponse();
|
|
2445
|
+
}
|
|
2446
|
+
if (url.pathname.startsWith(`${frameworkAssetsRoute}/`)) {
|
|
2447
|
+
return frameworkAssetResponse(req, url.pathname);
|
|
2448
|
+
}
|
|
2449
|
+
if (isSharedAppRoute(url.pathname)) {
|
|
2450
|
+
if (isAssetRequest(url.pathname)) {
|
|
2451
|
+
return notFoundResponse();
|
|
2452
|
+
}
|
|
2453
|
+
return sharedHtmlResponse(req, sharedIndexHtml, runtimeApiBaseUrl);
|
|
2454
|
+
}
|
|
2455
|
+
if (isSharedNamespace(url.pathname)) {
|
|
2456
|
+
return notFoundResponse();
|
|
2457
|
+
}
|
|
2458
|
+
if (url.pathname === "/" || url.pathname === "") {
|
|
2459
|
+
return htmlResponse(req, indexHtml);
|
|
2460
|
+
}
|
|
2461
|
+
const resolvedPath = resolveStaticPath(outdir, url.pathname);
|
|
2462
|
+
if (!resolvedPath) {
|
|
2463
|
+
return notFoundResponse();
|
|
2464
|
+
}
|
|
2465
|
+
const directFile = Bun.file(resolvedPath);
|
|
2466
|
+
if (await directFile.exists()) {
|
|
2467
|
+
if (resolvedPath === indexPath) {
|
|
2468
|
+
return htmlResponse(req, indexHtml);
|
|
2469
|
+
}
|
|
2470
|
+
return staticFileResponse(req, resolvedPath, staticAssetHeaders(url.pathname));
|
|
2471
|
+
}
|
|
2472
|
+
if (isAssetRequest(url.pathname)) {
|
|
2473
|
+
return notFoundResponse();
|
|
2474
|
+
}
|
|
2475
|
+
const htmlFile = Bun.file(`${resolvedPath}.html`);
|
|
2476
|
+
if (await htmlFile.exists()) {
|
|
2477
|
+
if (`${resolvedPath}.html` === indexPath) {
|
|
2478
|
+
return htmlResponse(req, indexHtml);
|
|
2479
|
+
}
|
|
2480
|
+
return fileResponse(req, htmlFile);
|
|
2481
|
+
}
|
|
2482
|
+
const nestedIndexFile = Bun.file(join7(resolvedPath, "index.html"));
|
|
2483
|
+
if (await nestedIndexFile.exists()) {
|
|
2484
|
+
return fileResponse(req, nestedIndexFile);
|
|
2485
|
+
}
|
|
2486
|
+
return htmlResponse(req, indexHtml);
|
|
2487
|
+
}
|
|
2488
|
+
});
|
|
2489
|
+
const displayHost = host === "0.0.0.0" ? "localhost" : host;
|
|
2490
|
+
return {
|
|
2491
|
+
host,
|
|
2492
|
+
port,
|
|
2493
|
+
url: `http://${displayHost}:${port}`,
|
|
2494
|
+
async stop() {
|
|
2495
|
+
server.stop(true);
|
|
2496
|
+
}
|
|
2497
|
+
};
|
|
2498
|
+
}
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
async function pathExists(path) {
|
|
2502
|
+
try {
|
|
2503
|
+
await access2(path);
|
|
2504
|
+
return true;
|
|
2505
|
+
} catch {
|
|
2506
|
+
return false;
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
var appPeerPackages = ["react", "react-dom", "react-router-dom", "@tanstack/react-query"];
|
|
2510
|
+
function assertAppPackagesInstalled(rootDir) {
|
|
2511
|
+
const missing = appPeerPackages.filter((name) => {
|
|
2512
|
+
for (let dir = rootDir;; dir = dirname3(dir)) {
|
|
2513
|
+
if (existsSync2(join7(dir, "node_modules", name, "package.json")))
|
|
2514
|
+
return false;
|
|
2515
|
+
if (dirname3(dir) === dir)
|
|
2516
|
+
return true;
|
|
2517
|
+
}
|
|
2518
|
+
});
|
|
2519
|
+
if (missing.length > 0)
|
|
2520
|
+
throw new AppPackagesMissingError(missing);
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
class AppPackagesMissingError extends Error {
|
|
2524
|
+
missing;
|
|
2525
|
+
name = "AppPackagesMissingError";
|
|
2526
|
+
constructor(missing) {
|
|
2527
|
+
super(`[SixbCustomApp] The app needs ${missing.join(", ")} in this project. Install them with: ` + `bun add ${missing.join(" ")}`);
|
|
2528
|
+
this.missing = missing;
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
function builtInRoutesFor(routes) {
|
|
2532
|
+
const projectRoutePatterns = new Set(routes.map((route) => routePatternKey(route.path)));
|
|
2533
|
+
const builtInRoutes = [
|
|
2534
|
+
...builtInAgentRoutePaths.map((path) => ({
|
|
2535
|
+
path,
|
|
2536
|
+
moduleSpecifier: builtInPageModule,
|
|
2537
|
+
exportName: "AgentsPage"
|
|
2538
|
+
})),
|
|
2539
|
+
{ path: "/", moduleSpecifier: builtInPageModule, exportName: "HomePage" },
|
|
2540
|
+
{
|
|
2541
|
+
path: "/objects/:objectTypeId/:primaryId",
|
|
2542
|
+
moduleSpecifier: builtInPageModule,
|
|
2543
|
+
exportName: "ObjectPage"
|
|
2544
|
+
},
|
|
2545
|
+
...sectionCatalog.flatMap((section) => [
|
|
2546
|
+
{
|
|
2547
|
+
path: section.path,
|
|
2548
|
+
moduleSpecifier: builtInPageModule,
|
|
2549
|
+
exportName: section.indexExportName
|
|
2550
|
+
},
|
|
2551
|
+
...section.pages.flatMap((page) => [
|
|
2552
|
+
{ path: page.path, moduleSpecifier: builtInPageModule, exportName: page.exportName },
|
|
2553
|
+
...(page.details ?? []).map((detail) => ({
|
|
2554
|
+
path: detail.path,
|
|
2555
|
+
moduleSpecifier: builtInPageModule,
|
|
2556
|
+
exportName: detail.exportName
|
|
2557
|
+
}))
|
|
2558
|
+
])
|
|
2559
|
+
])
|
|
2560
|
+
];
|
|
2561
|
+
return builtInRoutes.filter((route) => !projectRoutePatterns.has(routePatternKey(route.path)));
|
|
2562
|
+
}
|
|
2563
|
+
async function writeFileIfChanged2(path, content) {
|
|
2564
|
+
try {
|
|
2565
|
+
if (await readFile5(path, "utf-8") === content) {
|
|
2566
|
+
return;
|
|
2567
|
+
}
|
|
2568
|
+
} catch (error) {
|
|
2569
|
+
if (!isFileNotFoundError2(error)) {
|
|
2570
|
+
throw error;
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
await mkdir4(dirname3(path), { recursive: true });
|
|
2574
|
+
await writeFile3(path, content, "utf-8");
|
|
2575
|
+
}
|
|
2576
|
+
function isFileNotFoundError2(error) {
|
|
2577
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
2578
|
+
}
|
|
2579
|
+
async function frameworkAssetResponse(request, pathname) {
|
|
2580
|
+
const resolvedPath = resolveStaticPath(frameworkAssetsDir, pathname.slice(frameworkAssetsRoute.length));
|
|
2581
|
+
if (!resolvedPath || !await Bun.file(resolvedPath).exists())
|
|
2582
|
+
return notFoundResponse();
|
|
2583
|
+
return staticFileResponse(request, resolvedPath, { "cache-control": "public, max-age=86400" });
|
|
2584
|
+
}
|
|
2585
|
+
async function createPublicRoutes(publicDir) {
|
|
2586
|
+
const files = new Bun.Glob("**/*").scan({
|
|
2587
|
+
cwd: publicDir,
|
|
2588
|
+
absolute: true,
|
|
2589
|
+
onlyFiles: true
|
|
2590
|
+
});
|
|
2591
|
+
const routes = {};
|
|
2592
|
+
for await (const filePath of files) {
|
|
2593
|
+
const routePath = `/${filePath.slice(publicDir.length + 1).split("\\").join("/")}`;
|
|
2594
|
+
if (isReservedSixbRoute(routePath) || isSharedNamespace(routePath) || isFrameworkPrivateRoute(routePath) || routePath === customAppManifestRoute) {
|
|
2595
|
+
continue;
|
|
2596
|
+
}
|
|
2597
|
+
routes[routePath] = getHeadRoute((request) => filePathResponse(request, filePath));
|
|
2598
|
+
}
|
|
2599
|
+
return routes;
|
|
2600
|
+
}
|
|
2601
|
+
function createGeneratedAssetRoutes(outputRoot, assetPaths) {
|
|
2602
|
+
const routes = {};
|
|
2603
|
+
for (const assetPath of assetPaths) {
|
|
2604
|
+
const relativePath = relative3(outputRoot, assetPath);
|
|
2605
|
+
if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
|
|
2606
|
+
throw new Error(`[SixbCustomApp] Shared development asset escaped its output directory.`);
|
|
2607
|
+
}
|
|
2608
|
+
const routePath = `/${relativePath.split("\\").join("/")}`;
|
|
2609
|
+
routes[routePath] = getHeadRoute((request) => fileResponse(request, Bun.file(assetPath), { "cache-control": "no-store" }));
|
|
2610
|
+
}
|
|
2611
|
+
return routes;
|
|
2612
|
+
}
|
|
2613
|
+
function reservedSixbRoutes() {
|
|
2614
|
+
const handler = () => notFoundResponse();
|
|
2615
|
+
return {
|
|
2616
|
+
[internalAppShellRoute]: allMethodsRoute(handler),
|
|
2617
|
+
[`${internalAppShellRoute}/*`]: allMethodsRoute(handler),
|
|
2618
|
+
[internalSharedAppShellRoute]: allMethodsRoute(handler),
|
|
2619
|
+
[`${internalSharedAppShellRoute}/*`]: allMethodsRoute(handler),
|
|
2620
|
+
[`/${SHARED_APP_SHELL_FILE_NAME}`]: allMethodsRoute(handler),
|
|
2621
|
+
"/api": allMethodsRoute(handler),
|
|
2622
|
+
"/api/*": allMethodsRoute(handler),
|
|
2623
|
+
"/auth": allMethodsRoute(handler),
|
|
2624
|
+
"/auth/*": allMethodsRoute(handler),
|
|
2625
|
+
"/ws": allMethodsRoute(handler),
|
|
2626
|
+
"/ws/*": allMethodsRoute(handler),
|
|
2627
|
+
"/docs": allMethodsRoute(handler),
|
|
2628
|
+
"/docs/*": allMethodsRoute(handler)
|
|
2629
|
+
};
|
|
2630
|
+
}
|
|
2631
|
+
function sharedAppDevRoutes(html, apiBaseUrl) {
|
|
2632
|
+
const reject = () => notFoundResponse();
|
|
2633
|
+
const guardedHandler = async (request) => {
|
|
2634
|
+
const pathname = new URL(request.url).pathname;
|
|
2635
|
+
if (!isSharedAppRoute(pathname) || isAssetRequest(pathname)) {
|
|
2636
|
+
return notFoundResponse();
|
|
2637
|
+
}
|
|
2638
|
+
return sharedHtmlResponse(request, await html(), apiBaseUrl);
|
|
2639
|
+
};
|
|
2640
|
+
return {
|
|
2641
|
+
"/shared": allMethodsRoute(reject),
|
|
2642
|
+
"/shared/*": {
|
|
2643
|
+
GET: guardedHandler,
|
|
2644
|
+
HEAD: guardedHandler,
|
|
2645
|
+
POST: reject,
|
|
2646
|
+
PUT: reject,
|
|
2647
|
+
PATCH: reject,
|
|
2648
|
+
DELETE: reject,
|
|
2649
|
+
OPTIONS: reject
|
|
2650
|
+
}
|
|
2651
|
+
};
|
|
2652
|
+
}
|
|
2653
|
+
function isSharedAppRoute(pathname) {
|
|
2654
|
+
return /^\/shared\/[^/]+(?:\/.*)?$/.test(pathname);
|
|
2655
|
+
}
|
|
2656
|
+
function isSharedNamespace(pathname) {
|
|
2657
|
+
const decoded = decodeRoutePathname(pathname);
|
|
2658
|
+
return decoded === "/shared" || decoded?.startsWith("/shared/") === true;
|
|
2659
|
+
}
|
|
2660
|
+
function isFrameworkPrivateRoute(pathname) {
|
|
2661
|
+
const decoded = decodeRoutePathname(pathname)?.toLowerCase();
|
|
2662
|
+
if (!decoded)
|
|
2663
|
+
return false;
|
|
2664
|
+
const sharedShellRoute = `/${SHARED_APP_SHELL_FILE_NAME}`;
|
|
2665
|
+
return decoded === sharedShellRoute || decoded.startsWith(`${sharedShellRoute}/`) || decoded === internalAppShellRoute || decoded.startsWith(`${internalAppShellRoute}/`) || decoded === internalSharedAppShellRoute || decoded.startsWith(`${internalSharedAppShellRoute}/`);
|
|
2666
|
+
}
|
|
2667
|
+
function decodeRoutePathname(pathname) {
|
|
2668
|
+
try {
|
|
2669
|
+
return decodeURIComponent(pathname).replaceAll("\\", "/");
|
|
2670
|
+
} catch {
|
|
2671
|
+
return null;
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
function isReservedSixbRoute(pathname) {
|
|
2675
|
+
const decoded = decodeRoutePathname(pathname);
|
|
2676
|
+
if (!decoded)
|
|
2677
|
+
return false;
|
|
2678
|
+
return decoded === "/api" || decoded.startsWith("/api/") || decoded === "/auth" || decoded.startsWith("/auth/") || decoded === "/ws" || decoded.startsWith("/ws/") || decoded === "/docs" || decoded.startsWith("/docs/");
|
|
2679
|
+
}
|
|
2680
|
+
var ASSET_EXTENSIONS = new Set([
|
|
2681
|
+
"js",
|
|
2682
|
+
"mjs",
|
|
2683
|
+
"cjs",
|
|
2684
|
+
"css",
|
|
2685
|
+
"map",
|
|
2686
|
+
"json",
|
|
2687
|
+
"wasm",
|
|
2688
|
+
"ico",
|
|
2689
|
+
"png",
|
|
2690
|
+
"jpg",
|
|
2691
|
+
"jpeg",
|
|
2692
|
+
"gif",
|
|
2693
|
+
"svg",
|
|
2694
|
+
"webp",
|
|
2695
|
+
"avif",
|
|
2696
|
+
"bmp",
|
|
2697
|
+
"woff",
|
|
2698
|
+
"woff2",
|
|
2699
|
+
"ttf",
|
|
2700
|
+
"otf",
|
|
2701
|
+
"eot",
|
|
2702
|
+
"mp4",
|
|
2703
|
+
"webm",
|
|
2704
|
+
"ogg",
|
|
2705
|
+
"mp3",
|
|
2706
|
+
"wav",
|
|
2707
|
+
"txt",
|
|
2708
|
+
"xml",
|
|
2709
|
+
"webmanifest",
|
|
2710
|
+
"pdf"
|
|
2711
|
+
]);
|
|
2712
|
+
function isAssetRequest(pathname) {
|
|
2713
|
+
let decoded = pathname;
|
|
2714
|
+
try {
|
|
2715
|
+
decoded = decodeURIComponent(pathname);
|
|
2716
|
+
} catch {}
|
|
2717
|
+
const lastSegment = decoded.split(/[\\/]+/).pop() ?? "";
|
|
2718
|
+
const dot = lastSegment.lastIndexOf(".");
|
|
2719
|
+
if (dot <= 0 || dot === lastSegment.length - 1)
|
|
2720
|
+
return false;
|
|
2721
|
+
return ASSET_EXTENSIONS.has(lastSegment.slice(dot + 1).toLowerCase());
|
|
2722
|
+
}
|
|
2723
|
+
function resolveStaticPath(appRoot, pathname) {
|
|
2724
|
+
let decodedPath;
|
|
2725
|
+
try {
|
|
2726
|
+
decodedPath = decodeURIComponent(pathname);
|
|
2727
|
+
} catch {
|
|
2728
|
+
return null;
|
|
2729
|
+
}
|
|
2730
|
+
if (decodedPath.includes("\x00"))
|
|
2731
|
+
return null;
|
|
2732
|
+
const segments = decodedPath.split(/[\\/]+/);
|
|
2733
|
+
if (segments.includes(".."))
|
|
2734
|
+
return null;
|
|
2735
|
+
const normalizedPath = normalize(decodedPath).replace(/^[\\/]+/, "");
|
|
2736
|
+
const resolvedPath = resolve3(appRoot, normalizedPath);
|
|
2737
|
+
const rel = relative3(appRoot, resolvedPath);
|
|
2738
|
+
if (rel.startsWith("..") || isAbsolute(rel))
|
|
2739
|
+
return null;
|
|
2740
|
+
return resolvedPath;
|
|
2741
|
+
}
|
|
2742
|
+
function injectRuntimeConfig(html, config) {
|
|
2743
|
+
const existingRuntimeScript = /<script>window\.__SIXB_RUNTIME__ = (.*?);<\/script>/;
|
|
2744
|
+
const existingConfig = html.match(existingRuntimeScript)?.[1];
|
|
2745
|
+
const script = renderCustomAppRuntimeScript({
|
|
2746
|
+
auth: { enabled: config.authEnabled },
|
|
2747
|
+
...existingConfig ? JSON.parse(existingConfig) : {},
|
|
2748
|
+
...config.apiBaseUrl ? {
|
|
2749
|
+
api: { baseUrl: config.apiBaseUrl },
|
|
2750
|
+
auth: { enabled: config.authEnabled }
|
|
2751
|
+
} : {},
|
|
2752
|
+
publicEnv: config.publicEnv
|
|
2753
|
+
});
|
|
2754
|
+
if (existingRuntimeScript.test(html)) {
|
|
2755
|
+
return html.replace(existingRuntimeScript, () => script);
|
|
2756
|
+
}
|
|
2757
|
+
if (/<head\b[^>]*>/i.test(html)) {
|
|
2758
|
+
return html.replace(/<head\b[^>]*>/i, (head) => `${head}
|
|
2759
|
+
${script}`);
|
|
2760
|
+
}
|
|
2761
|
+
return `${script}
|
|
2762
|
+
${html}`;
|
|
2763
|
+
}
|
|
2764
|
+
function htmlResponse(request, html) {
|
|
2765
|
+
return new Response(request.method === "HEAD" ? null : html, {
|
|
2766
|
+
headers: {
|
|
2767
|
+
"content-type": "text/html; charset=utf-8",
|
|
2768
|
+
"cache-control": "no-store"
|
|
2769
|
+
}
|
|
2770
|
+
});
|
|
2771
|
+
}
|
|
2772
|
+
function sharedHtmlResponse(request, html, apiBaseUrl) {
|
|
2773
|
+
const secured = secureSharedHtml(html, request, { apiBaseUrl });
|
|
2774
|
+
return new Response(request.method === "HEAD" ? null : secured.html, {
|
|
2775
|
+
headers: {
|
|
2776
|
+
"content-type": "text/html; charset=utf-8",
|
|
2777
|
+
...secured.headers
|
|
2778
|
+
}
|
|
2779
|
+
});
|
|
2780
|
+
}
|
|
2781
|
+
function secureSharedHtml(html, request, options) {
|
|
2782
|
+
const nonce = randomBytes(18).toString("base64url");
|
|
2783
|
+
const requestOrigin = new URL(request.url).origin;
|
|
2784
|
+
let apiOrigin = requestOrigin;
|
|
2785
|
+
try {
|
|
2786
|
+
apiOrigin = new URL(options.apiBaseUrl ?? requestOrigin, requestOrigin).origin;
|
|
2787
|
+
} catch {}
|
|
2788
|
+
const apiSources = apiOrigin === requestOrigin ? [] : [apiOrigin];
|
|
2789
|
+
const connectSources = ["'self'", ...apiSources];
|
|
2790
|
+
const fileSources = ["'self'", ...apiSources, "data:", "blob:", "https:"];
|
|
2791
|
+
const scriptSources = [`'nonce-${nonce}'`, "'strict-dynamic'", "'self'"];
|
|
2792
|
+
const contentSecurityPolicy = [
|
|
2793
|
+
"default-src 'none'",
|
|
2794
|
+
"base-uri 'none'",
|
|
2795
|
+
"object-src 'none'",
|
|
2796
|
+
"frame-ancestors 'none'",
|
|
2797
|
+
"form-action 'none'",
|
|
2798
|
+
`script-src ${scriptSources.join(" ")}`,
|
|
2799
|
+
"style-src 'self' 'unsafe-inline'",
|
|
2800
|
+
`img-src ${fileSources.join(" ")}`,
|
|
2801
|
+
`media-src ${fileSources.join(" ")}`,
|
|
2802
|
+
"font-src 'self' data: https:",
|
|
2803
|
+
`connect-src ${connectSources.join(" ")}`,
|
|
2804
|
+
"manifest-src 'none'"
|
|
2805
|
+
].join("; ");
|
|
2806
|
+
return {
|
|
2807
|
+
html: html.replace(/<script(?![^>]*\snonce=)/g, `<script nonce="${nonce}"`),
|
|
2808
|
+
headers: {
|
|
2809
|
+
"cache-control": "no-store",
|
|
2810
|
+
"content-security-policy": contentSecurityPolicy,
|
|
2811
|
+
"permissions-policy": "camera=(), geolocation=(), microphone=(), payment=(), usb=(), browsing-topics=()",
|
|
2812
|
+
"referrer-policy": "no-referrer",
|
|
2813
|
+
"x-content-type-options": "nosniff",
|
|
2814
|
+
"x-frame-options": "DENY",
|
|
2815
|
+
"x-robots-tag": "noindex, nofollow, noarchive"
|
|
2816
|
+
}
|
|
2817
|
+
};
|
|
2818
|
+
}
|
|
2819
|
+
var IMMUTABLE_ASSET_PATTERN = /^(?:(?:app|shared|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/;
|
|
2820
|
+
function staticAssetHeaders(pathname) {
|
|
2821
|
+
if (pathname === customAppManifestRoute) {
|
|
2822
|
+
return {
|
|
2823
|
+
"content-type": "application/manifest+json; charset=utf-8",
|
|
2824
|
+
"cache-control": "no-cache"
|
|
2825
|
+
};
|
|
2826
|
+
}
|
|
2827
|
+
const lastSegment = pathname.split("/").pop() ?? "";
|
|
2828
|
+
if (!IMMUTABLE_ASSET_PATTERN.test(lastSegment)) {
|
|
2829
|
+
return {};
|
|
2830
|
+
}
|
|
2831
|
+
return { "cache-control": "public, max-age=31536000, immutable" };
|
|
2832
|
+
}
|
|
2833
|
+
async function staticFileResponse(request, path, headers) {
|
|
2834
|
+
const responseHeaders = new Headers(headers);
|
|
2835
|
+
const originalFile = Bun.file(path);
|
|
2836
|
+
let responseFile = originalFile;
|
|
2837
|
+
if (isPrecompressedAsset(path)) {
|
|
2838
|
+
responseHeaders.append("vary", "Accept-Encoding");
|
|
2839
|
+
if (!request.headers.has("range")) {
|
|
2840
|
+
for (const encoding of acceptedPrecompressedEncodings(request)) {
|
|
2841
|
+
const candidate = Bun.file(`${path}.${encoding === "br" ? "br" : "gz"}`);
|
|
2842
|
+
if (!await candidate.exists())
|
|
2843
|
+
continue;
|
|
2844
|
+
responseFile = candidate;
|
|
2845
|
+
responseHeaders.set("content-encoding", encoding);
|
|
2846
|
+
responseHeaders.set("content-type", originalFile.type);
|
|
2847
|
+
break;
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
return new Response(request.method === "HEAD" ? null : responseFile, {
|
|
2852
|
+
headers: responseHeaders
|
|
2853
|
+
});
|
|
2854
|
+
}
|
|
2855
|
+
function isPrecompressedAsset(path) {
|
|
2856
|
+
return path.endsWith(".js") || path.endsWith(".css");
|
|
2857
|
+
}
|
|
2858
|
+
function acceptedPrecompressedEncodings(request) {
|
|
2859
|
+
const header = request.headers.get("accept-encoding");
|
|
2860
|
+
if (!header)
|
|
2861
|
+
return [];
|
|
2862
|
+
const qualities = new Map;
|
|
2863
|
+
for (const item of header.split(",")) {
|
|
2864
|
+
const [rawName, ...parameters] = item.trim().split(";");
|
|
2865
|
+
const name = rawName.toLowerCase();
|
|
2866
|
+
let quality = 1;
|
|
2867
|
+
for (const parameter of parameters) {
|
|
2868
|
+
const match = parameter.trim().match(/^q=(0(?:\.\d+)?|1(?:\.0+)?)$/);
|
|
2869
|
+
if (match)
|
|
2870
|
+
quality = Number(match[1]);
|
|
2871
|
+
}
|
|
2872
|
+
qualities.set(name, quality);
|
|
2873
|
+
}
|
|
2874
|
+
const wildcard = qualities.get("*") ?? 0;
|
|
2875
|
+
return ["br", "gzip"].map((encoding, preference) => ({
|
|
2876
|
+
encoding,
|
|
2877
|
+
preference,
|
|
2878
|
+
quality: qualities.get(encoding) ?? wildcard
|
|
2879
|
+
})).filter((candidate) => candidate.quality > 0).sort((left, right) => right.quality - left.quality || left.preference - right.preference).map((candidate) => candidate.encoding);
|
|
2880
|
+
}
|
|
2881
|
+
function fileResponse(request, file, headers = {}) {
|
|
2882
|
+
return new Response(request.method === "HEAD" ? null : file, { headers });
|
|
2883
|
+
}
|
|
2884
|
+
function filePathResponse(request, path) {
|
|
2885
|
+
return fileResponse(request, Bun.file(path));
|
|
2886
|
+
}
|
|
2887
|
+
function notFoundResponse() {
|
|
2888
|
+
return new Response("Not Found", {
|
|
2889
|
+
status: 404,
|
|
2890
|
+
headers: {
|
|
2891
|
+
"cache-control": "no-store"
|
|
2892
|
+
}
|
|
2893
|
+
});
|
|
2894
|
+
}
|
|
2895
|
+
function getHeadRoute(handler) {
|
|
2896
|
+
return {
|
|
2897
|
+
GET: handler,
|
|
2898
|
+
HEAD: handler
|
|
2899
|
+
};
|
|
2900
|
+
}
|
|
2901
|
+
function allMethodsRoute(handler) {
|
|
2902
|
+
return {
|
|
2903
|
+
GET: handler,
|
|
2904
|
+
HEAD: handler,
|
|
2905
|
+
POST: handler,
|
|
2906
|
+
PUT: handler,
|
|
2907
|
+
PATCH: handler,
|
|
2908
|
+
DELETE: handler,
|
|
2909
|
+
OPTIONS: handler
|
|
2910
|
+
};
|
|
2911
|
+
}
|
|
2912
|
+
async function importHtmlBundle(htmlPath, version) {
|
|
2913
|
+
const bundleEntryPath = await prepareAppHtmlBundleEntry(htmlPath);
|
|
2914
|
+
const url = pathToFileURL2(bundleEntryPath);
|
|
2915
|
+
url.searchParams.set("v", String(version));
|
|
2916
|
+
const htmlModule = await import(url.href);
|
|
2917
|
+
return htmlModule.default;
|
|
2918
|
+
}
|
|
2919
|
+
function htmlBundleRoute(bundle) {
|
|
2920
|
+
return {
|
|
2921
|
+
GET: bundle,
|
|
2922
|
+
HEAD: bundle
|
|
2923
|
+
};
|
|
2924
|
+
}
|
|
2925
|
+
function manifestRoute(manifestPath) {
|
|
2926
|
+
return getHeadRoute((request) => fileResponse(request, Bun.file(manifestPath), staticAssetHeaders(customAppManifestRoute)));
|
|
2927
|
+
}
|
|
2928
|
+
function devServerInternalOrigin(host, port) {
|
|
2929
|
+
if (host === "0.0.0.0") {
|
|
2930
|
+
return `http://127.0.0.1:${port}`;
|
|
2931
|
+
}
|
|
2932
|
+
if (host === "::" || host === "[::]") {
|
|
2933
|
+
return `http://[::1]:${port}`;
|
|
2934
|
+
}
|
|
2935
|
+
const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
|
2936
|
+
return `http://${urlHost}:${port}`;
|
|
2937
|
+
}
|
|
2938
|
+
function spaHtmlRoute(internalOrigin, options = {}) {
|
|
2939
|
+
return getHeadRoute(async (request) => {
|
|
2940
|
+
const publicUrl = new URL(request.url);
|
|
2941
|
+
if (isReservedSixbRoute(publicUrl.pathname) || isSharedNamespace(publicUrl.pathname) || isFrameworkPrivateRoute(publicUrl.pathname)) {
|
|
2942
|
+
return notFoundResponse();
|
|
2943
|
+
}
|
|
2944
|
+
if (publicUrl.pathname !== "/" && isAssetRequest(publicUrl.pathname)) {
|
|
2945
|
+
return notFoundResponse();
|
|
2946
|
+
}
|
|
2947
|
+
const url = new URL(options.shellRoute ?? internalAppShellRoute, internalOrigin());
|
|
2948
|
+
url.search = publicUrl.search;
|
|
2949
|
+
const requestHeaders = new Headers(request.headers);
|
|
2950
|
+
for (const header of [
|
|
2951
|
+
"forwarded",
|
|
2952
|
+
"host",
|
|
2953
|
+
"x-forwarded-host",
|
|
2954
|
+
"x-forwarded-port",
|
|
2955
|
+
"x-forwarded-proto"
|
|
2956
|
+
]) {
|
|
2957
|
+
requestHeaders.delete(header);
|
|
2958
|
+
}
|
|
2959
|
+
const bundleResponse = await fetch(new Request(url, { method: request.method, headers: requestHeaders }));
|
|
2960
|
+
const responseHeaders = new Headers(bundleResponse.headers);
|
|
2961
|
+
responseHeaders.delete("content-length");
|
|
2962
|
+
responseHeaders.delete("etag");
|
|
2963
|
+
if (request.method === "HEAD") {
|
|
2964
|
+
return new Response(null, {
|
|
2965
|
+
status: bundleResponse.status,
|
|
2966
|
+
statusText: bundleResponse.statusText,
|
|
2967
|
+
headers: responseHeaders
|
|
2968
|
+
});
|
|
2969
|
+
}
|
|
2970
|
+
const html = restoreAppStaticUrls(await bundleResponse.text()).replace("</head>", '<script src="/__sixb/dev-reload.js"></script></head>');
|
|
2971
|
+
return new Response(options.transformHtml?.(html) ?? html, {
|
|
2972
|
+
status: bundleResponse.status,
|
|
2973
|
+
statusText: bundleResponse.statusText,
|
|
2974
|
+
headers: responseHeaders
|
|
2975
|
+
});
|
|
2976
|
+
});
|
|
2977
|
+
}
|
|
2978
|
+
export {
|
|
2979
|
+
AppPackagesMissingError,
|
|
2980
|
+
createCustomApp
|
|
2981
|
+
};
|
|
2982
|
+
|
|
2983
|
+
//# debugId=30AB960A6C76A40E64756E2164756E21
|