@salsita-ai/sdk 0.50.0-develop.334b422a4f → 0.50.0-develop.3986957af6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.d.ts +11 -5
  2. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.js +1 -1
  3. package/dist/application-spec/generate-application/runtime/admin-runtime/admin-runtime.d.ts +3 -2
  4. package/dist/application-spec/generate-application/runtime/admin-runtime/admin-runtime.js +1 -1
  5. package/dist/application-spec/generate-application/runtime/application-runtime.d.ts +12 -4
  6. package/dist/application-spec/generate-application/runtime/application-runtime.js +1 -1
  7. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.d.ts +3 -3
  8. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.js +1 -1
  9. package/dist/application-spec/generate-application/runtime/sections/expression-runtime.d.ts +9 -3
  10. package/dist/application-spec/generate-application/runtime/sections/expression-runtime.js +1 -1
  11. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +4 -3
  12. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -1
  13. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.d.ts +21 -5
  14. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -1
  15. package/dist/configurator/common/configurator-interface.d.ts +6 -1
  16. package/dist/configurator/common/configurator-interface.js +1 -1
  17. package/dist/configurator/configurator-context/ConfiguratorResponsiveProvider.d.ts +3 -3
  18. package/dist/configurator/configurator-context/ConfiguratorResponsiveProvider.js +1 -1
  19. package/dist/configurator/configurator-context/PreviewContextProvider.js +1 -1
  20. package/dist/configurator/ui/configurator-layout/universal/use-layout-scene-safe-area.js +1 -1
  21. package/dist/configurator/ui/save-message-snackbars/SaveMessageSnackbars.js +1 -1
  22. package/dist/docs/index.json +12 -1
  23. package/dist/docs/integrations/webcomponent-api/basics.mdx +2 -0
  24. package/dist/docs/layouts/custom-layout.mdx +318 -158
  25. package/dist/docs/layouts/gallery/ardent-compressor.mdx +1 -0
  26. package/dist/docs/layouts/gallery/fenwick-window.mdx +198 -127
  27. package/dist/docs/layouts/gallery/ferrule-bar-station.mdx +6567 -0
  28. package/dist/docs/layouts/gallery/sunfold-solar.mdx +16 -4
  29. package/dist/docs/phoenix/configurator-interface.mdx +4 -3
  30. package/dist/docs/phoenix/sessions-and-access.mdx +2 -0
  31. package/dist/domain/application/web-component-property.d.ts +3 -1
  32. package/dist/domain/application/web-component-property.js +1 -1
  33. package/dist/domain/domain-builder.d.ts +9 -3
  34. package/dist/domain/domain-builder.js +1 -1
  35. package/dist/domain/domain-runtime/domain-context/selectors.d.ts +1 -0
  36. package/dist/domain/domain-runtime/domain-context/selectors.js +1 -1
  37. package/dist/domain/domain-runtime/domain-runtime.d.ts +4 -0
  38. package/dist/domain/domain-runtime/errors/implementation-error-collector.d.ts +2 -0
  39. package/dist/domain/domain-runtime/errors/implementation-error-collector.js +1 -1
  40. package/dist/domain/domain-runtime/index.d.ts +1 -1
  41. package/dist/domain/domain-runtime/index.js +1 -1
  42. package/dist/domain/domain-runtime/spec/index.d.ts +1 -1
  43. package/dist/domain/domain-runtime/spec/index.js +1 -1
  44. package/dist/domain/domain-runtime/spec/module-checks/index.d.ts +1 -0
  45. package/dist/domain/domain-runtime/spec/module-checks/index.js +1 -1
  46. package/dist/domain/domain-runtime/spec/module-checks/merge-expression-modules.d.ts +23 -0
  47. package/dist/domain/domain-runtime/spec/module-checks/merge-expression-modules.js +1 -0
  48. package/dist/domain/domain-runtime/spec/module-checks/resolve-expression-modules.d.ts +3 -4
  49. package/dist/domain/domain-runtime/spec/module-checks/resolve-expression-modules.js +1 -1
  50. package/dist/domain/mocks/create-mock-domain-runtime.d.ts +2 -0
  51. package/dist/editor/domain-editors/DomainSpecContext.js +1 -1
  52. package/dist/editor/domain-editors/use-implementation-files.d.ts +6 -11
  53. package/dist/editor/domain-editors/use-implementation-files.js +1 -1
  54. package/dist/legacy/domain-cli/utils/cache.d.ts +1 -1
  55. package/dist/legacy/domain-cli/utils/cache.js +1 -1
  56. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/agents/claude-md.d.ts +1 -1
  57. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/agents/cursor-rules.d.ts +1 -1
  58. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/agents/shared-sdk-content.d.ts +1 -1
  59. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/agents/shared-sdk-content.js +11 -5
  60. package/dist/react-sdk/application-runtime/hooks/index.d.ts +1 -0
  61. package/dist/react-sdk/application-runtime/hooks/index.js +1 -1
  62. package/dist/react-sdk/application-runtime/hooks/responsive/index.d.ts +3 -0
  63. package/dist/react-sdk/application-runtime/hooks/responsive/index.js +1 -0
  64. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-actions.d.ts +9 -0
  65. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-actions.js +1 -0
  66. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-application.d.ts +26 -0
  67. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-application.js +1 -0
  68. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-state.d.ts +10 -0
  69. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-state.js +1 -0
  70. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-store.d.ts +24 -0
  71. package/dist/react-sdk/application-runtime/hooks/responsive/use-responsive-store.js +1 -0
  72. package/dist/react-sdk/application-runtime/hooks/use-access-service.d.ts +5 -0
  73. package/dist/react-sdk/application-runtime/hooks/use-access-service.js +1 -1
  74. package/dist/react-sdk/application-runtime/index.d.ts +1 -0
  75. package/dist/react-sdk/application-runtime/mocks/create-mock-application-runtime.js +1 -1
  76. package/dist/react-sdk/application-runtime/responsive/actions.d.ts +47 -0
  77. package/dist/react-sdk/application-runtime/responsive/actions.js +1 -0
  78. package/dist/react-sdk/application-runtime/responsive/index.d.ts +4 -0
  79. package/dist/react-sdk/application-runtime/responsive/index.js +1 -0
  80. package/dist/react-sdk/application-runtime/responsive/initialize.d.ts +3 -0
  81. package/dist/react-sdk/application-runtime/responsive/initialize.js +1 -0
  82. package/dist/react-sdk/application-runtime/responsive/selectors.d.ts +20 -0
  83. package/dist/react-sdk/application-runtime/responsive/selectors.js +1 -0
  84. package/dist/react-sdk/application-runtime/responsive/types.d.ts +104 -0
  85. package/dist/react-sdk/application-runtime/runtime/create-application-runtime.d.ts +91 -0
  86. package/dist/react-sdk/application-runtime/runtime/create-application-runtime.js +1 -1
  87. package/dist/react-sdk/domain-context/common-hooks/index.d.ts +1 -0
  88. package/dist/react-sdk/domain-context/common-hooks/index.js +1 -1
  89. package/dist/react-sdk/domain-context/common-hooks/use-configuration-save-state.d.ts +23 -0
  90. package/dist/react-sdk/domain-context/common-hooks/use-configuration-save-state.js +1 -0
  91. package/dist/react-sdk/domain-context/common-hooks/use-domain-context.d.ts +1 -0
  92. package/dist/react-sdk/domain-context/index.d.ts +1 -0
  93. package/dist/react-sdk/domain-context/index.js +1 -1
  94. package/dist/react-sdk/index.d.ts +0 -1
  95. package/dist/react-sdk/index.js +1 -1
  96. package/dist/react-sdk/web-component/create-web-component.js +1 -1
  97. package/dist/ui-sdk/responsive-application/ResponsiveApplicationProvider.d.ts +2 -2
  98. package/dist/ui-sdk/responsive-application/responsive-state-store.d.ts +11 -9
  99. package/dist/ui-sdk/responsive-application/use-store-responsive-info.js +1 -1
  100. package/package.json +3 -3
  101. package/dist/react-sdk/responsive-state/ResponsiveStateProvider.d.ts +0 -25
  102. package/dist/react-sdk/responsive-state/ResponsiveStateProvider.js +0 -1
  103. package/dist/react-sdk/responsive-state/canvas-padding.d.ts +0 -14
  104. package/dist/react-sdk/responsive-state/index.d.ts +0 -5
  105. package/dist/react-sdk/responsive-state/index.js +0 -1
  106. package/dist/react-sdk/responsive-state/responsive-state-manager.d.ts +0 -111
  107. package/dist/react-sdk/responsive-state/responsive-state-manager.js +0 -1
  108. package/dist/react-sdk/responsive-state/use-responsive-state-manager.d.ts +0 -10
  109. package/dist/react-sdk/responsive-state/use-responsive-state-manager.js +0 -1
  110. package/dist/react-sdk/responsive-state/use-responsive-state.d.ts +0 -11
  111. package/dist/react-sdk/responsive-state/use-responsive-state.js +0 -1
  112. /package/dist/react-sdk/{responsive-state/canvas-padding.js → application-runtime/responsive/types.js} +0 -0
@@ -74,6 +74,8 @@ expressions:
74
74
  type: number
75
75
  $roofPanelLimit:
76
76
  type: number
77
+ $panelAreaM2:
78
+ type: number
77
79
  $annualProductionKwh:
78
80
  type: number
79
81
  $monthly:
@@ -155,6 +157,10 @@ export default phx.domain.implementCustomExpressions({
155
157
  $roofPanelLimit: s => {
156
158
  return Math.floor((s.roofArea * USABLE_ROOF) / PANEL_AREA_M2)
157
159
  },
160
+ // The roof the panels cover, rounded up to whole square metres, as the tiles and the roof warning quote it
161
+ $panelAreaM2: s => {
162
+ return Math.ceil(s.panels * PANEL_AREA_M2)
163
+ },
158
164
  $annualProductionKwh: s => {
159
165
  return s.$systemKwp * YIELD_KWH_PER_KWP * ORIENTATION_FACTOR[s.orientation]
160
166
  },
@@ -272,7 +278,7 @@ export const KpiTiles = ({ columns }: KpiTilesProps) => {
272
278
  {
273
279
  label: 'System size',
274
280
  value: `${plan.$systemKwp.toFixed(1)} kWp`,
275
- context: `${plan.panels} panels, ${Math.round(plan.panels * 1.95)} m² of roof`,
281
+ context: `${plan.panels} panels, ${plan.$panelAreaM2} m² of roof`,
276
282
  },
277
283
  {
278
284
  label: 'Annual production',
@@ -669,7 +675,7 @@ export default phx.domain.implementCustomInvariants({
669
675
  {
670
676
  type: 'panelsExceedRoof',
671
677
  severity: 'warning',
672
- message: `${s.panels} panels need about ${Math.ceil(s.panels * 1.95)} m² of roof; ${s.roofArea} m² holds at most ${s.$roofPanelLimit}. Lower the panel count or measure the roof again.`,
678
+ message: `${s.panels} panels need about ${s.$panelAreaM2} m² of roof; ${s.roofArea} m² holds at most ${s.$roofPanelLimit}. Lower the panel count or measure the roof again.`,
673
679
  },
674
680
  ]
675
681
  },
@@ -993,6 +999,8 @@ expressions:
993
999
  type: number
994
1000
  $roofPanelLimit:
995
1001
  type: number
1002
+ $panelAreaM2:
1003
+ type: number
996
1004
  $annualProductionKwh:
997
1005
  type: number
998
1006
  $monthly:
@@ -1967,7 +1975,7 @@ export const KpiTiles = ({ columns }: KpiTilesProps) => {
1967
1975
  {
1968
1976
  label: 'System size',
1969
1977
  value: `${plan.$systemKwp.toFixed(1)} kWp`,
1970
- context: `${plan.panels} panels, ${Math.round(plan.panels * 1.95)} m² of roof`,
1978
+ context: `${plan.panels} panels, ${plan.$panelAreaM2} m² of roof`,
1971
1979
  },
1972
1980
  {
1973
1981
  label: 'Annual production',
@@ -2541,6 +2549,10 @@ export default phx.domain.implementCustomExpressions({
2541
2549
  $roofPanelLimit: s => {
2542
2550
  return Math.floor((s.roofArea * USABLE_ROOF) / PANEL_AREA_M2)
2543
2551
  },
2552
+ // The roof the panels cover, rounded up to whole square metres, as the tiles and the roof warning quote it
2553
+ $panelAreaM2: s => {
2554
+ return Math.ceil(s.panels * PANEL_AREA_M2)
2555
+ },
2544
2556
  $annualProductionKwh: s => {
2545
2557
  return s.$systemKwp * YIELD_KWH_PER_KWP * ORIENTATION_FACTOR[s.orientation]
2546
2558
  },
@@ -2657,7 +2669,7 @@ export default phx.domain.implementCustomInvariants({
2657
2669
  {
2658
2670
  type: 'panelsExceedRoof',
2659
2671
  severity: 'warning',
2660
- message: `${s.panels} panels need about ${Math.ceil(s.panels * 1.95)} m² of roof; ${s.roofArea} m² holds at most ${s.$roofPanelLimit}. Lower the panel count or measure the roof again.`,
2672
+ message: `${s.panels} panels need about ${s.$panelAreaM2} m² of roof; ${s.roofArea} m² holds at most ${s.$roofPanelLimit}. Lower the panel count or measure the roof again.`,
2661
2673
  },
2662
2674
  ]
2663
2675
  },
@@ -598,7 +598,7 @@ Texts from the spec, such as option titles and the `detail` fields, are `Localiz
598
598
 
599
599
  **Steps and tabs**
600
600
 
601
- A project layout builds its steps and tabs from the spec, so the structure stays in `navigationSteps`, `sidebarTabs` and `horizontalTabs`, where `$filter` switches it, and the layout decides how it looks. `phx.frontend.useStepNavigation()` gives a wizard its steps with a `status` each, and `next`, `previous` and `goTo`; `phx.frontend.useTabNavigation()` gives tabs with `isActive` each, and `select`. Both enter a navigation state, so controls, cameras and components filtered by `navigationStates` follow. Neither hides anything in read mode or blocks a step on violations: a layout that should not move on while the configuration is invalid combines `canGoNext` with `useStateValidity()`, and a stepper that offers only earlier steps enables the steps whose `status` is `'complete'`.
601
+ A project layout builds its steps and tabs from the spec, so the structure stays in `navigationSteps`, `sidebarTabs` and `horizontalTabs`, where `$filter` switches it, and the layout decides how it looks. `phx.frontend.useStepNavigation()` gives a wizard its steps with a `status` each, and `next`, `previous` and `goTo`; `phx.frontend.useTabNavigation()` gives tabs with `isActive` each, and `select`. Both enter a navigation state, so controls, cameras and components filtered by `navigationStates` follow. Neither hides anything in read mode or blocks a step on violations: a layout that should not move on while the configuration has a problem requires `phx.frontend.useStateValidity().severity !== 'warning'` besides `canGoNext`, because a change with a `fixable` or `fatal` violation is rejected and the committed configuration is never invalid, while a `warning` stays and blocks finalizing. A stepper that offers only earlier steps enables the steps whose `status` is `'complete'`.
602
602
 
603
603
  ```tsx
604
604
  export const Wizard = () => {
@@ -647,6 +647,7 @@ A layout builds its toolbar from `phx.frontend.useToolbarActions()`, which retur
647
647
  | `phx.frontend.useStateValidity()` | The validity of the last committed state: `{ valid: true, severity: null }`, or `{ valid: true, severity: 'notice' \| 'warning', entityViolations }`. A change that leaves a `fixable` or `fatal` violation is rejected and never committed, and neither is a change during which an error was thrown, so neither is seen here. |
648
648
  | `phx.frontend.useFinalizeViolations()` | `{ disabled, hints, violations }`. `disabled` is `true` while a `warning`, `fixable` or `fatal` violation holds or the configuration failed to save; `hints` is the violations' text, or `undefined`. |
649
649
  | `phx.frontend.useConfiguratorMessages(onMessage)` | Nothing. It calls `onMessage(message)` once per message: `{ kind: 'violation', entityId, violation, text }` for each violation of the rejected state, including notices and warnings already present, so `violation.severity` tells the reason for the rejection (`fixable` or `fatal`) from them, `{ kind: 'sideEffect', text }` for each hint of a committed update, `{ kind: 'error', error, text }` when an error is thrown while a change is validated, with `text` the generic "Oops, something went wrong", `{ kind: 'saveError', error, text }` each time saving the configuration fails, with `error` what the save rejected with and `text` a generic message, and `{ kind: 'saveRecovery', text }` when a save succeeds after a failed one, with `text` "Configuration updated". `text` is resolved to the current language; a violation's is its `message`, or its `type` without one, and the built-in snackbar prefixes it with `entityId`. Hints committed before the layout mounted are not delivered, nor is a save that failed before it mounted; when the most recent change was rejected or threw, its messages are delivered again when the hook mounts. `onMessage` may be a new function on every render. On `phx.frontend` the message is typed by the project, so `violation.type` narrows to its violation types; from `@salsita-ai/sdk/react` the type is `ConfiguratorMessage`. |
650
+ | `phx.frontend.useConfigurationSaveState()` | `{ revisionId, isSaving, failure }`, the save status of the configuration. An editable configuration saves every committed change on its own, three seconds after the last one, and a read-only one never saves. `revisionId` is the revision the configuration is at: the loaded one, then the one the latest save created. `isSaving` is `true` while a save runs. `failure` is `{ error, timestamp }` of the latest failed save, with `timestamp` in milliseconds since the epoch, and `null` once a later save succeeds or another configuration loads. A layout shows a save indicator with it; the messages of a failed save and of its recovery come from `useConfiguratorMessages`. Besides `phx.frontend`, `@salsita-ai/sdk/react` exports it. |
650
651
  | `phx.frontend.useFinalizeAction(handler)` | `{ run, isPending, error, disabled, hints }` for the `finalizeAction` whose `handler` it is given; see the Finalize paragraph below for how to call it. `run()` records the finalize-button click for analytics and runs the project's handler, does nothing while `disabled` or `isPending`, and returns a promise that resolves once the handler has settled and never rejects; `error` is what the handler's last run rejected with, or `null`; `disabled` and `hints` are those of `useFinalizeViolations()`. The type of the result is `UseFinalizeActionResult` from `@salsita-ai/sdk/configurator`, which also exports the hook. |
651
652
  | `phx.frontend.useFinalizeActions()` | `{ actions, primary, secondary, disabled, hints }`: every active `finalizeAction` of the spec in spec order, `primary` the first `'primary'` one, or else the first, or `null`, and `secondary` the others; see the Finalize paragraph below. Each action is `{ key, handler, variant, label, title, icon, run, isPending, error, disabled }`, with `label` and `title` resolved; `run()` records the finalize-button click for analytics and runs the action's handler, does nothing while `disabled` or `isPending`, and returns a promise that never rejects. `disabled` and `hints` are those of `useFinalizeViolations()`. Besides `phx.frontend`, `@salsita-ai/sdk/react` exports it. |
652
653
 
@@ -654,7 +655,7 @@ A layout builds its toolbar from `phx.frontend.useToolbarActions()`, which retur
654
655
 
655
656
  **Finalize**
656
657
 
657
- A project layout finalizes over the spec's `finalizeAction` components, each `{ variant, label, title, icon, handler }`, where `variant` is `'primary'` or `'secondary'` and `handler` names the project's handler registered with `phx.frontend.createPhoenixHandler`. `phx.frontend.useFinalizeActions()` is the convenient way: it lists them with what a button needs, runs their handlers itself, and can be called anywhere in the layout, including a dialog the layout opens with `useModal`, as often as it likes. It returns:
658
+ A project layout finalizes over the spec's `finalizeAction` components, each `{ variant, label, title, icon, handler }`, where `variant` is `'primary'` or `'secondary'` and `handler` names the project's handler registered with `phx.frontend.createPhoenixHandler`. `phx.frontend.useFinalizeActions()` is the convenient way: it lists them with what a button needs, runs their handlers itself, and can be called anywhere in the layout, including a dialog the layout opens with `useModal`, as often as it likes; [Custom Layout](?path=/docs/layouts-custom-layout--docs#request-a-quote) offers its primary action this way in its review step. It returns:
658
659
 
659
660
  - `actions`, every active `finalizeAction` in spec order, and `primary` and `secondary`, the same actions split as the built-in footer splits them: `primary` is the first `'primary'` action, or else the first action, or `null` without any, and `secondary` the others in spec order.
660
661
  - `disabled` and `hints`, those of `useFinalizeViolations()`: finalizing is not possible while a `warning`, `fixable` or `fatal` violation holds or the configuration failed to save, and `hints` says why.
@@ -698,7 +699,7 @@ export const Finalize = () => {
698
699
 
699
700
  The configurator runs the handlers outside the layout, beside it, whenever a configuration is open, also in read mode and on every step. A handler can use what the configurator provides, such as `useModal`, but not a provider the layout itself adds; such a handler fails to load and shows as that action's `error`. An action's `isPending` and `error` are kept while the layout re-renders and while its components unmount and mount again.
700
701
 
701
- To run a single action the layout already knows, `phx.frontend.useFinalizeAction(handler)` runs it in the layout itself and returns `{ run, isPending, error, disabled, hints }`, with the same meaning. It runs the project's handler factory, which calls hooks, so the layout calls it once per component, never in a loop or conditionally, and wraps that component in `<PhoenixHandlerBoundary name={handler}>` from `@salsita-ai/sdk/react`, so an edited handler takes effect without a reload. Its `isPending` and `error` belong to the mounted component: when it unmounts during a run, the handler keeps running, and a component mounted afterwards starts with `isPending` false and no `error`. [Custom Layout](?path=/docs/layouts-custom-layout--docs#request-a-quote) runs a finalize action this way from its review step.
702
+ To run a single action the layout already knows, `phx.frontend.useFinalizeAction(handler)` runs it in the layout itself and returns `{ run, isPending, error, disabled, hints }`, with the same meaning. It runs the project's handler factory, which calls hooks, so the layout calls it once per component, never in a loop or conditionally, and wraps that component in `<PhoenixHandlerBoundary name={handler}>` from `@salsita-ai/sdk/react`, so an edited handler takes effect without a reload. Its `isPending` and `error` belong to the mounted component: when it unmounts during a run, the handler keeps running, and a component mounted afterwards starts with `isPending` false and no `error`.
702
703
 
703
704
  Neither hook checks read mode, so the layout hides finalizing while `accessInfo.viewMode` is `true`, as above.
704
705
 
@@ -427,6 +427,8 @@ The `readonly` web component property lets the host force view mode without chan
427
427
 
428
428
  Because an owner-token session can be forced read-only client-side while the server still accepts writes from that owner token, Phoenix skips persistence and logs a warning instead of updating the configuration. This guards against the configuration being silently overwritten by code paths that mutate state in read-only mode. UI that triggers significant changes (anything that produces a new revision) should still be disabled when `accessInfo.viewMode` is true — the warning is a backstop, not a substitute.
429
429
 
430
+ The assistant follows the same read-only rule as the UI: its `apply` tool refuses changes while `accessInfo.viewMode` is true, that is with a read-revision token or while `readonly` is set, and makes them again once it is false. A switch of `readonly` takes effect at once, in both directions, and the configurator loads the configuration again. A change applied after `readonly` is cleared and before the configuration has loaded again is not saved; saving resumes once it has loaded. The `query` tool keeps working, including its dry-run mutations.
431
+
430
432
  ```html
431
433
  <salsita-configurator readonly></salsita-configurator>
432
434
  ```
@@ -23,10 +23,12 @@ export declare const webComponentAttributeParsers: {
23
23
  readonly commaSeparatedStrings: (value: string) => string[];
24
24
  /**
25
25
  * Parses a string into a boolean.
26
+ * - `""`, a bare attribute such as `<salsita-configurator readonly>` -> `true`
26
27
  * - `"true"` -> `true`
27
28
  * - `"false"` -> `false`
28
29
  *
29
- * All other values are considered invalid.
30
+ * The web component also reads the attribute's own name as its value (`readonly="readonly"`) as `true`,
31
+ * as HTML does for boolean attributes. All other values are considered invalid.
30
32
  */
31
33
  readonly boolean: (value: string) => boolean;
32
34
  /**
@@ -1,2 +1,2 @@
1
- import{match as r}from"ts-pattern";export const EmptyProperty=Symbol("emptyProperty");export const webComponentAttributeParsers={globalVariable:r=>{if(!Object.hasOwn(window,r))throw Error(`Global variable ${r} not found`);return window[r]},string:String,number:r=>{let t=Number(r);if(isNaN(t))throw Error(`Invalid number: ${r}`);return t},commaSeparatedStrings:r=>r.split(",").map(r=>r.trim()).filter(r=>""!==r),boolean:t=>r(t).with("true",()=>!0).with("false",()=>!1).otherwise(()=>{throw Error(`Invalid boolean: ${t}`)}),json:r=>{try{return JSON.parse(r)}catch(t){throw Error(`Invalid JSON: ${r}`)}},shareUrl:r=>{let t=new URL(r);return{ca:t.searchParams.get("ca"),cid:t.searchParams.get("cid")}}};export function createWebComponentPropertyDescriptor(r){if(void 0!==r.attributeParser&&void 0!==r.attributeNames&&(void 0===r.attributeParser||void 0===r.attributeNames))throw Error(`When exposing WebComponent properties as attributes, both 'attributeParser' and 'attributeNames' must be specified.
1
+ import{match as r}from"ts-pattern";export const EmptyProperty=Symbol("emptyProperty");export const webComponentAttributeParsers={globalVariable:r=>{if(!Object.hasOwn(window,r))throw Error(`Global variable ${r} not found`);return window[r]},string:String,number:r=>{let t=Number(r);if(isNaN(t))throw Error(`Invalid number: ${r}`);return t},commaSeparatedStrings:r=>r.split(",").map(r=>r.trim()).filter(r=>""!==r),boolean:t=>r(t).with("","true",()=>!0).with("false",()=>!1).otherwise(()=>{throw Error(`Invalid boolean: ${t}`)}),json:r=>{try{return JSON.parse(r)}catch(t){throw Error(`Invalid JSON: ${r}`)}},shareUrl:r=>{let t=new URL(r);return{ca:t.searchParams.get("ca"),cid:t.searchParams.get("cid")}}};export function createWebComponentPropertyDescriptor(r){if(void 0!==r.attributeParser&&void 0!==r.attributeNames&&(void 0===r.attributeParser||void 0===r.attributeNames))throw Error(`When exposing WebComponent properties as attributes, both 'attributeParser' and 'attributeNames' must be specified.
2
2
  To migrate from previous versions of the SDK, add 'attributeNames: [<property-name-in-lowercase>]'.`);return"required"in r?{attributeParser:void 0,attributeNames:void 0,defaultValue:r.mockValue,...r}:{attributeNames:void 0,attributeParser:void 0,required:!1,...r}}
@@ -24,11 +24,17 @@ export declare class DomainBuilder<ENTITIES extends DomainEntity<string>, ALLOWE
24
24
  withMigrate(migration: MigrateFunction<ENTITIES>): DomainBuilder<ENTITIES, ALLOWED_ROOT_ENTITIES, ALIASES, $MAP, PUBLISHED_DATA, SESSION_DATA, FRONTEND_DATA>;
25
25
  withExpressions(implementation: AliasedExpressions<ENTITIES, ALLOWED_ROOT_ENTITIES, PUBLISHED_DATA, SESSION_DATA, FRONTEND_DATA, ALIASES>): DomainBuilder<ENTITIES, ALLOWED_ROOT_ENTITIES, ALIASES, $MAP, PUBLISHED_DATA, SESSION_DATA, FRONTEND_DATA>;
26
26
  /**
27
- * Adds the expressions of the `src/expressions/` files, as the generated barrel lists them. Each file
28
- * is checked against the folder's contract and added on its own, so an expression defined twice is
29
- * reported with both files instead of being overwritten by file order.
27
+ * Adds the expressions of the `src/expressions/` files, as the generated barrel lists them. The
28
+ * files are merged by `mergeExpressionModules`, which checks each one and throws every wrong file,
29
+ * every expression defined twice and every expression the domain already has, such as a generated
30
+ * one, together as one `ImplementationErrors` of `DUPLICATE_DEFINITION`s.
30
31
  */
31
32
  withExpressionModules(modules: readonly ProjectModule[]): DomainBuilder<ENTITIES, ALLOWED_ROOT_ENTITIES, ALIASES, $MAP, PUBLISHED_DATA, SESSION_DATA, FRONTEND_DATA>;
33
+ /**
34
+ * Adds expressions already expanded to entity types, each with its origin. An expression that the
35
+ * domain, or an earlier one of the list, defines for the same entity type is an error.
36
+ */
37
+ private withEntityExpressions;
32
38
  /** Declares the actions of the domain, as the generated `domain-spec.ts` reads them from the spec's `actions` section. */
33
39
  withActions(actions: readonly ActionDefinition[]): DomainBuilder<ENTITIES, ALLOWED_ROOT_ENTITIES, ALIASES, $MAP, PUBLISHED_DATA, SESSION_DATA, FRONTEND_DATA>;
34
40
  /** Adds the action implementations of the `src/actions/` files, as the generated barrel lists them, after checking each file against the folder's contract. */
@@ -1 +1 @@
1
- import{DomainFactory as t,createMigrateFunction as i,expandAlias as e}from"./core/index.js";import{resolveActionModules as s,resolveExpressionModules as n}from"./domain-runtime/index.js";import{withProfilerLabel as a}from"./utils/profiler-label.js";export class DomainBuilder{entities;aliasMap;$entityReflections;allowedRootEntityTypes;implemented;modelVersion;publishedData;sessionData;frontendData;backendData;migrate;isAdminDomain;actions;actionImplementations;constructor(t,i,e,s,n,a,o,h,l,m,r,d,p,c){this.entities=t,this.aliasMap=i,this.$entityReflections=e,this.allowedRootEntityTypes=s,this.implemented=n,this.modelVersion=a,this.publishedData=o,this.sessionData=h,this.frontendData=l,this.backendData=m,this.migrate=r,this.isAdminDomain=d,this.actions=p,this.actionImplementations=c}static from(t,e,s,n,a,o,h,l,m,r){let d=i({1:t},1,{});return new DomainBuilder(t,e,s,n,{},a,o,h,l,m,d,r,{},{})}withMigrate(t){return new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,this.implemented,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,t,this.isAdminDomain,this.actions,this.actionImplementations)}withExpressions(t){let i={...this.implemented};return Object.entries(t).forEach(([t,s])=>{e(this.aliasMap,t).forEach(e=>{let n={...i[e]};i[e]=n,Object.entries(s).forEach(([i,s])=>{let o=n[i];if(o)throw Error(`Duplicate expression ${e}.${i}: The expression is defined on both ${t} and ${o.origin.typeOrAlias}, which would lead to ambiguous usage. Please ensure that expressions are only defined once.`);n[i]={...s,evaluate:a(`${e}_${i}`,s.evaluate),origin:{name:i,typeOrAlias:t}}})})}),new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,i,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,this.migrate,this.isAdminDomain,this.actions,this.actionImplementations)}withExpressionModules(t){return n(t,this.aliasMap).reduce((t,i)=>t.withExpressions(i.expressions),this)}withActions(t){return new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,this.implemented,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,this.migrate,this.isAdminDomain,Object.fromEntries(t.map(t=>[t.name,t])),this.actionImplementations)}withActionModules(t){return this.withActionImplementations(s(t))}withActionImplementations(t){return new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,this.implemented,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,this.migrate,this.isAdminDomain,this.actions,{...this.actionImplementations,...t})}build=()=>{let e=this.implemented,s=this.migrate??i({1:this.entities},1,{});return new t({aliasMap:this.aliasMap,entityReflections:this.entities,$entityReflections:this.$entityReflections,expressions:e,allowedRootEntityTypes:this.allowedRootEntityTypes,modelVersion:this.modelVersion,migrate:s,publishedData:this.publishedData,sessionData:this.sessionData,frontendData:this.frontendData,backendData:this.backendData,isAdminDomain:this.isAdminDomain,actions:this.actions,actionImplementations:this.actionImplementations})}}
1
+ import{DomainFactory as t,createMigrateFunction as i,expandAlias as e}from"./core/index.js";import{mergeExpressionModules as s,resolveActionModules as n}from"./domain-runtime/index.js";import{withProfilerLabel as a}from"./utils/profiler-label.js";export class DomainBuilder{entities;aliasMap;$entityReflections;allowedRootEntityTypes;implemented;modelVersion;publishedData;sessionData;frontendData;backendData;migrate;isAdminDomain;actions;actionImplementations;constructor(t,i,e,s,n,a,o,h,l,m,r,d,p,c){this.entities=t,this.aliasMap=i,this.$entityReflections=e,this.allowedRootEntityTypes=s,this.implemented=n,this.modelVersion=a,this.publishedData=o,this.sessionData=h,this.frontendData=l,this.backendData=m,this.migrate=r,this.isAdminDomain=d,this.actions=p,this.actionImplementations=c}static from(t,e,s,n,a,o,h,l,m,r){let d=i({1:t},1,{});return new DomainBuilder(t,e,s,n,{},a,o,h,l,m,d,r,{},{})}withMigrate(t){return new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,this.implemented,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,t,this.isAdminDomain,this.actions,this.actionImplementations)}withExpressions(t){let i=Object.entries(t);return this.withEntityExpressions(i.flatMap(([t,i])=>e(this.aliasMap,t).flatMap(e=>Object.entries(i).map(([i,s])=>({type:e,expression:{...s,origin:{name:i,typeOrAlias:t}}})))))}withExpressionModules(t){let i=new Map(Object.entries(this.implemented).map(([t,i])=>[t,new Set(Object.keys(i))]));return this.withEntityExpressions(Object.entries(s(t,this.aliasMap,void 0,i)).flatMap(([t,i])=>Object.values(i).map(i=>({type:t,expression:i}))))}withEntityExpressions(t){let i={...this.implemented};return t.forEach(({type:t,expression:e})=>{let{name:s,typeOrAlias:n}=e.origin,o={...i[t]},h=o[s];if(h)throw Error(`Duplicate expression ${t}.${s}: The expression is defined on both ${n} and ${h.origin.typeOrAlias}, which would lead to ambiguous usage. Please ensure that expressions are only defined once.`);o[s]={...e,evaluate:a(`${t}_${s}`,e.evaluate)},i[t]=o}),new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,i,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,this.migrate,this.isAdminDomain,this.actions,this.actionImplementations)}withActions(t){return new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,this.implemented,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,this.migrate,this.isAdminDomain,Object.fromEntries(t.map(t=>[t.name,t])),this.actionImplementations)}withActionModules(t){return this.withActionImplementations(n(t))}withActionImplementations(t){return new DomainBuilder(this.entities,this.aliasMap,this.$entityReflections,this.allowedRootEntityTypes,this.implemented,this.modelVersion,this.publishedData,this.sessionData,this.frontendData,this.backendData,this.migrate,this.isAdminDomain,this.actions,{...this.actionImplementations,...t})}build=()=>{let e=this.implemented,s=this.migrate??i({1:this.entities},1,{});return new t({aliasMap:this.aliasMap,entityReflections:this.entities,$entityReflections:this.$entityReflections,expressions:e,allowedRootEntityTypes:this.allowedRootEntityTypes,modelVersion:this.modelVersion,migrate:s,publishedData:this.publishedData,sessionData:this.sessionData,frontendData:this.frontendData,backendData:this.backendData,isAdminDomain:this.isAdminDomain,actions:this.actions,actionImplementations:this.actionImplementations})}}
@@ -124,6 +124,7 @@ export declare const createDomainContextSelectors: (context: Context) => {
124
124
  getMigrate: () => import("../../index.js").MigrateFunction<import("../../index.js").DomainEntity<string>>;
125
125
  getActiveMode: () => DomainMode;
126
126
  getIsInitialized: () => boolean;
127
+ getIsViewMode: () => boolean;
127
128
  getComponentReaderIndexes: () => ComponentReaderIndexes;
128
129
  getStoreRuntimeDependencies: () => {
129
130
  componentReaderIndexes: ComponentReaderIndexes;
@@ -1 +1 @@
1
- import{createSelector as e}from"@salsita-ai/common/utils";import{Domain as t,createInitialDomainState as n}from"../../core/index.js";import{ActionSystem as o,DimensionSystem as i,NavigationSystem as a,RecipeCookerSystem as s,StoreSystem as r,UndoSystem as c}from"../../domain-context/index.js";import{BlenderProjections as l,CollisionProjections as m,CompositionProjections as d,ConstraintProjections as g,PositionProjections as f,ProjectedEntitiesProjections as u,SnappingProjections as p,ValidationProjections as y}from"../../projections/index.js";import{SketchingProjections as w}from"../../sketching/sketching-projections.js";import{requireAccessService as h}from"../access/index.js";import{prepareActionImplementations as S,prepareDomainExpressions as x}from"../spec/index.js";import{ComponentReader as C}from"./component-reader.js";import{DomainContext as D}from"./domain-context.js";let j=e.withTypes(),I=[],v={},P={role:"admin",data:v},M=e=>{if(null!==e)return e;throw Error("Cannot read the session role and data because the domain session context is not set. The session context is written into the domain runtime by the session lifecycle after authentication. Move this read into the loaded session lifecycle.")};export const createDomainContextSelectors=e=>{let{applicationType:A,getState:R,actions:E,specSelectors:T,accessSelectors:b,webComponentSelectors:$,domainDataSelectors:k,sessionContextSelectors:N,domainServicesSelectors:z,environmentSelectors:L,getExtensionSystems:V}=e,B="configurator"===A?T.selectConfiguratorSpec:T.selectAdminSpec,F="configurator"===A?b.selectConfiguratorRawAccessService:b.selectAdminRawAccessService,W=j.leaf(e=>e.domainContext[A]),_=j([W],e=>e.initializationContext),q=j([_],e=>{if(null===e)throw Error(`Domain lifecycle context is not available for ${A}! Read it from an active domain lifecycle.`);return e}),O=j([W],e=>e.executionMode),U=j([W],e=>e.isInitialized),G=j([B],e=>e.factory),H=j([B],e=>e.expressions),J=j([B],e=>e.actions),K=j([B],e=>e.actionImplementations),Q=j([J,K],S),X=j([B],e=>e.$entityReflections),Y=j([H,X],(e,t)=>x({expressions:e,$entityReflections:t})),Z=j([B],e=>e.modelVersion),ee=j([B],e=>e.aliasMap),et=j([B],e=>e.allowedRootEntityTypes),en=j([B],e=>e.entityReflections),eo=j([B],e=>e.migrate),ei=j([O,$.selectReadonly,F],(e,t,n)=>"finalize"===e?"finalize":h(A,n).accessInfo.viewMode||t?"read":"owner"),ea=j([F],e=>e?.configurationId??null),es="configurator"===A?N.selectSessionContext:j([],()=>P),er=j([es],e=>e?.role??null),ec=j([es],e=>e?.data??null),el=j([j.leaf(e=>e.loadedData)],e=>"configurator"===A?e.configuratorLoadedData:e.adminLoadedData),em=j([el],e=>e?.schemaIdentity??null),ed=j([el,G],(e,t)=>{if(null===e)return"coherent";let n=e.schemaIdentity;return void 0===n?"missing-stamp":n===t?"coherent":"schema-mismatch"}),eg=j([ea,er,ec,em,ed,F],(e,t,n,o,i,a)=>null===e||null===a||null===t||null===n||null===o||"coherent"!==i?null:{access:a.accessInfo.access,configurationId:e,role:t,schemaIdentity:o,sessionData:n}),ef=j([F,$.selectReadonly],(e,t)=>e?.accessInfo.viewMode===!0||t),eu=j([eg,_,U,ef],(e,t,n,o)=>{let i=null!==e&&null!==t&&n&&t.access===e.access&&t.configurationId===e.configurationId&&t.role===e.role&&t.schemaIdentity===e.schemaIdentity&&t.sessionData===e.sessionData;return{identity:e,isCurrent:i,isViewMode:o}}),ep=j([B],e=>e.componentOptics),ey=j([ep],e=>(e=>{let t=new Map,n=new Map,o=new Map,i=new Map;for(let n of e)for(let e of n.entityTypes){let o=t.get(e);o||(o=new Map,t.set(e,o));let a=o.get(n.componentType);if(a||(a=new Map,o.set(n.componentType,a)),a.has(n.instanceName))throw Error(`Component instance ${n.instanceName} already exists for type ${n.componentType.name} in entity ${e}. This is likely a bug in the component definition! InstanceNames must be unique within an entity and component.`);if(a.set(n.instanceName,n),"dynamic"===n.kind){let t=i.get(e);t||(t=new Map,i.set(e,t));let o=t.get(n.componentType)??[],a=o.find(e=>{var t;return t=n.instanceName,e.startsWith(`${t}_`)||t.startsWith(`${e}_`)});if(a)throw Error(`Cannot register dynamic component instance ${n.instanceName} for component ${n.componentType.name} on entity ${e} because it overlaps with dynamic instance ${a}. Rename one dynamic instance so compound names cannot be ambiguous.`);t.set(n.componentType,[...o,n.instanceName])}}for(let[e,i]of t.entries()){n.set(e,new Set(i.keys()));let t=new Map;for(let[n,a]of(o.set(e,t),i.entries()))t.set(n,new Set(a.keys()))}return{opticMap:t,allComponentTypes:n,allComponentInstanceNames:o,dynamicInstanceNames:i}})(e)),ew=j([ey,Y,et],(e,t,n)=>({componentReaderIndexes:e,domainExpressions:t,allowedRootEntityTypes:n})),eh=j([B],e=>e.navigationStates),eS=j([B],e=>e.viewStates),ex="configurator"===A?j([T.selectConfiguratorSpec],e=>e.toolStates):j([],()=>I),eC="configurator"===A?j([T.selectConfiguratorSpec],e=>e.exportStates):j([],()=>I),eD="configurator"===A?j([T.selectConfiguratorSpec],e=>e.createTransformers):j([],()=>void 0),ej=j([el],e=>{if(null===e)throw Error(`Loaded data is not available for ${A}! Loaded data is written after the configuration fetch succeeds and before the domain context initialization starts.`);return e}),eI=j([ej,G],(e,t)=>n(t.validateAndMigrateState(e.initialEntities,e.modelVersion),e.rootEntityType)),ev="configurator"===A?k.selectConfiguratorFrontendData:k.selectAdminFrontendData,eP="configurator"===A?k.selectConfiguratorBackendData:k.selectAdminBackendData,eM="configurator"===A?k.selectConfiguratorPublishedData:k.selectAdminPublishedData,eA="configurator"===A?j([N.selectSessionContext],e=>M(e).role):j([],()=>"admin"),eR="configurator"===A?j([N.selectSessionContext],e=>M(e).data):j([],()=>v),eE=j([ea,ei,eA,eR,ej,F],(e,t,n,o,i,a)=>({access:a?.accessInfo.access??null,configurationId:e,mode:t,role:n,schemaIdentity:i.schemaIdentity,sessionData:o})),eT=j([q],e=>e.mode),eb=j([q],e=>{let t=e.configurationId;if(null===t)throw Error(`Configuration id is not available for ${A}! Read it from an active interactive domain lifecycle.`);return t}),e$=j([q],e=>e.role),ek=j([q],e=>e.sessionData),eN=j([eT,e$,ek,ev,eP,eM,eo],(e,t,n,o,i,a,s)=>({mode:e,role:t,sessionData:n,frontendData:o,backendData:i,publishedData:a,migrate:s,domain:eL,componentReader:eV,positionProjections:eq,sketchingProjections:e_,collisionProjections:eO,constraintProjections:eG,snappingProjections:eU,projectedEntitiesProjections:eH})),ez={selectApplicationSpec:B,selectRawAccessService:F,selectDomainContextState:W,selectInitializationContext:_,selectActiveInitializationContext:q,selectExecutionMode:O,selectIsInitialized:U,selectFactory:G,selectSpecExpressions:H,select$SpecEntityReflections:X,selectDomainExpressions:Y,selectModelVersion:Z,selectAliasMap:ee,selectAllowedRootEntityTypes:et,selectEntityReflections:en,selectMigrate:eo,selectLatestMode:ei,selectLatestConfigurationId:ea,selectLatestSessionContext:es,selectLatestRoleOrNull:er,selectLatestSessionDataOrNull:ec,selectLatestSchemaIdentity:em,selectSchemaCoherence:ed,selectInitializationIdentity:eg,selectIsViewMode:ef,selectInitializationState:eu,selectComponentOptics:ep,selectComponentReaderIndexes:ey,selectStoreRuntimeDependencies:ew,selectNavigationStates:eh,selectViewStates:eS,selectToolStates:ex,selectExportStates:eC,selectCreateTransformers:eD,selectLatestLoadedData:el,selectLoadedData:ej,selectInitialDomainState:eI,selectFrontendData:ev,selectBackendData:eP,selectPublishedData:eM,selectLatestRole:eA,selectLatestSessionData:eR,selectNextInitializationContext:eE,selectActiveMode:eT,selectActiveConfigurationId:eb,selectActiveRole:e$,selectActiveSessionData:ek,selectExpressionContext:eN,getInitializationContext:()=>_(R()),getInitializationState:()=>eu(R()),getNextInitializationContext:()=>eE(R()),getLatestLoadedData:()=>el(R()),getSchemaCoherence:()=>ed(R()),getActiveConfigurationId:()=>eb(R()),getFactory:()=>G(R()),getDomainExpressions:()=>Y(R()),getActionDefinitions:()=>J(R()),getActionImplementations:()=>Q(R()),getModelVersion:()=>Z(R()),getAliasMap:()=>ee(R()),getAllowedRootEntityTypes:()=>et(R()),getEntityReflections:()=>en(R()),getMigrate:()=>eo(R()),getActiveMode:()=>eT(R()),getIsInitialized:()=>U(R()),getComponentReaderIndexes:()=>ey(R()),getStoreRuntimeDependencies:()=>ew(R()),getNavigationStates:()=>eh(R()),getViewStates:()=>eS(R()),getToolStates:()=>ex(R()),getExportStates:()=>eC(R()),getCreateTransformers:()=>eD(R()),getLoadedData:()=>ej(R()),getInitialDomainState:()=>eI(R()),getFrontendData:()=>ev(R()),getBackendData:()=>eP(R()),getPublishedData:()=>eM(R()),getActiveRole:()=>e$(R()),getActiveSessionData:()=>ek(R()),getDomain:()=>eL,getComponentReader:()=>eV,getCompositionProjections:()=>eB,getDimensionSystem:()=>eF,getValidationProjections:()=>eW,getSketchingProjections:()=>e_,getPositionProjections:()=>eq,getCollisionProjections:()=>eO,getSnappingProjections:()=>eU,getConstraintProjections:()=>eG,getProjectedEntitiesProjections:()=>eH,getStoreSystem:()=>eJ,getNavigationSystem:()=>eK,getUndoSystem:()=>eQ,getRecipeCookerSystem:()=>eX,getActionSystem:()=>eY,getBlenderProjections:()=>eZ,getExpressionContext:()=>eN(R()),getDomainSystems:function(){return e0},getDomainContext:function(){return e1}},eL=new t({selectors:ez}),eV=new C({selectors:ez}),eB=new d({selectors:ez}),eF=new i({selectors:ez}),eW=new y({selectors:ez}),e_=new w({selectors:ez}),eq=new f({selectors:ez}),eO=new m({selectors:ez}),eU=new p({selectors:ez}),eG=new g({selectors:ez}),eH=new u({selectors:ez}),eJ=new r({selectors:ez,domainServicesSelectors:z,environmentSelectors:L}),eK=new a({selectors:ez,domainServicesSelectors:z}),eQ=new c({selectors:ez}),eX=new s({selectors:ez}),eY=new o({selectors:ez}),eZ=new l({selectors:ez,domainServicesSelectors:z}),e0={domainContextSelectors:ez,domain:eL,componentReader:eV,compositionProjections:eB,blenderProjections:eZ,validationProjections:eW,storeSystem:eJ,navigationSystem:eK,dimensionSystem:eF,undoSystem:eQ,recipeCooker:eX,actionSystem:eY,sketchingProjections:e_,collisionProjections:eO,positionProjections:eq,snappingProjections:eU,projectedEntitiesProjections:eH,constraintProjections:eG},e1=new D({selectors:ez,actions:E,getExtensionSystems:V});return ez};
1
+ import{createSelector as e}from"@salsita-ai/common/utils";import{Domain as t,createInitialDomainState as n}from"../../core/index.js";import{ActionSystem as o,DimensionSystem as i,NavigationSystem as a,RecipeCookerSystem as s,StoreSystem as r,UndoSystem as c}from"../../domain-context/index.js";import{BlenderProjections as l,CollisionProjections as d,CompositionProjections as m,ConstraintProjections as g,PositionProjections as f,ProjectedEntitiesProjections as u,SnappingProjections as p,ValidationProjections as y}from"../../projections/index.js";import{SketchingProjections as w}from"../../sketching/sketching-projections.js";import{requireAccessService as h}from"../access/index.js";import{prepareActionImplementations as S,prepareDomainExpressions as x}from"../spec/index.js";import{ComponentReader as C}from"./component-reader.js";import{DomainContext as D}from"./domain-context.js";let j=e.withTypes(),I=[],v={},P={role:"admin",data:v},M=e=>{if(null!==e)return e;throw Error("Cannot read the session role and data because the domain session context is not set. The session context is written into the domain runtime by the session lifecycle after authentication. Move this read into the loaded session lifecycle.")};export const createDomainContextSelectors=e=>{let{applicationType:A,getState:R,actions:E,specSelectors:T,accessSelectors:b,webComponentSelectors:$,domainDataSelectors:k,sessionContextSelectors:N,domainServicesSelectors:z,environmentSelectors:L,getExtensionSystems:V}=e,B="configurator"===A?T.selectConfiguratorSpec:T.selectAdminSpec,F="configurator"===A?b.selectConfiguratorRawAccessService:b.selectAdminRawAccessService,W=j.leaf(e=>e.domainContext[A]),_=j([W],e=>e.initializationContext),q=j([_],e=>{if(null===e)throw Error(`Domain lifecycle context is not available for ${A}! Read it from an active domain lifecycle.`);return e}),O=j([W],e=>e.executionMode),U=j([W],e=>e.isInitialized),G=j([B],e=>e.factory),H=j([B],e=>e.expressions),J=j([B],e=>e.actions),K=j([B],e=>e.actionImplementations),Q=j([J,K],S),X=j([B],e=>e.$entityReflections),Y=j([H,X],(e,t)=>x({expressions:e,$entityReflections:t})),Z=j([B],e=>e.modelVersion),ee=j([B],e=>e.aliasMap),et=j([B],e=>e.allowedRootEntityTypes),en=j([B],e=>e.entityReflections),eo=j([B],e=>e.migrate),ei=j([O,$.selectReadonly,F],(e,t,n)=>"finalize"===e?"finalize":h(A,n).accessInfo.viewMode||t?"read":"owner"),ea=j([F],e=>e?.configurationId??null),es="configurator"===A?N.selectSessionContext:j([],()=>P),er=j([es],e=>e?.role??null),ec=j([es],e=>e?.data??null),el=j([j.leaf(e=>e.loadedData)],e=>"configurator"===A?e.configuratorLoadedData:e.adminLoadedData),ed=j([el],e=>e?.schemaIdentity??null),em=j([el,G],(e,t)=>{if(null===e)return"coherent";let n=e.schemaIdentity;return void 0===n?"missing-stamp":n===t?"coherent":"schema-mismatch"}),eg=j([ea,er,ec,ed,em,F],(e,t,n,o,i,a)=>null===e||null===a||null===t||null===n||null===o||"coherent"!==i?null:{access:a.accessInfo.access,configurationId:e,role:t,schemaIdentity:o,sessionData:n}),ef=j([F,$.selectReadonly],(e,t)=>e?.accessInfo.viewMode===!0||t),eu=j([eg,_,U,ef],(e,t,n,o)=>{let i=null!==e&&null!==t&&n&&t.access===e.access&&t.configurationId===e.configurationId&&t.role===e.role&&t.schemaIdentity===e.schemaIdentity&&t.sessionData===e.sessionData;return{identity:e,isCurrent:i,isViewMode:o}}),ep=j([B],e=>e.componentOptics),ey=j([ep],e=>(e=>{let t=new Map,n=new Map,o=new Map,i=new Map;for(let n of e)for(let e of n.entityTypes){let o=t.get(e);o||(o=new Map,t.set(e,o));let a=o.get(n.componentType);if(a||(a=new Map,o.set(n.componentType,a)),a.has(n.instanceName))throw Error(`Component instance ${n.instanceName} already exists for type ${n.componentType.name} in entity ${e}. This is likely a bug in the component definition! InstanceNames must be unique within an entity and component.`);if(a.set(n.instanceName,n),"dynamic"===n.kind){let t=i.get(e);t||(t=new Map,i.set(e,t));let o=t.get(n.componentType)??[],a=o.find(e=>{var t;return t=n.instanceName,e.startsWith(`${t}_`)||t.startsWith(`${e}_`)});if(a)throw Error(`Cannot register dynamic component instance ${n.instanceName} for component ${n.componentType.name} on entity ${e} because it overlaps with dynamic instance ${a}. Rename one dynamic instance so compound names cannot be ambiguous.`);t.set(n.componentType,[...o,n.instanceName])}}for(let[e,i]of t.entries()){n.set(e,new Set(i.keys()));let t=new Map;for(let[n,a]of(o.set(e,t),i.entries()))t.set(n,new Set(a.keys()))}return{opticMap:t,allComponentTypes:n,allComponentInstanceNames:o,dynamicInstanceNames:i}})(e)),ew=j([ey,Y,et],(e,t,n)=>({componentReaderIndexes:e,domainExpressions:t,allowedRootEntityTypes:n})),eh=j([B],e=>e.navigationStates),eS=j([B],e=>e.viewStates),ex="configurator"===A?j([T.selectConfiguratorSpec],e=>e.toolStates):j([],()=>I),eC="configurator"===A?j([T.selectConfiguratorSpec],e=>e.exportStates):j([],()=>I),eD="configurator"===A?j([T.selectConfiguratorSpec],e=>e.createTransformers):j([],()=>void 0),ej=j([el],e=>{if(null===e)throw Error(`Loaded data is not available for ${A}! Loaded data is written after the configuration fetch succeeds and before the domain context initialization starts.`);return e}),eI=j([ej,G],(e,t)=>n(t.validateAndMigrateState(e.initialEntities,e.modelVersion),e.rootEntityType)),ev="configurator"===A?k.selectConfiguratorFrontendData:k.selectAdminFrontendData,eP="configurator"===A?k.selectConfiguratorBackendData:k.selectAdminBackendData,eM="configurator"===A?k.selectConfiguratorPublishedData:k.selectAdminPublishedData,eA="configurator"===A?j([N.selectSessionContext],e=>M(e).role):j([],()=>"admin"),eR="configurator"===A?j([N.selectSessionContext],e=>M(e).data):j([],()=>v),eE=j([ea,ei,eA,eR,ej,F],(e,t,n,o,i,a)=>({access:a?.accessInfo.access??null,configurationId:e,mode:t,role:n,schemaIdentity:i.schemaIdentity,sessionData:o})),eT=j([q],e=>e.mode),eb=j([q],e=>{let t=e.configurationId;if(null===t)throw Error(`Configuration id is not available for ${A}! Read it from an active interactive domain lifecycle.`);return t}),e$=j([q],e=>e.role),ek=j([q],e=>e.sessionData),eN=j([eT,e$,ek,ev,eP,eM,eo],(e,t,n,o,i,a,s)=>({mode:e,role:t,sessionData:n,frontendData:o,backendData:i,publishedData:a,migrate:s,domain:eL,componentReader:eV,positionProjections:eq,sketchingProjections:e_,collisionProjections:eO,constraintProjections:eG,snappingProjections:eU,projectedEntitiesProjections:eH})),ez={selectApplicationSpec:B,selectRawAccessService:F,selectDomainContextState:W,selectInitializationContext:_,selectActiveInitializationContext:q,selectExecutionMode:O,selectIsInitialized:U,selectFactory:G,selectSpecExpressions:H,select$SpecEntityReflections:X,selectDomainExpressions:Y,selectModelVersion:Z,selectAliasMap:ee,selectAllowedRootEntityTypes:et,selectEntityReflections:en,selectMigrate:eo,selectLatestMode:ei,selectLatestConfigurationId:ea,selectLatestSessionContext:es,selectLatestRoleOrNull:er,selectLatestSessionDataOrNull:ec,selectLatestSchemaIdentity:ed,selectSchemaCoherence:em,selectInitializationIdentity:eg,selectIsViewMode:ef,selectInitializationState:eu,selectComponentOptics:ep,selectComponentReaderIndexes:ey,selectStoreRuntimeDependencies:ew,selectNavigationStates:eh,selectViewStates:eS,selectToolStates:ex,selectExportStates:eC,selectCreateTransformers:eD,selectLatestLoadedData:el,selectLoadedData:ej,selectInitialDomainState:eI,selectFrontendData:ev,selectBackendData:eP,selectPublishedData:eM,selectLatestRole:eA,selectLatestSessionData:eR,selectNextInitializationContext:eE,selectActiveMode:eT,selectActiveConfigurationId:eb,selectActiveRole:e$,selectActiveSessionData:ek,selectExpressionContext:eN,getInitializationContext:()=>_(R()),getInitializationState:()=>eu(R()),getNextInitializationContext:()=>eE(R()),getLatestLoadedData:()=>el(R()),getSchemaCoherence:()=>em(R()),getActiveConfigurationId:()=>eb(R()),getFactory:()=>G(R()),getDomainExpressions:()=>Y(R()),getActionDefinitions:()=>J(R()),getActionImplementations:()=>Q(R()),getModelVersion:()=>Z(R()),getAliasMap:()=>ee(R()),getAllowedRootEntityTypes:()=>et(R()),getEntityReflections:()=>en(R()),getMigrate:()=>eo(R()),getActiveMode:()=>eT(R()),getIsInitialized:()=>U(R()),getIsViewMode:()=>ef(R()),getComponentReaderIndexes:()=>ey(R()),getStoreRuntimeDependencies:()=>ew(R()),getNavigationStates:()=>eh(R()),getViewStates:()=>eS(R()),getToolStates:()=>ex(R()),getExportStates:()=>eC(R()),getCreateTransformers:()=>eD(R()),getLoadedData:()=>ej(R()),getInitialDomainState:()=>eI(R()),getFrontendData:()=>ev(R()),getBackendData:()=>eP(R()),getPublishedData:()=>eM(R()),getActiveRole:()=>e$(R()),getActiveSessionData:()=>ek(R()),getDomain:()=>eL,getComponentReader:()=>eV,getCompositionProjections:()=>eB,getDimensionSystem:()=>eF,getValidationProjections:()=>eW,getSketchingProjections:()=>e_,getPositionProjections:()=>eq,getCollisionProjections:()=>eO,getSnappingProjections:()=>eU,getConstraintProjections:()=>eG,getProjectedEntitiesProjections:()=>eH,getStoreSystem:()=>eJ,getNavigationSystem:()=>eK,getUndoSystem:()=>eQ,getRecipeCookerSystem:()=>eX,getActionSystem:()=>eY,getBlenderProjections:()=>eZ,getExpressionContext:()=>eN(R()),getDomainSystems:function(){return e0},getDomainContext:function(){return e1}},eL=new t({selectors:ez}),eV=new C({selectors:ez}),eB=new m({selectors:ez}),eF=new i({selectors:ez}),eW=new y({selectors:ez}),e_=new w({selectors:ez}),eq=new f({selectors:ez}),eO=new d({selectors:ez}),eU=new p({selectors:ez}),eG=new g({selectors:ez}),eH=new u({selectors:ez}),eJ=new r({selectors:ez,domainServicesSelectors:z,environmentSelectors:L}),eK=new a({selectors:ez,domainServicesSelectors:z}),eQ=new c({selectors:ez}),eX=new s({selectors:ez}),eY=new o({selectors:ez}),eZ=new l({selectors:ez,domainServicesSelectors:z}),e0={domainContextSelectors:ez,domain:eL,componentReader:eV,compositionProjections:eB,blenderProjections:eZ,validationProjections:eW,storeSystem:eJ,navigationSystem:eK,dimensionSystem:eF,undoSystem:eQ,recipeCooker:eX,actionSystem:eY,sketchingProjections:e_,collisionProjections:eO,positionProjections:eq,snappingProjections:eU,projectedEntitiesProjections:eH,constraintProjections:eG},e1=new D({selectors:ez,actions:E,getExtensionSystems:V});return ez};
@@ -417,6 +417,7 @@ export declare function createDomainRuntimeSlices<State extends DomainRuntimeSta
417
417
  getMigrate: () => import("../index.js").MigrateFunction<import("../index.js").DomainEntity<string>>;
418
418
  getActiveMode: () => import("../index.js").DomainMode;
419
419
  getIsInitialized: () => boolean;
420
+ getIsViewMode: () => boolean;
420
421
  getComponentReaderIndexes: () => import("./index.js").ComponentReaderIndexes;
421
422
  getStoreRuntimeDependencies: () => {
422
423
  componentReaderIndexes: import("./index.js").ComponentReaderIndexes;
@@ -526,6 +527,7 @@ export declare function createDomainRuntimeSlices<State extends DomainRuntimeSta
526
527
  getMigrate: () => import("../index.js").MigrateFunction<import("../index.js").DomainEntity<string>>;
527
528
  getActiveMode: () => import("../index.js").DomainMode;
528
529
  getIsInitialized: () => boolean;
530
+ getIsViewMode: () => boolean;
529
531
  getComponentReaderIndexes: () => import("./index.js").ComponentReaderIndexes;
530
532
  getStoreRuntimeDependencies: () => {
531
533
  componentReaderIndexes: import("./index.js").ComponentReaderIndexes;
@@ -1017,6 +1019,7 @@ export declare const createDomainRuntime: (props: Omit<Props<DomainRuntimeState>
1017
1019
  getMigrate: () => import("../index.js").MigrateFunction<import("../index.js").DomainEntity<string>>;
1018
1020
  getActiveMode: () => import("../index.js").DomainMode;
1019
1021
  getIsInitialized: () => boolean;
1022
+ getIsViewMode: () => boolean;
1020
1023
  getComponentReaderIndexes: () => import("./index.js").ComponentReaderIndexes;
1021
1024
  getStoreRuntimeDependencies: () => {
1022
1025
  componentReaderIndexes: import("./index.js").ComponentReaderIndexes;
@@ -1126,6 +1129,7 @@ export declare const createDomainRuntime: (props: Omit<Props<DomainRuntimeState>
1126
1129
  getMigrate: () => import("../index.js").MigrateFunction<import("../index.js").DomainEntity<string>>;
1127
1130
  getActiveMode: () => import("../index.js").DomainMode;
1128
1131
  getIsInitialized: () => boolean;
1132
+ getIsViewMode: () => boolean;
1129
1133
  getComponentReaderIndexes: () => import("./index.js").ComponentReaderIndexes;
1130
1134
  getStoreRuntimeDependencies: () => {
1131
1135
  componentReaderIndexes: import("./index.js").ComponentReaderIndexes;
@@ -10,6 +10,8 @@ export interface ImplementationErrorCollector {
10
10
  */
11
11
  readonly attempt: <T>(check: () => T, fallback: T) => T;
12
12
  readonly add: (error: ImplementationError) => void;
13
+ /** The errors recorded so far, in the order they were recorded. A host that reports them itself, such as the editor, reads them here instead of throwing them. */
14
+ readonly recorded: () => readonly ImplementationError[];
13
15
  /**
14
16
  * Throws the recorded errors as one {@link ImplementationErrors}, in the order they were
15
17
  * recorded. Does nothing when there are none.
@@ -1 +1 @@
1
- import{isImplementationError as r}from"./implementation-error.js";import{ImplementationErrors as t,isImplementationErrors as e}from"./implementation-errors.js";export const createImplementationErrorCollector=()=>{let o=[],n=r=>{o.push(r)};return{add:n,attempt:(t,o)=>{try{return t()}catch(t){if(e(t))return t.errors.forEach(n),o;if(r(t))return n(t),o;throw t}},throwIfAny:()=>{if(o.length>0)throw new t(o)}}};
1
+ import{isImplementationError as r}from"./implementation-error.js";import{ImplementationErrors as t,isImplementationErrors as e}from"./implementation-errors.js";export const createImplementationErrorCollector=()=>{let o=[],n=r=>{o.push(r)};return{add:n,attempt:(t,o)=>{try{return t()}catch(t){if(e(t))return t.errors.forEach(n),o;if(r(t))return n(t),o;throw t}},recorded:()=>[...o],throwIfAny:()=>{if(o.length>0)throw new t(o)}}};
@@ -1,7 +1,7 @@
1
1
  export * from './domain-runtime.js';
2
2
  export * from './domain-context/index.js';
3
3
  export * from './domain-services/index.js';
4
- export { type ImplementationErrorCode, type ImplementationErrorProps, type StartupStage, ImplementationError, ImplementationErrors, isImplementationError, isImplementationErrors, toImplementationErrors, } from './errors/index.js';
4
+ export { type ImplementationErrorCode, type ImplementationErrorCollector, type ImplementationErrorProps, type StartupStage, ImplementationError, ImplementationErrors, createImplementationErrorCollector, isImplementationError, isImplementationErrors, toImplementationErrors, } from './errors/index.js';
5
5
  export * from './spec/index.js';
6
6
  export * from './environment/index.js';
7
7
  export * from './access/index.js';
@@ -1 +1 @@
1
- export*from"./domain-runtime.js";export*from"./domain-context/index.js";export*from"./domain-services/index.js";export{ImplementationError,ImplementationErrors,isImplementationError,isImplementationErrors,toImplementationErrors}from"./errors/index.js";export*from"./spec/index.js";export*from"./environment/index.js";export*from"./access/index.js";export*from"./overrides/index.js";export*from"./loaded-data/index.js";export*from"./domain-data/index.js";export*from"./session-context/index.js";export*from"./web-component/index.js";
1
+ export*from"./domain-runtime.js";export*from"./domain-context/index.js";export*from"./domain-services/index.js";export{ImplementationError,ImplementationErrors,createImplementationErrorCollector,isImplementationError,isImplementationErrors,toImplementationErrors}from"./errors/index.js";export*from"./spec/index.js";export*from"./environment/index.js";export*from"./access/index.js";export*from"./overrides/index.js";export*from"./loaded-data/index.js";export*from"./domain-data/index.js";export*from"./session-context/index.js";export*from"./web-component/index.js";
@@ -4,6 +4,6 @@ export * from './actions.js';
4
4
  export * from './create-violation-expressions.js';
5
5
  export * from './initialize.js';
6
6
  export * from './memoize-expression.js';
7
- export { type PhoenixEntityElementProps, type PhoenixEntityElementRegistration, type PhoenixLayoutElementRegistration, type PhoenixIconRegistration, type AssistantFormElementRegistration, type ElementRegistration, type CustomPhoenixEntityElementProps, type PhoenixLayoutElementDefinition, type PhoenixEntityElementDefinition, type CreateCustomPhoenixLayoutElement, type CreateCustomPhoenixEntityElement, createPhoenixLayoutElement, createPhoenixEntityElement, createCustomPhoenixLayoutElement, createCustomPhoenixEntityElement, createAssistantFormElement, findAssistantFormElementErrors, resolveElementModule, resolveElementModules, type PhoenixHandlerDefinition, type SystemPhoenixHandlerDefinition, type PhoenixHandlerRegistration, type SystemPhoenixHandlerRegistration, type SystemPhoenixAsyncHandlerDefinition, type SystemPhoenixAsyncHandlerRegistration, type HandlerRegistration, type CreatePhoenixHandler, createPhoenixHandler, createSystemPhoenixHandler, createSystemPhoenixAsyncHandler, resolveHandlerModule, resolveHandlerModules, type ProjectModule, resolveActionModules, resolveComponentOpticModules, type ExpressionModule, resolveExpressionModules, resolveImportedTransformers, resolveTransformerModule, resolveTransformerModules, resolveInvariantModules, } from './module-checks/index.js';
7
+ export { type PhoenixEntityElementProps, type PhoenixEntityElementRegistration, type PhoenixLayoutElementRegistration, type PhoenixIconRegistration, type AssistantFormElementRegistration, type ElementRegistration, type CustomPhoenixEntityElementProps, type PhoenixLayoutElementDefinition, type PhoenixEntityElementDefinition, type CreateCustomPhoenixLayoutElement, type CreateCustomPhoenixEntityElement, createPhoenixLayoutElement, createPhoenixEntityElement, createCustomPhoenixLayoutElement, createCustomPhoenixEntityElement, createAssistantFormElement, findAssistantFormElementErrors, resolveElementModule, resolveElementModules, type PhoenixHandlerDefinition, type SystemPhoenixHandlerDefinition, type PhoenixHandlerRegistration, type SystemPhoenixHandlerRegistration, type SystemPhoenixAsyncHandlerDefinition, type SystemPhoenixAsyncHandlerRegistration, type HandlerRegistration, type CreatePhoenixHandler, createPhoenixHandler, createSystemPhoenixHandler, createSystemPhoenixAsyncHandler, resolveHandlerModule, resolveHandlerModules, type ProjectModule, resolveActionModules, resolveComponentOpticModules, type ExpressionModule, resolveExpressionModules, type ValuedExpressions, mergeExpressionModules, resolveImportedTransformers, resolveTransformerModule, resolveTransformerModules, resolveInvariantModules, } from './module-checks/index.js';
8
8
  export * from './prepare-action-implementations.js';
9
9
  export * from './prepare-domain-expressions.js';
@@ -1 +1 @@
1
- export*from"./selectors.js";export*from"./actions.js";export*from"./create-violation-expressions.js";export*from"./initialize.js";export*from"./memoize-expression.js";export{createPhoenixLayoutElement,createPhoenixEntityElement,createCustomPhoenixLayoutElement,createCustomPhoenixEntityElement,createAssistantFormElement,findAssistantFormElementErrors,resolveElementModule,resolveElementModules,createPhoenixHandler,createSystemPhoenixHandler,createSystemPhoenixAsyncHandler,resolveHandlerModule,resolveHandlerModules,resolveActionModules,resolveComponentOpticModules,resolveExpressionModules,resolveImportedTransformers,resolveTransformerModule,resolveTransformerModules,resolveInvariantModules}from"./module-checks/index.js";export*from"./prepare-action-implementations.js";export*from"./prepare-domain-expressions.js";
1
+ export*from"./selectors.js";export*from"./actions.js";export*from"./create-violation-expressions.js";export*from"./initialize.js";export*from"./memoize-expression.js";export{createPhoenixLayoutElement,createPhoenixEntityElement,createCustomPhoenixLayoutElement,createCustomPhoenixEntityElement,createAssistantFormElement,findAssistantFormElementErrors,resolveElementModule,resolveElementModules,createPhoenixHandler,createSystemPhoenixHandler,createSystemPhoenixAsyncHandler,resolveHandlerModule,resolveHandlerModules,resolveActionModules,resolveComponentOpticModules,resolveExpressionModules,mergeExpressionModules,resolveImportedTransformers,resolveTransformerModule,resolveTransformerModules,resolveInvariantModules}from"./module-checks/index.js";export*from"./prepare-action-implementations.js";export*from"./prepare-domain-expressions.js";
@@ -4,6 +4,7 @@ export { findAssistantFormElementErrors } from './find-assistant-form-element-er
4
4
  export { type ProjectModule } from './project-modules.js';
5
5
  export { resolveActionModules } from './resolve-action-modules.js';
6
6
  export { resolveComponentOpticModules } from './resolve-component-optic-modules.js';
7
+ export { type ValuedExpressions, mergeExpressionModules } from './merge-expression-modules.js';
7
8
  export { type ExpressionModule, resolveExpressionModules } from './resolve-expression-modules.js';
8
9
  export { resolveImportedTransformers, resolveTransformerModule, resolveTransformerModules, } from './resolve-imported-transformers.js';
9
10
  export { type AnyInvariant, resolveInvariantModules } from './resolve-invariant-modules.js';
@@ -1 +1 @@
1
- export{createPhoenixLayoutElement,createPhoenixEntityElement,createCustomPhoenixLayoutElement,createCustomPhoenixEntityElement,createAssistantFormElement,resolveElementModule,resolveElementModules}from"./element-registration.js";export{createPhoenixHandler,createSystemPhoenixHandler,createSystemPhoenixAsyncHandler,resolveHandlerModule,resolveHandlerModules}from"./handler-registration.js";export{findAssistantFormElementErrors}from"./find-assistant-form-element-errors.js";export{resolveActionModules}from"./resolve-action-modules.js";export{resolveComponentOpticModules}from"./resolve-component-optic-modules.js";export{resolveExpressionModules}from"./resolve-expression-modules.js";export{resolveImportedTransformers,resolveTransformerModule,resolveTransformerModules}from"./resolve-imported-transformers.js";export{resolveInvariantModules}from"./resolve-invariant-modules.js";
1
+ export{createPhoenixLayoutElement,createPhoenixEntityElement,createCustomPhoenixLayoutElement,createCustomPhoenixEntityElement,createAssistantFormElement,resolveElementModule,resolveElementModules}from"./element-registration.js";export{createPhoenixHandler,createSystemPhoenixHandler,createSystemPhoenixAsyncHandler,resolveHandlerModule,resolveHandlerModules}from"./handler-registration.js";export{findAssistantFormElementErrors}from"./find-assistant-form-element-errors.js";export{resolveActionModules}from"./resolve-action-modules.js";export{resolveComponentOpticModules}from"./resolve-component-optic-modules.js";export{mergeExpressionModules}from"./merge-expression-modules.js";export{resolveExpressionModules}from"./resolve-expression-modules.js";export{resolveImportedTransformers,resolveTransformerModule,resolveTransformerModules}from"./resolve-imported-transformers.js";export{resolveInvariantModules}from"./resolve-invariant-modules.js";
@@ -0,0 +1,23 @@
1
+ import type { AnonymousExpression, AnyExpressions } from '../../../core/index.js';
2
+ import { type ImplementationErrorCollector } from '../../errors/index.js';
3
+ import { type ProjectModule } from './project-modules.js';
4
+ type AnyAnonymousExpression = AnonymousExpression<any, any, any, any, any, any, unknown>;
5
+ type AliasMap = Readonly<Record<string, readonly string[]>>;
6
+ /** The expression names that already have a value, by entity type, so no project file may define them. */
7
+ export type ValuedExpressions = ReadonlyMap<string, ReadonlySet<string>>;
8
+ /** Whether a file's default export has the shape of the expressions folder contract. */
9
+ export declare const isExpressionExport: (value: unknown) => value is Record<string, Record<string, AnyAnonymousExpression>>;
10
+ /**
11
+ * Merges the `src/expressions/` files (or `src/admin/expressions/`) into the expressions of each
12
+ * entity type. It checks each file against the folder contract, rejects an expression that two
13
+ * files, or two keys of one file, define for one entity type after the aliases of `aliasMap` are
14
+ * expanded, and rejects an expression listed in `valued`, which the application gives a value
15
+ * already. Each accepted expression gets its `origin`: its name and the entity type or alias the
16
+ * file keys it by.
17
+ *
18
+ * Each file is checked on its own: a wrong file is recorded in `errors` with all its conflicts and
19
+ * left out, and the files after it still merge. Without `errors`, everything recorded is thrown at
20
+ * the end as one `ImplementationErrors`.
21
+ */
22
+ export declare const mergeExpressionModules: (modules: readonly ProjectModule[], aliasMap: AliasMap, errors?: ImplementationErrorCollector, valued?: ValuedExpressions) => AnyExpressions;
23
+ export {};
@@ -0,0 +1 @@
1
+ import{ImplementationError as e,ImplementationErrors as o,createImplementationErrorCollector as t}from"../../errors/index.js";import{SHARED_FOLDER_HINT as i,createContractError as n,isRecord as r}from"./project-modules.js";let s={expected:"an object of expressions keyed by entity type or alias, then by expression name",fix:`Create it with phx.domain.implementCustomExpressions({ ... }) (phx.domain.admin.implementCustomExpressions({ ... }) under src/admin/), ${i}.`},a=e=>r(e)&&"function"==typeof e.evaluate,p=e=>r(e)&&Object.values(e).every(a);export const isExpressionExport=e=>r(e)&&Object.values(e).every(p);let l=(o,t,i)=>new e({code:"DUPLICATE_DEFINITION",origin:o,problem:`Duplicate expression ${t}`,fix:i}),d=(e,t,i,r)=>{if(!isExpressionExport(e.exports))throw n(e,s,e.exports);let a=[],p=new Map,d=[];for(let[o,n]of Object.entries(e.exports))for(let s of t[o]??[o])for(let[t,f]of Object.entries(n)){let n=`${s}.${t}`,h=p.get(n),m=i.get(n);r.get(s)?.has(t)?d.push(l(e.origin,n,"The application already gives it a value (an $eval, $msg or read in the spec, a relation, the $violations of its invariants, or a built-in expression of the SDK), so this implementation would be ignored. Remove it from the file, or declare the expression in the spec with a type and no value.")):void 0!==h?d.push(l(e.origin,n,`The file defines it on both ${h} and ${o}, so its value would depend on the order the definitions are merged in. Define it once, on the alias or on the entity type.`)):void 0!==m&&d.push(l(e.origin,n,`It is also defined in ${m}, so its value would depend on file order. Keep one definition and remove the other.`)),p.set(n,o),a.push({key:n,entityType:s,typeOrAlias:o,name:t,expression:f})}if(d.length>0)throw new o(d);return a};export const mergeExpressionModules=(e,o,i,n=new Map)=>{let r=i??t(),s=new Map,a={};for(let t of e)for(let{key:e,entityType:i,typeOrAlias:p,name:l,expression:f}of r.attempt(()=>d(t,o,s,n),[]))s.set(e,t.origin),a[i]={...a[i],[l]:{...f,origin:{name:l,typeOrAlias:p}}};return void 0===i&&r.throwIfAny(),a};
@@ -1,5 +1,5 @@
1
1
  import type { AnonymousExpression } from '../../../core/index.js';
2
- import { type ProjectModule } from './project-modules.js';
2
+ import type { ProjectModule } from './project-modules.js';
3
3
  /** The expressions of one validated expression file, keyed by entity type or alias, then by expression name. */
4
4
  export interface ExpressionModule {
5
5
  readonly origin: string;
@@ -7,9 +7,8 @@ export interface ExpressionModule {
7
7
  }
8
8
  type AnyAnonymousExpression = AnonymousExpression<any, any, any, any, any, any, unknown>;
9
9
  /**
10
- * Validates the `src/expressions/` files and rejects an expression that two files define for the
11
- * same entity type. Merging stays with the caller, because the domain builder and the editor expand
12
- * aliases at different points; within one file the builder's own duplicate check applies.
10
+ * Validates the `src/expressions/` files with the checks of {@link mergeExpressionModules}, throws
11
+ * everything they find as one `ImplementationErrors`, and returns each file on its own, unmerged.
13
12
  */
14
13
  export declare const resolveExpressionModules: (modules: readonly ProjectModule[], aliasMap: Readonly<Record<string, readonly string[]>>) => readonly ExpressionModule[];
15
14
  export {};
@@ -1 +1 @@
1
- import{SHARED_FOLDER_HINT as e,createContractError as o,isRecord as t}from"./project-modules.js";let i={expected:"an object of expressions keyed by entity type or alias, then by expression name",fix:`Create it with phx.domain.implementCustomExpressions({ ... }) (phx.domain.admin.implementCustomExpressions({ ... }) under src/admin/), ${e}.`},r=e=>t(e)&&"function"==typeof e.evaluate,n=e=>t(e)&&Object.values(e).every(r);export const resolveExpressionModules=(e,r)=>{let s=new Map;return e.map(e=>{let p;if(!(t(p=e.exports)&&Object.values(p).every(n)))throw o(e,i,e.exports);for(let[o,t]of Object.entries(e.exports))for(let i of r[o]??[o])for(let o of Object.keys(t)){let t=`${i}.${o}`,r=s.get(t);if(void 0!==r&&r!==e.origin)throw Error(`Duplicate expression ${t}: it is defined in both ${r} and ${e.origin}, which would make its value depend on file order. Keep one definition and remove the other.`);s.set(t,e.origin)}return{origin:e.origin,expressions:e.exports}})};
1
+ import{isExpressionExport as e,mergeExpressionModules as o}from"./merge-expression-modules.js";export const resolveExpressionModules=(s,r)=>(o(s,r),s.flatMap(o=>e(o.exports)?[{origin:o.origin,expressions:o.exports}]:[]));
@@ -414,6 +414,7 @@ export declare const createMockDomainRuntime: <ENTITIES extends DomainEntity<str
414
414
  getMigrate: () => import("../index.js").MigrateFunction<DomainEntity<string>>;
415
415
  getActiveMode: () => import("../index.js").DomainMode;
416
416
  getIsInitialized: () => boolean;
417
+ getIsViewMode: () => boolean;
417
418
  getComponentReaderIndexes: () => import("../index.js").ComponentReaderIndexes;
418
419
  getStoreRuntimeDependencies: () => {
419
420
  componentReaderIndexes: import("../index.js").ComponentReaderIndexes;
@@ -523,6 +524,7 @@ export declare const createMockDomainRuntime: <ENTITIES extends DomainEntity<str
523
524
  getMigrate: () => import("../index.js").MigrateFunction<DomainEntity<string>>;
524
525
  getActiveMode: () => import("../index.js").DomainMode;
525
526
  getIsInitialized: () => boolean;
527
+ getIsViewMode: () => boolean;
526
528
  getComponentReaderIndexes: () => import("../index.js").ComponentReaderIndexes;
527
529
  getStoreRuntimeDependencies: () => {
528
530
  componentReaderIndexes: import("../index.js").ComponentReaderIndexes;
@@ -1 +1 @@
1
- import{jsx as e}from"react/jsx-runtime";import r from"lodash-es/debounce.js";import t from"promise-queue";import{createContext as o,useCallback as n,useContext as i,useEffect as s,useMemo as a,useRef as c,useState as m}from"react";import{match as l}from"ts-pattern";import{ApplicationRuntime as p,BinaryFile as u,RawProjectFiles as d,RuntimeReferenceStore as g,TextFile as f,buildPhoenixDefinitions as S,isConfiguratorModelSchemaCompatible as v,isTextFile as y,parseApplicationFiles as E}from"#package/application-spec";import{findActionImplementationConflicts as h,getAllPhxDefinitions as x}from"#package/domain";import{useApplicationRuntime as A,useMountGuard as C}from"#package/react-sdk";import{useEditorConnection as D}from"../services/EditorConnectionContext.js";import{trpc as I}from"../services/trpc.js";import{applyRuntimeReset as N,applySpecUpdate as w,prepareRuntimeRefresh as P,prepareRuntimeReset as _}from"./apply-spec-update.js";import{useDiagnostics as R}from"./use-diagnostics.js";import{useImplementationFiles as j}from"./use-implementation-files.js";import{getWasmSwcParsers as L}from"./wasm-swc-parsers.js";let k=o(null),T={debug:e=>console.debug(e)},M=e=>e instanceof Error?e.message:String(e);export const DomainSpecProvider=o=>{let{children:i,domainSpec:O,initialRawProjectFiles:b}=o,[$,F]=m(a(()=>O?[{fileName:"domain.yaml",content:O}]:b?b.files.filter(y).map(e=>({fileName:e.name,content:e.content})):[],[O,b])),[z,H]=m(null),q=a(()=>new g,[]),G=a(()=>S(x()),[]),U=c(null),Q=A(),{getImplementationFiles:B}=j(),{diagnostics:V,unreadDiagnosticCount:X,setDiagnostics:Y,pushDiagnostic:Z,clearDiagnostics:J,markDiagnosticsRead:K}=R(),W=a(()=>new t(1,1/0),[]),ee=c(0),er=c(null),{mutateAsync:et}=I.requestSpecFiles.useMutation(),{mutateAsync:eo}=I.save.useMutation(),en=C(),{localMode:ei,connectionStatus:es}=D(),{data:ea}=I.getEditorConfig.useQuery(void 0,{enabled:!ei&&"connected"===es}),ec=ei||ea?.specSync===!0,em=$.length>0?$:void 0,el=a(()=>$.map(e=>e.fileName),[$]),ep=a(()=>r(async e=>{if(!ei&&"connected"===es&&0!==e.length)try{await eo(e.map(e=>({fileName:e.fileName,content:e.content})))}catch(e){console.error("[DomainSpecContext] Failed to save files to disk:",e)}},1e3),[ei,es,eo]);s(()=>()=>{ep.cancel()},[ep]);let eu=n(()=>{H(null)},[]),ed=n(async(e,r)=>{F(t=>{let o=t.find(r=>r.fileName===e)?t.map(t=>t.fileName===e?{...t,content:r}:t):[...t,{fileName:e,content:r}];return ep(o),o})},[ep]),eg=n(async(e,r)=>{let t,o,n=()=>en()&&ee.current===r;if(!n())return;let i=d(e.rawProjectFiles.files.map(e=>l(e).with({kind:"text"},e=>f(e.name,e.content)).with({kind:"binary"},e=>u(e.name)).exhaustive()));F(i.files.filter(y).map(e=>({fileName:e.name,content:e.content})));try{t=await L()}catch(e){if(!n())return;Y([{code:"MODULE_ANALYZER_UNAVAILABLE",message:`The editor's module analyzer failed to load: ${e instanceof Error?e.message:String(e)}`,severity:"error",source:"spec",path:[]}]);return}if(!n())return;let s=E({rawProjectFiles:i,phxDefinitions:G},{analyzer:t.analyzer,evalExpressionParser:t.evalExpressionParser,referenceStore:q,logger:T});if(console.info(`[DomainSpecContext] Spec parsed: ${s.ok?"ok":"error"}, ${s.diagnostics.length} diagnostics`),!s.ok)return void Y([...s.errors,...s.diagnostics].map(e=>({...e,source:"spec"})));J();let{applicationSpec:a}=s.value,c=await B({application:s.value,projectRoot:e.projectRoot});if(!n())return;if(c.errors.length>0)return void Y(c.errors.map(e=>({code:e.code,message:e.message,severity:"error",source:"reload",path:[]})));let m=h([...a.configurator.actions.values()].map(e=>String(e.name)),c.actionImplementations??Q.getState().spec.configurator.actionImplementations);if(m.extra.length>0&&console.error(`[DomainSpecContext] Action implementations without a declaration: ${m.extra.join(", ")}`),m.missing.length>0){let e=`Missing action implementations: ${m.missing.join(", ")}. Add each to a default export of phx.domain.implementActions({ ... }) in src/actions/.`;console.error(`[DomainSpecContext] ${e}`),Z({code:"MISSING_ACTION_IMPLEMENTATIONS",message:e,severity:"error",source:"runtime"});return}let g=p(a,q,c.implementations,c.importedTransformers,c.invariantImplementations,c.adminImplementations);if(!g.ok){let e=`Missing expression implementations: ${g.missingExpressions.map(e=>`${e.entityType}.${e.exprName}`).join(", ")}`;console.error(`[DomainSpecContext] ${e}`),Z({code:"MISSING_EXPRESSION_IMPLEMENTATIONS",message:e,severity:"error",source:"runtime"});return}let{runtime:S}=g,x=null===U.current||v(U.current.configurator,a.configurator),A=Q.selectors.environment.getPersistenceConfig();if(!x){let e;if("server"===A.type)return void Z({code:"HOT_RELOAD_MODEL_CHANGE_REQUIRES_RESTART",message:"Domain model changes require an application restart and were not applied.",severity:"error",source:"runtime"});if(!Q.selectors.domainContext.configurator.getInitializationState().isCurrent)return void Q.selectors.domainServices.getLogger().debug("[DomainSpecContext] Skipping the model reset because no configurator session is initialized; the change applies once a session loads under the new spec.");try{e=_({runtime:S,implementationFiles:c,previousSpec:Q.getState().spec})}catch(e){Z({code:"HOT_RELOAD_PREPARE_FAILED",message:M(e),severity:"error",source:"runtime"});return}for(let r of(Q.selectors.domainServices.getLogger().debug("[DomainSpecContext] Reseeding the reset session directly from the spec preset; onPresetLoadedHandler and ProductSelected analytics are intentionally skipped."),N(Q,e,Q.selectors.domainApplicationContext.configurator.getConfigurationPersistSystem().revisionId$.value),U.current=a,e.implementationErrors))Z({code:r.code,message:r.message,severity:"error",source:"runtime"});return}try{o=P({runtime:S,implementationFiles:c,previousSpec:Q.getState().spec})}catch(e){Z({code:"HOT_RELOAD_PREPARE_FAILED",message:M(e),severity:"error",source:"runtime"});return}if(n())for(let e of(w(Q,o),U.current=a,o.implementationErrors))Z({code:e.code,message:e.message,severity:"error",source:"runtime"})},[Q,B,en,G,Z,q,Y,J]),ef=c(null),eS=n(e=>{let r=ee.current+1;ee.current=r,er.current={data:e,generation:r},W.add(async()=>{let e=er.current;e&&e.data!==ef.current&&(er.current=null,ef.current=e.data,await eg(e.data,e.generation))})},[eg,W]);I.onSpecChange.useSubscription(void 0,{enabled:!ei&&ec,onData:eS}),s(()=>{!ei&&ec&&et().catch(()=>{console.warn("[DomainSpecContext] Failed to request spec files")})},[et,ei,ec]);let ev=a(()=>({files:em,fileNames:el,updateFile:ed,parsing:!1,parseError:z,clearParseError:eu,diagnostics:V,clearDiagnostics:J,unreadDiagnosticCount:X,markDiagnosticsRead:K}),[em,el,ed,z,eu,V,J,X,K]);return e(k.Provider,{value:ev,children:i})};export const useDomainSpecContext=()=>{let e=i(k);if(null===e)throw Error("useDomainSpecContext must be used within DomainSpecProvider");return e};
1
+ import{jsx as e}from"react/jsx-runtime";import r from"lodash-es/debounce.js";import t from"promise-queue";import{createContext as o,useCallback as n,useContext as i,useEffect as s,useMemo as a,useRef as c,useState as m}from"react";import{match as l}from"ts-pattern";import{ApplicationRuntime as u,BinaryFile as p,RawProjectFiles as d,RuntimeReferenceStore as g,TextFile as f,buildPhoenixDefinitions as v,isConfiguratorModelSchemaCompatible as S,isTextFile as h,parseApplicationFiles as y}from"#package/application-spec";import{createImplementationErrorCollector as E,findActionImplementationConflicts as x,getAllPhxDefinitions as A}from"#package/domain";import{useApplicationRuntime as C,useMountGuard as D}from"#package/react-sdk";import{useEditorConnection as w}from"../services/EditorConnectionContext.js";import{trpc as N}from"../services/trpc.js";import{applyRuntimeReset as P,applySpecUpdate as R,prepareRuntimeRefresh as _,prepareRuntimeReset as j}from"./apply-spec-update.js";import{useDiagnostics as I}from"./use-diagnostics.js";import{useImplementationFiles as L}from"./use-implementation-files.js";import{getWasmSwcParsers as k}from"./wasm-swc-parsers.js";let b=o(null),M={debug:e=>console.debug(e)},O=e=>e instanceof Error?e.message:String(e);export const DomainSpecProvider=o=>{let{children:i,domainSpec:T,initialRawProjectFiles:$}=o,[F,z]=m(a(()=>T?[{fileName:"domain.yaml",content:T}]:$?$.files.filter(h).map(e=>({fileName:e.name,content:e.content})):[],[T,$])),[H,q]=m(null),U=a(()=>new g,[]),G=a(()=>v(A()),[]),Q=c(null),B=C(),{getImplementationFiles:V}=L(),{diagnostics:Y,unreadDiagnosticCount:Z,setDiagnostics:J,pushDiagnostic:K,clearDiagnostics:W,markDiagnosticsRead:X}=I(),ee=a(()=>new t(1,1/0),[]),er=c(0),et=c(null),{mutateAsync:eo}=N.requestSpecFiles.useMutation(),{mutateAsync:en}=N.save.useMutation(),ei=D(),{localMode:es,connectionStatus:ea}=w(),{data:ec}=N.getEditorConfig.useQuery(void 0,{enabled:!es&&"connected"===ea}),em=es||ec?.specSync===!0,el=F.length>0?F:void 0,eu=a(()=>F.map(e=>e.fileName),[F]),ep=a(()=>r(async e=>{if(!es&&"connected"===ea&&0!==e.length)try{await en(e.map(e=>({fileName:e.fileName,content:e.content})))}catch(e){console.error("[DomainSpecContext] Failed to save files to disk:",e)}},1e3),[es,ea,en]);s(()=>()=>{ep.cancel()},[ep]);let ed=n(()=>{q(null)},[]),eg=n(async(e,r)=>{z(t=>{let o=t.find(r=>r.fileName===e)?t.map(t=>t.fileName===e?{...t,content:r}:t):[...t,{fileName:e,content:r}];return ep(o),o})},[ep]),ef=n(async(e,r)=>{let t,o,n=()=>ei()&&er.current===r;if(!n())return;let i=d(e.rawProjectFiles.files.map(e=>l(e).with({kind:"text"},e=>f(e.name,e.content)).with({kind:"binary"},e=>p(e.name)).exhaustive()));z(i.files.filter(h).map(e=>({fileName:e.name,content:e.content})));try{t=await k()}catch(e){if(!n())return;J([{code:"MODULE_ANALYZER_UNAVAILABLE",message:`The editor's module analyzer failed to load: ${e instanceof Error?e.message:String(e)}`,severity:"error",source:"spec",path:[]}]);return}if(!n())return;let s=y({rawProjectFiles:i,phxDefinitions:G},{analyzer:t.analyzer,evalExpressionParser:t.evalExpressionParser,referenceStore:U,logger:M});if(console.info(`[DomainSpecContext] Spec parsed: ${s.ok?"ok":"error"}, ${s.diagnostics.length} diagnostics`),!s.ok)return void J([...s.errors,...s.diagnostics].map(e=>({...e,source:"spec"})));W();let{applicationSpec:a}=s.value,c=await V({application:s.value,projectRoot:e.projectRoot});if(!n())return;if(c.errors.length>0)return void J(c.errors.map(e=>({code:e.code,message:e.message,severity:"error",source:"reload",path:[]})));let m=x([...a.configurator.actions.values()].map(e=>String(e.name)),c.actionImplementations??B.getState().spec.configurator.actionImplementations);if(m.extra.length>0&&console.error(`[DomainSpecContext] Action implementations without a declaration: ${m.extra.join(", ")}`),m.missing.length>0){let e=`Missing action implementations: ${m.missing.join(", ")}. Add each to a default export of phx.domain.implementActions({ ... }) in src/actions/.`;console.error(`[DomainSpecContext] ${e}`),K({code:"MISSING_ACTION_IMPLEMENTATIONS",message:e,severity:"error",source:"runtime"});return}let g=E(),v=u(a,U,c.expressionModules,c.importedTransformers,c.invariantImplementations,c.adminExpressionModules,void 0,void 0,void 0,g);for(let e of g.recorded())console.error(`[DomainSpecContext] ${e.message}`),K({code:e.code,message:e.message,severity:"error",source:"runtime"});if(!v.ok)return;let{runtime:A}=v,C=null===Q.current||S(Q.current.configurator,a.configurator),D=B.selectors.environment.getPersistenceConfig();if(!C){let e;if("server"===D.type)return void K({code:"HOT_RELOAD_MODEL_CHANGE_REQUIRES_RESTART",message:"Domain model changes require an application restart and were not applied.",severity:"error",source:"runtime"});if(!B.selectors.domainContext.configurator.getInitializationState().isCurrent)return void B.selectors.domainServices.getLogger().debug("[DomainSpecContext] Skipping the model reset because no configurator session is initialized; the change applies once a session loads under the new spec.");try{e=j({runtime:A,implementationFiles:c,previousSpec:B.getState().spec})}catch(e){K({code:"HOT_RELOAD_PREPARE_FAILED",message:O(e),severity:"error",source:"runtime"});return}for(let r of(B.selectors.domainServices.getLogger().debug("[DomainSpecContext] Reseeding the reset session directly from the spec preset; onPresetLoadedHandler and ProductSelected analytics are intentionally skipped."),P(B,e,B.selectors.domainApplicationContext.configurator.getConfigurationPersistSystem().revisionId$.value),Q.current=a,e.implementationErrors))K({code:r.code,message:r.message,severity:"error",source:"runtime"});return}try{o=_({runtime:A,implementationFiles:c,previousSpec:B.getState().spec})}catch(e){K({code:"HOT_RELOAD_PREPARE_FAILED",message:O(e),severity:"error",source:"runtime"});return}if(n())for(let e of(R(B,o),Q.current=a,o.implementationErrors))K({code:e.code,message:e.message,severity:"error",source:"runtime"})},[B,V,ei,G,K,U,J,W]),ev=c(null),eS=n(e=>{let r=er.current+1;er.current=r,et.current={data:e,generation:r},ee.add(async()=>{let e=et.current;e&&e.data!==ev.current&&(et.current=null,ev.current=e.data,await ef(e.data,e.generation))})},[ef,ee]);N.onSpecChange.useSubscription(void 0,{enabled:!es&&em,onData:eS}),s(()=>{!es&&em&&eo().catch(()=>{console.warn("[DomainSpecContext] Failed to request spec files")})},[eo,es,em]);let eh=a(()=>({files:el,fileNames:eu,updateFile:eg,parsing:!1,parseError:H,clearParseError:ed,diagnostics:Y,clearDiagnostics:W,unreadDiagnosticCount:Z,markDiagnosticsRead:X}),[el,eu,eg,H,ed,Y,W,Z,X]);return e(b.Provider,{value:eh,children:i})};export const useDomainSpecContext=()=>{let e=i(b);if(null===e)throw Error("useDomainSpecContext must be used within DomainSpecProvider");return e};
@@ -1,4 +1,4 @@
1
- import type { Application, ExpressionImplementations, InvariantImplementations } from '#package/application-spec';
1
+ import type { Application, InvariantImplementations } from '#package/application-spec';
2
2
  import { type AnyActionImplementations, type DomainComponentOptic, type DomainEntity, type ElementRegistration, type HandlerRegistration, type ImportedTransformer, type ProjectModule, type SystemComponentTypeConstraint } from '#package/domain';
3
3
  type RuntimeData = Record<string, unknown>;
4
4
  type RuntimeEntity = DomainEntity<string>;
@@ -21,15 +21,17 @@ export interface ReloadError {
21
21
  /**
22
22
  * The freshly reloaded (or cached) implementation files needed to build an `ApplicationRuntime`.
23
23
  *
24
- * `implementations`, `adminImplementations`, `invariantImplementations`, `importedTransformers` and `customComponentOptics` always contain the latest
24
+ * `expressionModules` and `adminExpressionModules` are the expression files as imported, unchecked:
25
+ * `ApplicationRuntime` checks and merges them with the aliases of the spec being edited.
26
+ * `expressionModules`, `adminExpressionModules`, `invariantImplementations`, `importedTransformers` and `customComponentOptics` always contain the latest
25
27
  * successfully loaded values. So does `actionImplementations`, which is `null` only until the first successful load: a round
26
28
  * that loaded them may be dropped before it is applied, and the next round must still carry them.
27
29
  * `handlers`/`elements` are `null` when their category did not change this round.
28
30
  */
29
31
  export interface ImplementationFiles {
30
- readonly implementations: ExpressionImplementations;
32
+ readonly expressionModules: readonly ProjectModule[];
31
33
  readonly actionImplementations: AnyActionImplementations | null;
32
- readonly adminImplementations?: ExpressionImplementations;
34
+ readonly adminExpressionModules?: readonly ProjectModule[];
33
35
  readonly invariantImplementations: InvariantImplementations;
34
36
  readonly importedTransformers: readonly ImportedTransformer[];
35
37
  readonly customComponentOptics: readonly ReloadedComponentOptic[] | null;
@@ -41,13 +43,6 @@ export interface GetImplementationFilesProps {
41
43
  readonly application: Application;
42
44
  readonly projectRoot: string;
43
45
  }
44
- type ResolvedExpressions = ExpressionImplementations;
45
- /**
46
- * Validates the expression modules through the resolver the domain builder uses, then expands their
47
- * aliases. The expansion stays here because the editor rebuilds expressions against the alias map of
48
- * the spec being edited, where the built app's domain builder holds its own.
49
- */
50
- export declare const mergeExpressionModules: (modules: readonly ProjectModule[], aliasMap: Record<string, readonly string[]>) => ResolvedExpressions;
51
46
  export declare const mergeComponentOptics: <ComponentOptic>(generatedComponentOptics: readonly ComponentOptic[], customComponentOptics: readonly ComponentOptic[]) => readonly ComponentOptic[];
52
47
  export declare const getCustomComponentOptics: <ComponentOptic extends {
53
48
  readonly generated?: boolean;
@@ -1 +1 @@
1
- import{useCallback as e,useRef as n}from"react";import{expandAlias as t,resolveActionModules as a,resolveComponentOpticModules as r,resolveElementModule as o,resolveExpressionModules as s,resolveHandlerModule as i,resolveInvariantModules as l,resolveTransformerModule as m}from"#package/domain";import{importImplementationFile as c}from"./import-implementation-file.js";let p=e=>e instanceof Error?e.message:String(e),f=async(e,n)=>{let t=Date.now();return Promise.all(e.map(async e=>({origin:e,exports:await c(`/@fs/${n}/${e}?t=${t}`)})))},d=async(e,n)=>a(await f(e,n));export const mergeExpressionModules=(e,n)=>{let a={};for(let{expressions:t}of s(e,n))for(let[e,n]of Object.entries(t))a[e]={...a[e],...n};let r={};for(let[e,o]of Object.entries(a))for(let a of t(n,e)){let n=r[a]??{};for(let[t,a]of Object.entries(o))n[t]={...a,origin:{name:t,typeOrAlias:e}};r[a]=n}return r};export const mergeComponentOptics=(e,n)=>e.concat(n);export const getCustomComponentOptics=e=>e.filter(e=>!0!==e.generated);let u=async(e,n,t)=>mergeExpressionModules(await f(e,t),n),g=async(e,n)=>r(await f(e,n)),h=async(e,n)=>l(await f(e,n)),E=async(e,n)=>(await f(e,n)).map(m),F=async(e,n)=>(await f(e,n)).map(e=>({filePath:e.origin,registrations:i(e)})),w=async(e,n)=>(await f(e,n)).map(e=>({filePath:e.origin,registrations:o(e)}));export const useImplementationFiles=()=>{let t=n({}),a=n(null),r=n({}),o=n(0),s=n(null),i=n({}),l=n(null),m=n(null),c=n(null),f=n([]),I=n(null),y=n(null),O=n(new Map),A=n(new Map);return{getImplementationFiles:e(async e=>{let{application:n,projectRoot:R}=e,C=++o.current,{applicationSpec:D,categorizedFiles:L}=n,S=[],x=t.current,M=r.current,_=i.current,$=c.current,b=f.current,v=L.expressionsChanged,N=L.actionsChanged,j=L.componentsChanged,P=L.transformersChanged,H=L.handlersChanged,T=L.elementsChanged,k=Object.fromEntries(L.invariants.map(e=>[e.file.name,e.depHash])),J=l.current,X=JSON.stringify(D.configurator.invariants.entries),V=null===J||m.current!==X||Object.keys(J).length!==L.invariants.length||L.invariants.some(e=>J[e.file.name]!==e.depHash);if(console.info(`[useImplementationFiles] Changed: spec=${L.specChanged}, expressions=${L.expressionsChanged}, actions=${L.actionsChanged}, adminExpressions=${L.adminExpressionsChanged}, transformers=${L.transformersChanged}, handlers=${L.handlersChanged}, elements=${L.elementsChanged}`),v){console.info("[useImplementationFiles] Reloading expression implementations");try{let e=Object.fromEntries(D.configurator.latestModel.aliases);t.current=x=await u(L.expressions.map(e=>e.file.name),e,R)}catch(e){console.warn("[useImplementationFiles] Failed to reload expressions:",e),S.push({code:"RELOAD_EXPRESSIONS_FAILED",message:p(e)})}}let q=a.current;if(N){console.info("[useImplementationFiles] Reloading action implementations");try{a.current=q=await d(L.actions.map(e=>e.file.name),R)}catch(e){console.warn("[useImplementationFiles] Failed to reload actions:",e),S.push({code:"RELOAD_ACTIONS_FAILED",message:p(e)})}}let z=JSON.stringify({projectRoot:R,files:L.adminExpressions.map(e=>[e.file.name,e.depHash]),aliases:[...D.admin.latestModel.aliases]});if(C===o.current&&s.current!==z)try{M=await u(L.adminExpressions.map(e=>e.file.name),Object.fromEntries(D.admin.latestModel.aliases),R),C===o.current&&(r.current=M,s.current=z)}catch(e){S.push({code:"RELOAD_ADMIN_EXPRESSIONS_FAILED",message:p(e)})}if(j){console.info("[useImplementationFiles] Reloading component optics");try{c.current=$=await g(L.components.map(e=>e.file.name),R)}catch(e){console.warn("[useImplementationFiles] Failed to reload components:",e),S.push({code:"RELOAD_COMPONENTS_FAILED",message:p(e)})}}if(V){console.info("[useImplementationFiles] Reloading invariant implementations");try{i.current=_=await h(L.invariants.map(e=>e.file.name),R),l.current=k,m.current=X}catch(e){console.warn("[useImplementationFiles] Failed to reload invariants:",e),S.push({code:"RELOAD_INVARIANTS_FAILED",message:p(e)})}}if(P){console.info("[useImplementationFiles] Reloading transformer implementations");try{f.current=b=await E(L.transformers.map(e=>e.file.name),R)}catch(e){console.warn("[useImplementationFiles] Failed to reload transformers:",e),S.push({code:"RELOAD_TRANSFORMERS_FAILED",message:p(e)})}}let B=null;if(H){console.info("[useImplementationFiles] Reloading handler implementations");try{let e=Object.fromEntries(L.handlers.map(e=>[e.file.name,e.depHash])),n=I.current,t=t=>null===n||n[t]!==e[t],a=A.current,r=L.handlers.map(e=>e.file.name),o=r.filter(e=>t(e)||!a.has(e)),s=await F(o,R),i=new Map(s.map(e=>[e.filePath,e])),l=r.map(e=>{let n=i.get(e)??a.get(e);if(!n)throw Error(`Handler file "${e}" was neither re-imported nor cached from a previous round. This is a hot-reload bookkeeping bug — reload the editor page to recover.`);return n}),m=l.flatMap(e=>e.registrations),c={};for(let{filePath:n,registrations:a}of l){let r=t(n)?e[n]:void 0;if(r)for(let e of a)c[e.name]=r}console.info(`[useImplementationFiles] Staged handlers for registry (${m.length} total)`),B={handlers:m,nameHashes:c},A.current=new Map(l.map(e=>[e.filePath,e])),I.current=e}catch(e){console.warn("[useImplementationFiles] Failed to reload handlers:",e),S.push({code:"RELOAD_HANDLERS_FAILED",message:p(e)})}}let G=null;if(T){console.info("[useImplementationFiles] Reloading element implementations");try{let e=Object.fromEntries(L.elements.map(e=>[e.file.name,e.depHash])),n=y.current,t=t=>null===n||n[t]!==e[t],a=O.current,r=L.elements.map(e=>e.file.name),o=r.filter(e=>t(e)||!a.has(e)),s=await w(o,R),i=new Map(s.map(e=>[e.filePath,e])),l=r.map(e=>{let n=i.get(e)??a.get(e);if(!n)throw Error(`Element file "${e}" was neither re-imported nor cached from a previous round. This is a hot-reload bookkeeping bug — reload the editor page to recover.`);return n}),m=l.flatMap(e=>e.registrations),c={},p=0;for(let{filePath:n,registrations:a}of l){let r=t(n)?e[n]:void 0;for(let e of a)if("assistantFormElement"!==e.type){if("entity"===e.type||"layout"===e.type){r&&(c[e.name]=r);continue}r&&(c[`icon:${p}`]=r),p+=1}}console.info(`[useImplementationFiles] Staged elements for registry (${m.length} total)`),G={elements:m,nameHashes:c},O.current=new Map(l.map(e=>[e.filePath,e])),y.current=e}catch(e){console.warn("[useImplementationFiles] Failed to reload elements:",e),S.push({code:"RELOAD_ELEMENTS_FAILED",message:p(e)})}}return{implementations:x,actionImplementations:q,adminImplementations:M,invariantImplementations:_,importedTransformers:b,customComponentOptics:$,handlers:B,elements:G,errors:S}},[])}};
1
+ import{useCallback as e,useRef as n}from"react";import{resolveActionModules as t,resolveComponentOpticModules as a,resolveElementModule as r,resolveHandlerModule as o,resolveInvariantModules as i,resolveTransformerModule as s}from"#package/domain";import{importImplementationFile as l}from"./import-implementation-file.js";let m=e=>e instanceof Error?e.message:String(e),c=async(e,n)=>{let t=Date.now();return Promise.all(e.map(async e=>({origin:e,exports:await l(`/@fs/${n}/${e}?t=${t}`)})))},p=async(e,n)=>t(await c(e,n));export const mergeComponentOptics=(e,n)=>e.concat(n);export const getCustomComponentOptics=e=>e.filter(e=>!0!==e.generated);let u=async(e,n)=>a(await c(e,n)),d=async(e,n)=>i(await c(e,n)),f=async(e,n)=>(await c(e,n)).map(s),h=async(e,n)=>(await c(e,n)).map(e=>({filePath:e.origin,registrations:o(e)})),g=async(e,n)=>(await c(e,n)).map(e=>({filePath:e.origin,registrations:r(e)}));export const useImplementationFiles=()=>{let t=n([]),a=n(null),r=n([]),o=n(0),i=n(null),s=n({}),l=n(null),E=n(null),F=n(null),w=n([]),I=n(null),y=n(null),A=n(new Map),O=n(new Map);return{getImplementationFiles:e(async e=>{let{application:n,projectRoot:R}=e,C=++o.current,{applicationSpec:D,categorizedFiles:L}=n,S=[],_=t.current,$=r.current,x=s.current,v=F.current,N=w.current,M=L.expressionsChanged,P=L.actionsChanged,b=L.componentsChanged,H=L.transformersChanged,T=L.handlersChanged,k=L.elementsChanged,j=Object.fromEntries(L.invariants.map(e=>[e.file.name,e.depHash])),J=l.current,X=JSON.stringify(D.configurator.invariants.entries),V=null===J||E.current!==X||Object.keys(J).length!==L.invariants.length||L.invariants.some(e=>J[e.file.name]!==e.depHash);if(console.info(`[useImplementationFiles] Changed: spec=${L.specChanged}, expressions=${L.expressionsChanged}, actions=${L.actionsChanged}, adminExpressions=${L.adminExpressionsChanged}, transformers=${L.transformersChanged}, handlers=${L.handlersChanged}, elements=${L.elementsChanged}`),M){console.info("[useImplementationFiles] Reloading expression implementations");try{t.current=_=await c(L.expressions.map(e=>e.file.name),R)}catch(e){console.warn("[useImplementationFiles] Failed to reload expressions:",e),S.push({code:"RELOAD_EXPRESSIONS_FAILED",message:m(e)})}}let q=a.current;if(P){console.info("[useImplementationFiles] Reloading action implementations");try{a.current=q=await p(L.actions.map(e=>e.file.name),R)}catch(e){console.warn("[useImplementationFiles] Failed to reload actions:",e),S.push({code:"RELOAD_ACTIONS_FAILED",message:m(e)})}}let z=JSON.stringify({projectRoot:R,files:L.adminExpressions.map(e=>[e.file.name,e.depHash])});if(C===o.current&&i.current!==z)try{$=await c(L.adminExpressions.map(e=>e.file.name),R),C===o.current&&(r.current=$,i.current=z)}catch(e){S.push({code:"RELOAD_ADMIN_EXPRESSIONS_FAILED",message:m(e)})}if(b){console.info("[useImplementationFiles] Reloading component optics");try{F.current=v=await u(L.components.map(e=>e.file.name),R)}catch(e){console.warn("[useImplementationFiles] Failed to reload components:",e),S.push({code:"RELOAD_COMPONENTS_FAILED",message:m(e)})}}if(V){console.info("[useImplementationFiles] Reloading invariant implementations");try{s.current=x=await d(L.invariants.map(e=>e.file.name),R),l.current=j,E.current=X}catch(e){console.warn("[useImplementationFiles] Failed to reload invariants:",e),S.push({code:"RELOAD_INVARIANTS_FAILED",message:m(e)})}}if(H){console.info("[useImplementationFiles] Reloading transformer implementations");try{w.current=N=await f(L.transformers.map(e=>e.file.name),R)}catch(e){console.warn("[useImplementationFiles] Failed to reload transformers:",e),S.push({code:"RELOAD_TRANSFORMERS_FAILED",message:m(e)})}}let B=null;if(T){console.info("[useImplementationFiles] Reloading handler implementations");try{let e=Object.fromEntries(L.handlers.map(e=>[e.file.name,e.depHash])),n=I.current,t=t=>null===n||n[t]!==e[t],a=O.current,r=L.handlers.map(e=>e.file.name),o=r.filter(e=>t(e)||!a.has(e)),i=await h(o,R),s=new Map(i.map(e=>[e.filePath,e])),l=r.map(e=>{let n=s.get(e)??a.get(e);if(!n)throw Error(`Handler file "${e}" was neither re-imported nor cached from a previous round. This is a hot-reload bookkeeping bug — reload the editor page to recover.`);return n}),m=l.flatMap(e=>e.registrations),c={};for(let{filePath:n,registrations:a}of l){let r=t(n)?e[n]:void 0;if(r)for(let e of a)c[e.name]=r}console.info(`[useImplementationFiles] Staged handlers for registry (${m.length} total)`),B={handlers:m,nameHashes:c},O.current=new Map(l.map(e=>[e.filePath,e])),I.current=e}catch(e){console.warn("[useImplementationFiles] Failed to reload handlers:",e),S.push({code:"RELOAD_HANDLERS_FAILED",message:m(e)})}}let G=null;if(k){console.info("[useImplementationFiles] Reloading element implementations");try{let e=Object.fromEntries(L.elements.map(e=>[e.file.name,e.depHash])),n=y.current,t=t=>null===n||n[t]!==e[t],a=A.current,r=L.elements.map(e=>e.file.name),o=r.filter(e=>t(e)||!a.has(e)),i=await g(o,R),s=new Map(i.map(e=>[e.filePath,e])),l=r.map(e=>{let n=s.get(e)??a.get(e);if(!n)throw Error(`Element file "${e}" was neither re-imported nor cached from a previous round. This is a hot-reload bookkeeping bug — reload the editor page to recover.`);return n}),m=l.flatMap(e=>e.registrations),c={},p=0;for(let{filePath:n,registrations:a}of l){let r=t(n)?e[n]:void 0;for(let e of a)if("assistantFormElement"!==e.type){if("entity"===e.type||"layout"===e.type){r&&(c[e.name]=r);continue}r&&(c[`icon:${p}`]=r),p+=1}}console.info(`[useImplementationFiles] Staged elements for registry (${m.length} total)`),G={elements:m,nameHashes:c},A.current=new Map(l.map(e=>[e.filePath,e])),y.current=e}catch(e){console.warn("[useImplementationFiles] Failed to reload elements:",e),S.push({code:"RELOAD_ELEMENTS_FAILED",message:m(e)})}}return{expressionModules:_,actionImplementations:q,adminExpressionModules:$,invariantImplementations:x,importedTransformers:N,customComponentOptics:v,handlers:B,elements:G,errors:S}},[])}};
@@ -1,3 +1,3 @@
1
- export declare const cacheVersion = 772;
1
+ export declare const cacheVersion = 773;
2
2
  export declare const needsRebuild: (fileContents: string[], outputDirectory: string) => Promise<boolean>;
3
3
  export declare const writeCacheInfo: (fileContents: string[], outputDirectory: string) => Promise<void>;