@salsita-ai/sdk 0.50.0-develop.da8d27f5d7 → 0.50.0-develop.dfac20c66b

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 (169) hide show
  1. package/README.md +19 -11
  2. package/dist/application-spec/errors/diagnostic-codes.d.ts +6 -0
  3. package/dist/application-spec/errors/diagnostic-codes.js +1 -1
  4. package/dist/application-spec/errors/diagnostic-messages.d.ts +6 -0
  5. package/dist/application-spec/errors/diagnostic-messages.js +1 -1
  6. package/dist/application-spec/generate-application/code/domain-runtime-files.js +1 -1
  7. package/dist/application-spec/generate-application/code/templates/application-types.js +6 -6
  8. package/dist/application-spec/generate-application/code/templates/configurator-domain-code.d.ts +1 -0
  9. package/dist/application-spec/generate-application/code/templates/configurator-domain-code.js +11 -8
  10. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-domain-block.d.ts +3 -1
  11. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-domain-block.js +70 -66
  12. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-phx-globals.js +3 -0
  13. package/dist/application-spec/generate-application/code/templates/domain-spec.js +5 -5
  14. package/dist/application-spec/generate-application/code/templates/domain.js +2 -2
  15. package/dist/application-spec/generate-application/code/templates/global-definition/generate-action-types.d.ts +11 -0
  16. package/dist/application-spec/generate-application/code/templates/global-definition/generate-action-types.js +8 -0
  17. package/dist/application-spec/generate-application/code/templates/global-definition/index.d.ts +1 -0
  18. package/dist/application-spec/generate-application/code/templates/global-definition/index.js +1 -1
  19. package/dist/application-spec/generate-application/code/templates/globals.js +1 -0
  20. package/dist/application-spec/generate-application/code/templates/index.d.ts +6 -6
  21. package/dist/application-spec/generate-application/code/templates/index.js +1 -1
  22. package/dist/application-spec/generate-application/code/templates/skills/agents-md.js +2 -0
  23. package/dist/application-spec/generate-application/code/templates/skills/phoenix-cli-skill.js +1 -0
  24. package/dist/application-spec/generate-application/code/templates/{phoenix-create-configurator-skill.d.ts → skills/phoenix-create-configurator-skill.d.ts} +1 -1
  25. package/dist/application-spec/generate-application/code/templates/{phoenix-create-configurator-skill.js → skills/phoenix-create-configurator-skill.js} +4 -2
  26. package/dist/application-spec/generate-application/code/templates/skills/phoenix-feedback-skill.js +54 -0
  27. package/dist/application-spec/generate-application/code/templates/{phoenix-review-skill.js → skills/phoenix-review-skill.js} +6 -4
  28. package/dist/application-spec/generate-application/code/templates/skills/phoenix-skill.js +1 -0
  29. package/dist/application-spec/generate-application/code/templates/{common → skills}/sdk-content.d.ts +24 -1
  30. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.js +67 -0
  31. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.d.ts +2 -0
  32. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.js +1 -1
  33. package/dist/application-spec/generate-application/runtime/sections/actions-runtime.d.ts +14 -0
  34. package/dist/application-spec/generate-application/runtime/sections/actions-runtime.js +1 -0
  35. package/dist/application-spec/generate-application/runtime/sections/index.d.ts +1 -0
  36. package/dist/application-spec/generate-application/runtime/sections/index.js +1 -1
  37. package/dist/application-spec/parse-application-files/categorize/categorize-files.d.ts +3 -1
  38. package/dist/application-spec/parse-application-files/categorize/categorize-files.js +1 -1
  39. package/dist/application-spec/parse-application-files/merge/index.d.ts +1 -0
  40. package/dist/application-spec/parse-application-files/merge/index.js +1 -1
  41. package/dist/application-spec/parse-application-files/merge/merged-actions.d.ts +11 -0
  42. package/dist/application-spec/parse-application-files/merge/merged-actions.js +1 -0
  43. package/dist/application-spec/parse-application-files/merge/merged-spec.d.ts +2 -0
  44. package/dist/application-spec/parse-application-files/merge/merged-spec.js +1 -1
  45. package/dist/application-spec/parse-application-files/raw-spec/index.d.ts +1 -0
  46. package/dist/application-spec/parse-application-files/raw-spec/index.js +1 -1
  47. package/dist/application-spec/parse-application-files/raw-spec/raw-actions.d.ts +18 -0
  48. package/dist/application-spec/parse-application-files/raw-spec/raw-actions.js +1 -0
  49. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.d.ts +14 -2
  50. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.js +1 -1
  51. package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.d.ts +2 -0
  52. package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.js +1 -1
  53. package/dist/application-spec/parse-application-files/resolve/resolve-import-modules.js +1 -1
  54. package/dist/application-spec/parse-application-files/spec/application/application-spec.js +1 -1
  55. package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.d.ts +4 -2
  56. package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.js +1 -1
  57. package/dist/application-spec/parse-application-files/spec/common/index.d.ts +1 -0
  58. package/dist/application-spec/parse-application-files/spec/common/index.js +1 -1
  59. package/dist/application-spec/parse-application-files/spec/common/schema-ref-resolver.d.ts +23 -0
  60. package/dist/application-spec/parse-application-files/spec/common/schema-ref-resolver.js +1 -0
  61. package/dist/application-spec/parse-application-files/spec/model/names/action-name.d.ts +10 -0
  62. package/dist/application-spec/parse-application-files/spec/model/names/action-name.js +1 -0
  63. package/dist/application-spec/parse-application-files/spec/model/names/index.d.ts +1 -0
  64. package/dist/application-spec/parse-application-files/spec/model/names/index.js +1 -1
  65. package/dist/application-spec/parse-application-files/spec/sections/actions.d.ts +35 -0
  66. package/dist/application-spec/parse-application-files/spec/sections/actions.js +1 -0
  67. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.d.ts +3 -14
  68. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.js +1 -1
  69. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.d.ts +12 -3
  70. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
  71. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant.d.ts +5 -3
  72. package/dist/application-spec/parse-application-files/spec/sections/index.d.ts +1 -0
  73. package/dist/application-spec/parse-application-files/spec/sections/index.js +1 -1
  74. package/dist/client/phoenix-api.d.ts +5 -1
  75. package/dist/configurator/application-runtime/extensions/configurator-extension-systems.d.ts +2 -1
  76. package/dist/configurator/application-runtime/extensions/configurator-extension-systems.js +1 -1
  77. package/dist/configurator/application-runtime/extensions/selectors.d.ts +2 -1
  78. package/dist/configurator/application-runtime/extensions/selectors.js +1 -1
  79. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +35 -0
  80. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -0
  81. package/dist/configurator/{assistant → application-runtime/extensions/systems/assistant-system}/browser-details.d.ts +1 -1
  82. package/dist/configurator/application-runtime/extensions/systems/assistant-system/browser-details.js +1 -0
  83. package/dist/configurator/{assistant → application-runtime/extensions/systems/assistant-system}/graphql-tools.d.ts +13 -14
  84. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -0
  85. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
  86. package/dist/configurator/application-runtime/extensions/systems/index.d.ts +1 -0
  87. package/dist/configurator/application-runtime/extensions/systems/index.js +1 -1
  88. package/dist/configurator/assistant/use-assistant-chat.js +1 -1
  89. package/dist/docs/index.json +12 -2
  90. package/dist/docs/other-features/domain-actions.mdx +418 -0
  91. package/dist/docs/phoenix/admin.mdx +2 -2
  92. package/dist/docs/phoenix/best-practices.mdx +1 -0
  93. package/dist/docs/phoenix/finalization.mdx +1 -1
  94. package/dist/docs/phoenix/integration/headless-mode-external.mdx +5 -5
  95. package/dist/docs/phoenix/integration/widget-mode-external.mdx +5 -5
  96. package/dist/docs/phoenix/migrations.mdx +45 -5
  97. package/dist/docs/phoenix/phoenix-cli.mdx +60 -20
  98. package/dist/docs/phoenix/project-structure.mdx +4 -1
  99. package/dist/docs/phoenix/sdk-builder-workflow.mdx +9 -6
  100. package/dist/domain/actions/action-factory.d.ts +10 -0
  101. package/dist/domain/actions/action-factory.js +1 -0
  102. package/dist/domain/actions/prepare-action-implementations.d.ts +15 -0
  103. package/dist/domain/actions/prepare-action-implementations.js +5 -0
  104. package/dist/domain/application/application-config.d.ts +3 -1
  105. package/dist/domain/application/assistant-mutations.d.ts +15 -14
  106. package/dist/domain/application/assistant-mutations.js +1 -1
  107. package/dist/domain/core/action.d.ts +67 -0
  108. package/dist/domain/core/action.js +1 -0
  109. package/dist/domain/core/domain-factory.d.ts +4 -0
  110. package/dist/domain/core/index.d.ts +1 -0
  111. package/dist/domain/domain-builder.d.ts +7 -0
  112. package/dist/domain/domain-builder.js +1 -1
  113. package/dist/domain/domain-context/action-system/action-system.d.ts +40 -0
  114. package/dist/domain/domain-context/action-system/action-system.js +1 -0
  115. package/dist/domain/domain-context/domain-context-systems.d.ts +5 -2
  116. package/dist/domain/domain-context/index.d.ts +1 -0
  117. package/dist/domain/domain-context/index.js +1 -1
  118. package/dist/domain/domain-runtime/domain-context/domain-context.js +1 -1
  119. package/dist/domain/domain-runtime/domain-context/selectors.d.ts +4 -0
  120. package/dist/domain/domain-runtime/domain-context/selectors.js +1 -1
  121. package/dist/domain/domain-runtime/domain-runtime.d.ts +12 -0
  122. package/dist/domain/domain-runtime/spec/initialize.js +1 -1
  123. package/dist/domain/domain-runtime/spec/types.d.ts +15 -1
  124. package/dist/domain/index.d.ts +2 -0
  125. package/dist/domain/index.js +1 -1
  126. package/dist/domain/mocks/create-mock-domain-runtime.d.ts +6 -0
  127. package/dist/editor/domain-editors/DomainSpecContext.js +1 -1
  128. package/dist/editor/domain-editors/apply-spec-update.js +1 -1
  129. package/dist/editor/domain-editors/use-implementation-files.d.ts +7 -3
  130. package/dist/editor/domain-editors/use-implementation-files.js +1 -1
  131. package/dist/phoenix/application-spec/generate-assistant-prompt.d.ts +2 -2
  132. package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
  133. package/dist/phoenix/cli.js +1 -1
  134. package/dist/phoenix/commands/build.d.ts +5 -0
  135. package/dist/phoenix/commands/build.js +1 -1
  136. package/dist/phoenix/commands/deploy.js +2 -2
  137. package/dist/phoenix/commands/feedback.d.ts +2 -1
  138. package/dist/phoenix/commands/feedback.js +1 -1
  139. package/dist/phoenix/commands/login.d.ts +24 -6
  140. package/dist/phoenix/commands/login.js +2 -2
  141. package/dist/phoenix/services/index.d.ts +1 -0
  142. package/dist/phoenix/services/index.js +1 -1
  143. package/dist/phoenix/services/phx-banner-plugin.d.ts +32 -0
  144. package/dist/phoenix/services/phx-banner-plugin.js +1 -0
  145. package/dist/phoenix/services/phx-licenses-plugin.d.ts +55 -0
  146. package/dist/phoenix/services/phx-licenses-plugin.js +8 -0
  147. package/dist/phoenix/services/vite-config.d.ts +2 -0
  148. package/dist/phoenix/services/vite-config.js +1 -1
  149. package/dist/phoenix/utils/index.d.ts +1 -0
  150. package/dist/phoenix/utils/index.js +1 -1
  151. package/dist/phoenix/utils/read-git-commit.d.ts +14 -0
  152. package/dist/phoenix/utils/read-git-commit.js +1 -0
  153. package/dist/react-sdk/application-runtime/runtime/create-application-runtime.d.ts +12 -0
  154. package/dist/react-sdk/domain-context/common-hooks/use-domain-context.d.ts +3 -0
  155. package/package.json +3 -3
  156. package/dist/application-spec/generate-application/code/templates/agents-md.js +0 -2
  157. package/dist/application-spec/generate-application/code/templates/common/sdk-content.js +0 -67
  158. package/dist/application-spec/generate-application/code/templates/phoenix-cli-skill.js +0 -1
  159. package/dist/application-spec/generate-application/code/templates/phoenix-feedback-skill.js +0 -31
  160. package/dist/application-spec/generate-application/code/templates/phoenix-skill.js +0 -1
  161. package/dist/configurator/assistant/browser-details.js +0 -1
  162. package/dist/configurator/assistant/graphql-tools.js +0 -1
  163. /package/dist/application-spec/generate-application/code/templates/{common → skills}/agent-skill.d.ts +0 -0
  164. /package/dist/application-spec/generate-application/code/templates/{common → skills}/agent-skill.js +0 -0
  165. /package/dist/application-spec/generate-application/code/templates/{agents-md.d.ts → skills/agents-md.d.ts} +0 -0
  166. /package/dist/application-spec/generate-application/code/templates/{phoenix-cli-skill.d.ts → skills/phoenix-cli-skill.d.ts} +0 -0
  167. /package/dist/application-spec/generate-application/code/templates/{phoenix-feedback-skill.d.ts → skills/phoenix-feedback-skill.d.ts} +0 -0
  168. /package/dist/application-spec/generate-application/code/templates/{phoenix-review-skill.d.ts → skills/phoenix-review-skill.d.ts} +0 -0
  169. /package/dist/application-spec/generate-application/code/templates/{phoenix-skill.d.ts → skills/phoenix-skill.d.ts} +0 -0
@@ -1 +1 @@
1
- let e=["How to read the GraphQL schema of this configurator:","- A configuration is a set of entities. `root` is the root entity, `entities` lists every entity or the ones with the given ids, and `selectedEntity` is the entity the user has selected, or the root entity when nothing is selected.","- Every entity has an `id` of the form `<Type>-<number>`, for example `Table-1`, and a `type` with its entity type name. Ids are assigned by the configurator: read them from the configuration and never make one up.","- A field whose name starts with `_` is computed by the configurator from other values. It can be read like any other field and never written.","- Numbers are in the units the configuration stores them in. A field description names the unit when the product defines one.",'- A text field that only takes fixed values lists them in its description as "One of: ...". Use exactly those values.',"- A field typed as another entity type or as a list of one is a relation: select fields on it to read the related entities.","- Field and type descriptions come from the team that built the configurator and say what a value means for the product."],t=["How changes work:","- Every field of the `Mutation` type is one change. Its description says what it changes and what it returns.","- The configurator checks the whole configuration after each change. A change that would leave it invalid fails with an error that names the entities at fault, and it is not applied. Later changes of the same request are then not run.","- The configurator may adjust other values in response to a change, so read what a mutation returns instead of assuming the values you sent."],n=["How to add entities:","- Entities are added from recipes, the same ones the configurator offers the user. An entity type that can take children has a `meta` field; `meta { childRecipes }` lists its recipe groups and their recipes.","- List the recipes of the group first, pick one by its `key`, then call `addChild` with the id of the parent, the `groupId` and the `key`. Keys change with the configuration and the language, so never reuse one from memory.","- `dryRun` on a recipe shows what adding it would do without adding it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, and the `errors` when it cannot be added. An entity whose id the configuration does not have yet is new. It is costly, so select it only on the recipes you are deciding between.","- Put each `addChild` in its own operation. The recipes of a group and what they add depend on the configuration before them, so after adding something, list the group again before adding from it once more."],a=["How to replace entities:","- An entity is replaced from recipes, the same ones the configurator offers the user. An entity type that can be replaced has a `meta` field; `meta { replaceRecipes }` lists its replace recipe groups and what the entity can be replaced with.","- List the recipes of the group first, pick one by its `key`, then call `replaceEntity` with the id of the entity, the `groupId` and the `key`. `dryRun` on a replace recipe shows what replacing would do without doing it: the replacement and everything else that changes are under `changedEntities`, and the replaced entity is among the `deletedEntityIds`.","- The replacement is a new entity with a new id, and its field values come from the recipe, so they can differ from those of the entity it replaces. Read the ids and values `replaceEntity` returns, and never use the old id again.","- Put each `replaceEntity` in its own operation. The recipes of a group and what they do depend on the configuration before them, so after replacing something, list the group of the replacement again before replacing once more."],i=["How to find the values a field can take:","- Some fields store a key whose choices the configurator holds elsewhere. Such a field has an edge under `meta` named after it: `meta { <field>Options }` lists its choices, each with the `value` to write and the `name` the user sees.","- Read the choices before you write such a field or name a choice to the user, and write the `value`, not the `name`. A value outside the list is rejected unless the edge description says the field is not checked.","- `dryRun` on an option shows what writing its value would do without writing it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, and the `errors` when the value cannot be written. It is costly, so select it only on the options you are deciding between. It is null when the edge description says the options cannot be dry-run.","- The choices can depend on the entity and on its current state. Read them again after a change, unless the edge description says they are the same for all instances or do not change."],o=["How to use the `query` and `apply` tools:","- Both take `operations`, a list of GraphQL documents that run in order. Each document holds exactly one operation. To do several things, send several items in one call instead of several calls.","- Write values into the document as literals. Use `variables` only for a value that cannot be written as a literal.","- Select only the fields you need: results are returned whole.","- The result has one GraphQL result per operation, in the order sent. When an operation fails, its `errors` say why and the operations after it are not run.","- `query` reads the configuration the user has open and never changes it. Call it before you say anything about the configuration."],s=["- This configurator exposes no changes, so there is nothing for `apply` to run. Say so when the user asks you to change the configuration."],r=['- Mutations inside `query` answer "what if" questions. Each operation sees the changes of the ones before it, so a mutation followed by a query shows the configuration as it would be. Nothing is kept and the user sees no change.',"- `apply` makes the changes the user asked for. It is all or nothing: when any operation fails, nothing is changed; when all succeed, the user gets them as one undo step.","- `committed` in the result says whether the changes were kept. When it is false although no operation failed, `message` says why: the changes may be waiting for the approval of the user, the user may have changed the configuration meanwhile, or this session may not change the configuration at all. Without a `message`, the operations changed nothing. Never tell the user a change was made unless `committed` is true."];export const generateAssistantPrompt=h=>{let d=/^type Mutation\b/m.test(h.sdl);return[e,...d?[t]:[],.../^\s+addChild\(/m.test(h.sdl)?[n]:[],.../^\s+replaceEntity\(/m.test(h.sdl)?[a]:[],.../^type FieldOption\b/m.test(h.sdl)?[i]:[],[...o,...d?r:s]].map(e=>e.join("\n")).join("\n\n")};
1
+ let e=["How to read the GraphQL schema of this configurator:","- A configuration is a set of entities. `root` is the root entity, `entities` lists every entity or the ones with the given ids, and `selectedEntity` is the entity the user has selected, or the root entity when nothing is selected.","- Every entity has an `id` of the form `<Type>-<number>`, for example `Table-1`, and a `type` with its entity type name. Ids are assigned by the configurator: read them from the configuration and never make one up.","- A field whose name starts with `_` is computed by the configurator from other values. It can be read like any other field and never written.","- Numbers are in the units the configuration stores them in. A field description names the unit when the product defines one.",'- A text field that only takes fixed values lists them in its description as "One of: ...". Use exactly those values.',"- A field typed as another entity type or as a list of one is a relation: select fields on it to read the related entities.","- Field and type descriptions come from the team that built the configurator and say what a value means for the product."],t=["How changes work:","- Every field of the `Mutation` type is one change. Its description says what it changes and what it returns.","- The configurator checks the whole configuration after each change. A change that would leave it invalid fails with an error that names the entities at fault, and it is not applied. Later changes of the same request are then not run.","- The configurator may adjust other values in response to a change, so read what a mutation returns instead of assuming the values you sent."],a=["How to add entities:","- Entities are added from recipes, the same ones the configurator offers the user. An entity type that can take children has a `meta` field; `meta { childRecipes }` lists its recipe groups and their recipes.","- List the recipes of the group first, pick one by its `key`, then call `addChild` with the id of the parent, the `groupId` and the `key`. Keys change with the configuration and the language, so never reuse one from memory.","- `dryRun` on a recipe shows what adding it would do without adding it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, and the `errors` when it cannot be added. An entity whose id the configuration does not have yet is new. It is costly, so select it only on the recipes you are deciding between.","- Put each `addChild` in its own operation. The recipes of a group and what they add depend on the configuration before them, so after adding something, list the group again before adding from it once more."],n=["How to replace entities:","- An entity is replaced from recipes, the same ones the configurator offers the user. An entity type that can be replaced has a `meta` field; `meta { replaceRecipes }` lists its replace recipe groups and what the entity can be replaced with.","- List the recipes of the group first, pick one by its `key`, then call `replaceEntity` with the id of the entity, the `groupId` and the `key`. `dryRun` on a replace recipe shows what replacing would do without doing it: the replacement and everything else that changes are under `changedEntities`, and the replaced entity is among the `deletedEntityIds`.","- The replacement is a new entity with a new id, and its field values come from the recipe, so they can differ from those of the entity it replaces. Read the ids and values `replaceEntity` returns, and never use the old id again.","- Put each `replaceEntity` in its own operation. The recipes of a group and what they do depend on the configuration before them, so after replacing something, list the group of the replacement again before replacing once more."],i=["How to find the values a field can take:","- Some fields store a key whose choices the configurator holds elsewhere. Such a field has an edge under `meta` named after it: `meta { <field>Options }` lists its choices, each with the `value` to write and the `name` the user sees.","- Read the choices before you write such a field or name a choice to the user, and write the `value`, not the `name`. A value outside the list is rejected unless the edge description says the field is not checked.","- `dryRun` on an option shows what writing its value would do without writing it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, and the `errors` when the value cannot be written. It is costly, so select it only on the options you are deciding between. It is null when the edge description says the options cannot be dry-run.","- The choices can depend on the entity and on its current state. Read them again after a change, unless the edge description says they are the same for all instances or do not change."],o=["How the custom changes of this configurator work:","- Besides the generic changes, the `Mutation` type has fields the team built for this product. Each runs one domain operation the configurator itself uses, so prefer it over composing the same change from generic mutations. Its description says what it does and what its arguments mean.","- Its arguments are checked against what the operation declares; an argument that does not fit, or a change the product does not allow, fails the field with a message that says what to send instead.","- It returns an object whose fields the description names; a field typed as an entity reads that entity after the change."],s=["How to use the `query` and `apply` tools:","- Both take `operations`, a list of GraphQL documents that run in order. Each document holds exactly one operation. To do several things, send several items in one call instead of several calls.","- Write values into the document as literals. Use `variables` only for a value that cannot be written as a literal.","- Select only the fields you need: results are returned whole.","- The result has one GraphQL result per operation, in the order sent. When an operation fails, its `errors` say why and the operations after it are not run.","- `query` reads the configuration the user has open and never changes it. Call it before you say anything about the configuration."],r=["- This configurator exposes no changes, so there is nothing for `apply` to run. Say so when the user asks you to change the configuration."],h=['- Mutations inside `query` answer "what if" questions. Each operation sees the changes of the ones before it, so a mutation followed by a query shows the configuration as it would be. Nothing is kept and the user sees no change.',"- `apply` makes the changes the user asked for. It is all or nothing: when any operation fails, nothing is changed; when all succeed, the user gets them as one undo step.","- `committed` in the result says whether the changes were kept. When it is false although no operation failed, `message` says why: the changes may be waiting for the approval of the user, the user may have changed the configuration meanwhile, or this session may not change the configuration at all. Without a `message`, the operations changed nothing. Never tell the user a change was made unless `committed` is true."];export const generateAssistantPrompt=d=>{let c=/^type Mutation\b/m.test(d.sdl);return[e,...c?[t]:[],.../^\s+addChild\(/m.test(d.sdl)?[a]:[],.../^\s+replaceEntity\(/m.test(d.sdl)?[n]:[],.../^type FieldOption\b/m.test(d.sdl)?[i]:[],...Object.keys(d.actions).length>0?[o]:[],[...s,...c?h:r]].map(e=>e.join("\n")).join("\n\n")};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{bool as e,str as o}from"envalid";import{readFileSync as t}from"fs";import{readFile as i}from"fs/promises";import{arch as r,platform as n}from"os";import{dirname as a,join as s,resolve as l}from"path";import{P as p,match as d}from"ts-pattern";import{fileURLToPath as c}from"url";import u from"yargs";import{hideBin as E}from"yargs/helpers";import{z as v}from"zod";import{createEnvReader as f}from"@salsita-ai/common/env";import{DEFAULT_PROJECT_ALIAS as g,FeedbackType as m}from"@salsita-ai/contracts/domain";import{phoenixCli as y}from"#package/legacy";import{readSpecProject as h}from"./application-spec/read-spec-project.js";import{prepareDevelopmentEnvironment as R,prepareLocalEnvironment as S,runActivateDeploymentCommand as _,runBuildCommand as U,runChangelogCommand as O,runCheckCommand as P,runCleanCommand as b,runCleanupEnvironmentCommand as L,runCreateEnvironmentCommand as I,runDataCommand as N,runDeployCommand as T,runDeploymentBuildEnvsCommand as w,runDevCommand as k,runDocsCommand as D,runExtractSourcesCommand as j,runFeedbackCommand as G,runFinishDeploymentCommand as C,runFixCommand as A,runInitCommand as K,runInspectAssetsCommand as V,runLinkCommand as M,runListEnvironmentsCommand as J,runLoginCommand as B,runLogoutCommand as F,runPrepareCiCommand as Y,runPrepareDeploymentCommand as q,runRegisterDeploymentCommand as x,runSceneCommand as H,runScreenshotCommand as W,runStateCommand as $,runStoryCommand as X,runSyncCommand as z,runUnlinkCommand as Q}from"./commands/index.js";import{DEFAULT_PHOENIX_REGION as Z,PHOENIX_REGIONS as ee,PUBLIC_PHOENIX_REGIONS as eo,getRegionServerUrl as et,getRegionStudioUrl as ei,resolveSignedInDevelopmentEnvironment as er}from"./services/index.js";import{getIsEditorEnabled as en}from"./utils/get-is-editor-enabled.js";import{createLogger as ea}from"./utils/index.js";let es=(e,o,t)=>{e?.info(`Using ${o?"application-spec":"domain-spec"} flow (${t})`)},el=(e,o,t)=>{let i=t?.logger??ea();if(void 0!==e)return i.detail(`Application spec: ${e} (from CLI flag)`),es(t?.logger,e,"from CLI flag"),e;let r=process.env.USE_APPLICATION_SPEC;if(void 0!==r){let e="true"===r||"1"===r;return i.detail(`Application spec: ${e} (from environment variable)`),es(t?.logger,e,"from environment variable"),e}return void 0!==o?(i.detail(`Application spec: ${o} (from package.json phoenix.applicationFlow)`),es(t?.logger,o,"from package.json phoenix.applicationFlow"),o):(i.detail("Application spec: false (default)"),es(t?.logger,!1,"default"),!1)},ep=t(s(a(c(import.meta.url)),"../../package.json"),"utf-8");if(!ep)throw Error("Project package.json is required, please provide it in the package.json file");let ed=v.object({version:v.string({required_error:"Project version is required, please provide it in the package.json file"}),name:v.string({required_error:"Project name is required, please provide it in the package.json file"})}).parse(JSON.parse(ep)),ec=async()=>{try{let e=await i("./package.json","utf-8"),o=JSON.parse(e);return{name:o.name,applicationFlow:o.phoenix?.applicationFlow}}catch{return{name:void 0,applicationFlow:void 0}}},eu=e=>{if(!(e instanceof Error))return String(e);let o=(e=>{if(!(e instanceof Error))return;if(e.message.length>0)return e.message;let o=(e instanceof AggregateError?e.errors:[]).find(e=>e instanceof Error&&e.message.length>0);return o instanceof Error?o.message:"code"in e&&"string"==typeof e.code?e.code:void 0})(e.cause);return void 0===o?e.message:`${e.message}: ${o}`};await u(E(process.argv)).scriptName("phoenix").usage("$0 <command> [options]").command(["build","b"],"Build the project",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, defaults to project name in package.json)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("onlyFrontend",{alias:"F",type:"boolean",description:"Build only frontend bundle"}).option("onlyWebhook",{alias:"W",type:"boolean",description:"Build only webhooks"}).option("force",{alias:"f",type:"boolean",description:"Force full rebuild, skip cache (env: FORCE_REBUILD, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}),async t=>{let i,r=f({PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),ENABLE_EDITOR:e({default:!0}),DEBUG:e({default:!1}),BUILD_TARGET:o({choices:["frontend","webhook","both"],default:"both"}),FORCE_REBUILD:e({default:!1})})(),n=ea({debug:t.debug??r.DEBUG}),a=en(t.editor,r.ENABLE_EDITOR),s=t.force??r.FORCE_REBUILD,l=await ec(),p=el(t.applicationSpec,l.applicationFlow,{logger:n}),d=t.projectSlug??r.PROJECT_SLUG??l.name,c=t.environmentSlug??r.ENVIRONMENT_SLUG??l.name;if(!d)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!c)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");let u=t.onlyFrontend,E=t.onlyWebhook;if(u&&E)throw Error("Cannot use --onlyFrontend and --onlyWebhook flags together, they are mutually exclusive");i=u?"frontend":E?"webhook":r.BUILD_TARGET,await (p?U:y.runBuildCommand)({sdkVersion:ed.version,projectSlug:d,environmentSlug:c,cliUseWorkspace:t.workspace,enableEditor:a,buildTarget:i,force:s},{logger:n})}).command(["clean","cl"],"Clean build artifacts, reinstall dependencies, and rebuild specs",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, defaults to project name in package.json)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}),async t=>{let i=f({PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),ENABLE_EDITOR:e({default:!0}),DEBUG:e({default:!1})})(),r=ea({debug:t.debug??i.DEBUG}),n=en(t.editor,i.ENABLE_EDITOR),a=await ec(),s=el(t.applicationSpec,a.applicationFlow,{logger:r}),l=t.projectSlug??i.PROJECT_SLUG??a.name,p=t.environmentSlug??i.ENVIRONMENT_SLUG??a.name;if(!l)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!p)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");await (s?b:y.runCleanCommand)({sdkVersion:ed.version,projectSlug:l,environmentSlug:p,cliUseWorkspace:t.workspace,enableEditor:n},{logger:r})}).command(["dev","d"],"Start development mode (Vite, spec watching, and the webhook tunnel)",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("editorWsPort",{alias:"ep",type:"string",description:"Port for the editor WebSocket server (defaults to EDITOR_WS_PORT env or 3020)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG; required in server mode unless --local; offline modes default to the package name)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG; required in server mode unless --local; offline modes default to the package name)"}).option("withLingui",{alias:"wl",type:"boolean",description:"Enable or disable i18n messages extraction and compilation (defaults to WITH_LINGUI env or false)"}).option("persistence",{alias:"P",type:"string",description:"Persistence mode for the configurator (defaults to PERSISTENCE_MODE env or server)",choices:["memory","local-storage","server"]}).option("force",{alias:"f",type:"boolean",description:"Force full rebuild, skip cache (env: FORCE_REBUILD, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}).option("tui",{alias:"T",type:"boolean",description:"Render logs in a terminal UI with per-stream pages and split view; requires an interactive terminal (env: PHOENIX_TUI, default: false)"}).option("local",{type:"boolean",description:"Use local-mode development environment defaults (env: PHOENIX_LOCAL, default: false)"}).option("region",{choices:eo,description:`Phoenix region of the workspace you are signed in to, used when .env has no SERVER_URL (default: ${Z})`}).option("serverUrl",{type:"string",description:"URL of the Phoenix server, instead of SERVER_URL or the region default"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket when the development deployment is prepared (env: SKIP_UPLOAD, default: false)"}),async t=>{let i=f({ENABLE_EDITOR:e({default:!0}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),EDITOR_WS_PORT:o({default:"3020"}),DEBUG:e({default:!1}),WITH_LINGUI:e({default:!1}),PERSISTENCE_MODE:o({default:void 0}),FORCE_REBUILD:e({default:!1}),PHOENIX_TUI:e({default:!1}),SERVER_URL:o({default:void 0}),DEVELOPMENT_KEY:o({default:void 0}),PHOENIX_LOCAL:e({default:!1}),PHOENIX_REGION:o({choices:ee,default:void 0}),SKIP_UPLOAD:e({default:!1})})(),r=t.debug??i.DEBUG,n=ea({debug:r}),a=en(t.editor,i.ENABLE_EDITOR),s=t.editorWsPort??i.EDITOR_WS_PORT,l=t.force??i.FORCE_REBUILD,c=t.withLingui??i.WITH_LINGUI,u=t.persistence??i.PERSISTENCE_MODE,E=!u||"server"===u,v=t.tui??i.PHOENIX_TUI,m=await ec(),R=el(t.applicationSpec,m.applicationFlow,{logger:n}),S=t.local??i.PHOENIX_LOCAL,_=t.projectSlug??i.PROJECT_SLUG,U=E&&R&&!S&&!_?.length?await h(process.cwd()):void 0,{serverUrl:O,developmentKey:P,apiToken:b,projectSlug:L,environmentSlug:I}=await d({useServer:E,local:S,serverUrl:t.serverUrl??i.SERVER_URL,developmentKey:i.DEVELOPMENT_KEY,projectSlug:_?.length?_:U,environmentSlug:t.environmentSlug??i.ENVIRONMENT_SLUG}).with({useServer:!1},async({serverUrl:e,developmentKey:o,projectSlug:t,environmentSlug:i})=>({serverUrl:e,developmentKey:o,apiToken:void 0,projectSlug:t??m.name,environmentSlug:i??m.name})).with({local:!0},async({serverUrl:e,developmentKey:o,projectSlug:t,environmentSlug:i})=>({serverUrl:e?.length?e:"http://localhost:3000",developmentKey:o?.length?o:"dev_local-dev-key-12345",apiToken:void 0,projectSlug:t?.length?t:"local",environmentSlug:i?.length?i:"dev-local"})).with({developmentKey:p.string.minLength(1)},()=>U===g,()=>{throw Error(`phoenix dev has a DEVELOPMENT_KEY, but the spec says \`project: ${g}\`, which only a signed-in workspace can resolve. Set PROJECT_SLUG in .env by pasting the .env block of your Studio development environment, or name the project's slug in the spec.`)}).with({serverUrl:p.string.minLength(1),developmentKey:p.string.minLength(1),projectSlug:p.string.minLength(1),environmentSlug:p.string.minLength(1)},async({serverUrl:e,developmentKey:o,projectSlug:t,environmentSlug:i})=>({serverUrl:e,developmentKey:o,apiToken:void 0,projectSlug:t,environmentSlug:i})).with({developmentKey:p.union(void 0,""),projectSlug:p.string.minLength(1)},()=>R,async({serverUrl:e,projectSlug:o})=>{let r=e?.length?e:et(t.region??i.PHOENIX_REGION??Z),a=await er({serverUrl:r,project:o});return n.info(`Developing in ${a.projectSlug}/${a.environmentSlug} of workspace "${a.workspaceName}" on ${r}`),{serverUrl:r,developmentKey:void 0,apiToken:a.apiToken,projectSlug:a.projectSlug,environmentSlug:a.environmentSlug}}).with({developmentKey:p.union(void 0,""),projectSlug:p.union(void 0,"")},()=>R,()=>{throw Error(`phoenix dev does not know which project to develop in. Add \`project: ${g}\` to spec/application.yaml to use the default project of the workspace you are signed in to, or paste the .env block of a Studio development environment into .env. Pass --local to use the local-mode server.`)}).otherwise(()=>{throw Error("phoenix dev needs SERVER_URL, PROJECT_SLUG, ENVIRONMENT_SLUG, and DEVELOPMENT_KEY in .env. Create a development environment for your project in Studio and paste its .env block, or pass --local to use the local-mode server.")});if(!L)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!I)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");let N={sdkVersion:ed.version,projectSlug:L,environmentSlug:I,cliUseWorkspace:t.workspace,enableEditor:a,editorWsPort:s,debug:r,withLingui:c,persistenceMode:u,force:l,tui:v,serverUrl:O,skipUpload:t.skipUpload??i.SKIP_UPLOAD};if(R){let e=P?{developmentKey:P}:b?{apiToken:b}:void 0;await k({...N,credential:e},{logger:n})}else await y.runDevCommand({...N,developmentKey:P},{logger:n})}).command(["link","l"],"Link local SDK for development",e=>e.option("sdk-path",{type:"string",description:"Path to the SDK repository",default:"../configurator-phoenix"}),async e=>{let o=ea();await M({sdkPath:e.sdkPath},{logger:o})}).command(["unlink","ul"],"Remove local SDK linking",()=>{},async()=>{let e=ea();await Q({logger:e})}).command(["sync","s"],"Sync project files and compile specs without building vite/webhooks",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, defaults to project name in package.json)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("force",{alias:"f",type:"boolean",description:"Force full rebuild, skip cache (env: FORCE_REBUILD, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}).option("analyze",{alias:"a",type:"boolean",description:"Print pipeline metrics flamegraph after build (requires --applicationSpec)"}),async t=>{let i=f({ENABLE_EDITOR:e({default:!0}),DEBUG:e({default:!1}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),FORCE_REBUILD:e({default:!1})})(),r=ea({debug:t.debug??i.DEBUG}),n=en(t.editor,i.ENABLE_EDITOR),a=t.force??i.FORCE_REBUILD,s=await ec(),l=el(t.applicationSpec,s.applicationFlow,{logger:r}),p=t.projectSlug??i.PROJECT_SLUG??s.name,d=t.environmentSlug??i.ENVIRONMENT_SLUG??s.name;if(!p)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!d)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");await (l?z:y.runSyncCommand)({sdkVersion:ed.version,projectSlug:p,environmentSlug:d,cliUseWorkspace:t.workspace,enableEditor:n,force:a,analyze:t.analyze},{logger:r})}).command("init [folder]","Start a Phoenix project: write package.json when the folder has none, a starter spec and pnpm-workspace.yaml with the pnpm settings the install needs. Continue with phoenix sync, phoenix login and phoenix dev",e=>e.positional("folder",{type:"string",description:"Folder to create the project in (default: the working directory)"}).option("scaffold",{type:"boolean",hidden:!0,description:"Accepted for compatibility and ignored: init always only writes the starter project"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging"}),async e=>{let o=ea({debug:e.debug??!1});try{await K({sdkVersion:ed.version,projectRoot:void 0===e.folder?void 0:l(e.folder)},{logger:o})}catch(e){o.error(e instanceof Error?e.message:String(e)),process.exit(1)}}).command(["story","st"],"Storybook example utilities",e=>X(e),()=>{}).command(["check","c"],"Run checks (TypeScript, ESLint, Prettier). Runs all by default, or only selected when any of --types/--lint/--format is passed.",e=>e.option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("types",{type:"boolean",description:"Run TypeScript check"}).option("lint",{type:"boolean",description:"Run ESLint check"}).option("format",{type:"boolean",description:"Run Prettier check"}),async o=>{let t=f({DEBUG:e({default:!1})})(),i=ea({debug:o.debug??t.DEBUG});await P({types:o.types,lint:o.lint,format:o.format},{logger:i})}).command(["fix","f"],"Fix linting and formatting issues. Runs all by default, or only selected when any of --lint/--format is passed.",e=>e.option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("lint",{type:"boolean",description:"Run ESLint fix"}).option("format",{type:"boolean",description:"Run Prettier fix"}),async o=>{let t=f({DEBUG:e({default:!1})})(),i=ea({debug:o.debug??t.DEBUG});await A({lint:o.lint,format:o.format},{logger:i})}).command(["changelog","clog"],"Display SDK changelog",e=>e.option("ver",{type:"string",description:"Show specific version (e.g., 0.36.0)"}).option("all",{alias:"a",type:"boolean",description:"Show all versions (warning: large output)"}).option("page",{alias:"p",type:"number",description:"Page number (3 versions per page)"}).option("list",{alias:"l",type:"boolean",description:"List version numbers only"}),async e=>{let o=ea();await O({version:e.ver,all:e.all,page:e.page,list:e.list},{logger:o})}).command(["inspect:assets","ia"],"Inspect 3D assets (glTF/GLB) — nodes, transforms, bounds, origin, materials, morph targets, animations",e=>e.option("file",{alias:"f",type:"string",description:"Path to specific glTF/GLB file"}).option("objects",{alias:"O",type:"boolean",description:"Show only object/node names"}).option("materials",{alias:"m",type:"boolean",description:"Show only material names"}).option("morphs",{alias:"M",type:"boolean",description:"Show only morph target names"}).option("animations",{alias:"a",type:"boolean",description:"Show only animation names"}).option("json",{alias:"j",type:"boolean",description:"Output as JSON"}),async e=>{let o=ea();await V({file:e.file,objects:e.objects,materials:e.materials,morphs:e.morphs,animations:e.animations,json:e.json},{logger:o})}).command(["screenshot","ss"],"Capture a screenshot of the configurator canvas",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (defaults to SCREENSHOT_OUTPUT env or ./screenshot.png)"}).option("width",{alias:"w",type:"number",description:"Width in pixels (default: 1920)"}).option("height",{alias:"H",type:"number",description:"Height in pixels (default: 1080)"}).option("format",{alias:"f",type:"string",description:"Image format: PNG or JPEG (default: PNG)"}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"}),SCREENSHOT_OUTPUT:o({default:"./screenshot.png"})})(),i=ea();await W({port:e.port??t.EDITOR_WS_PORT,output:e.output??t.SCREENSHOT_OUTPUT,width:e.width,height:e.height,format:e.format},{logger:i})}).command(["inspect:state","is"],"Get the current editor state as JSON (entities, navigation, validation)",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (prints to stdout if omitted)"}).option("sections",{alias:"s",type:"string",description:"Comma-separated sections: entities,navigation,validation (default: all)"}).option("pretty",{alias:"P",type:"boolean",description:"Pretty-print JSON output (default: true)",default:!0}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"})})(),i=ea();await $({port:e.port??t.EDITOR_WS_PORT,output:e.output,sections:e.sections,pretty:e.pretty},{logger:i})}).command(["inspect:data","id"],"Get the current editor context data as JSON (published, frontend, backend, session, access, web component)",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (prints to stdout if omitted)"}).option("pretty",{alias:"P",type:"boolean",description:"Pretty-print JSON output (default: true)",default:!0}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"})})(),i=ea();await N({port:e.port??t.EDITOR_WS_PORT,output:e.output,pretty:e.pretty},{logger:i})}).command(["inspect:scene","isc"],"Get the current Three.js scene graph as JSON",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (prints to stdout if omitted)"}).option("pretty",{alias:"P",type:"boolean",description:"Pretty-print JSON output (default: true)",default:!0}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"})})(),i=ea();await H({port:e.port??t.EDITOR_WS_PORT,output:e.output,pretty:e.pretty},{logger:i})}).command(["docs","doc"],"Browse SDK documentation",e=>e.option("read",{alias:"r",type:"string",description:"Read a specific doc file (e.g., docs/phoenix/admin.mdx)"}).option("category",{alias:"c",type:"string",description:"Show all docs in a category"}).option("list",{alias:"l",type:"boolean",description:"List all docs with paths and titles"}).option("search",{alias:"s",type:"string",description:"Search doc content for a term (case-insensitive)"}).option("dir",{type:"boolean",description:"Print the absolute path of the docs directory"}),async e=>{let o=ea();await D({read:e.read,category:e.category,list:e.list,search:e.search,dir:e.dir},{logger:o})}).command(["prepare:ci","pci","ci"],"Prepare CI environment by copying .env.ci to .env",()=>{},async()=>{let e=ea();await Y({logger:e})}).command({command:"environment:create",aliases:["env:create"],describe:"Create a new deployment environment",deprecated:"Switch to a new workflow and use deployment:prepare instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("name",{alias:"n",type:"string",description:"Name of the environment to be created"}).option("slug",{type:"string",description:"Slug of the customer to be created"}).option("uuid",{alias:"u",type:"string",description:"UUID of the environment to be created"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment UUID to",default:".env.generated"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await I({server:o.server,apiKey:o.apiKey,name:o.name,slug:o.slug,uuid:o.uuid,outFile:o.outFile,debug:i},{logger:r})}}).command({command:"environment:list",aliases:["env:list"],describe:"List all deployment environments",deprecated:"Switch to a new workflow and use the prepare environment flow instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await J({server:o.server,apiKey:o.apiKey,debug:i},{logger:r})}}).command(["environment:cleanup","env:cleanup","ec"],"Cleanup a transient deployment environment",e=>e.option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key (env: PROJECT_KEY, required)"}).option("projectSlug",{alias:"p",type:"string",description:"Project slug (env: PROJECT_SLUG, required)"}).option("environmentSlug",{alias:"e",type:"string",description:"Environment slug (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write cleanup result env variables to (env: OUT_FILE, default: .env.generated)",default:".env.generated"}),async t=>{let i=f({DEBUG:e({default:!1}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),SERVER_URL:o({default:void 0}),OUT_FILE:o({default:void 0})})(),r=t.debug??i.DEBUG,n=t.apiKey??i.ENVIRONMENT_API_KEY,a=t.projectKey??i.PROJECT_KEY,s=t.projectSlug??i.PROJECT_SLUG,l=await ec(),p=t.environmentSlug??i.ENVIRONMENT_SLUG??l.name,d=t.serverUrl??i.SERVER_URL,c=t.outFile??i.OUT_FILE??".env.generated";if(!n)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");if(!a)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");if(!s)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");if(!p)throw Error("Environment slug is required, provide via --environmentSlug or -e, or set ENVIRONMENT_SLUG environment variable");if(!d)throw Error("Server URL is required, provide via --serverUrl or -su, or set SERVER_URL environment variable");let u=ea({debug:r});await L({server:d,apiKey:n,projectKey:a,projectSlug:s,environmentSlug:p,debug:r,outFile:c},{logger:u})}).command(["login <customer>"],"Sign the CLI in to an SDK-builder workspace; you approve it in Studio",e=>e.positional("customer",{type:"string",demandOption:!0,description:"Slug of the SDK-builder workspace (customer)"}).option("region",{choices:eo,description:`Phoenix region the workspace lives in (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}).option("studioUrl",{type:"string",description:"URL of Studio for the workspace, instead of the region default"}).option("open",{type:"boolean",default:!0,description:"Open the approval page in the default browser (--no-open to only print the link)"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0})})(),i=e.region??t.PHOENIX_REGION??Z,r=ea();try{await B({customer:e.customer,serverUrl:e.serverUrl??et(i),studioUrl:e.studioUrl??ei(i,e.customer),open:e.open},{logger:r})}catch(e){r.error(eu(e)),process.exit(1)}}).command(["deploy"],"Upload this SDK-builder project and follow its build until it is live",e=>e.option("region",{choices:eo,description:`Phoenix region the workspace lives in (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}).option("wait",{type:"boolean",default:!0,description:"Follow the build until it finishes (--no-wait to return once it starts)"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0})})(),i=e.region??t.PHOENIX_REGION??Z,r=ea();try{await T({serverUrl:e.serverUrl??et(i),sdkVersion:ed.version,wait:e.wait,projectDir:process.cwd(),pollIntervalMs:3e3},{logger:r})}catch(e){r.error(eu(e)),process.exit(1)}}).command(["logout"],"Revoke the API token of an SDK-builder workspace and forget it on this computer",e=>e.option("region",{choices:eo,description:`Phoenix region to sign out of (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0})})(),i=e.region??t.PHOENIX_REGION??Z,r=ea();try{await F({serverUrl:e.serverUrl??et(i)},{logger:r})}catch(e){r.error(eu(e)),process.exit(1)}}).command(["feedback <message>"],"Send feedback about the SDK, CLI, docs or Studio to the Phoenix team",e=>e.positional("message",{type:"string",demandOption:!0,description:"What you want to tell the Phoenix team"}).option("type",{choices:[m.Bug,m.Idea,m.Other],default:m.Other,description:"What the feedback is about"}).option("contact",{type:"string",description:"How to reach you, when you want a reply"}).option("agent",{type:"string",description:"Name of the coding agent that writes the feedback"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the workspace project the feedback is about (env: PROJECT_SLUG, defaults to `project` of the application spec)"}).option("region",{choices:eo,description:`Phoenix region the workspace lives in (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0}),PROJECT_SLUG:o({default:void 0})})(),i=ea(),a=e.region??t.PHOENIX_REGION??Z,s=e.projectSlug??t.PROJECT_SLUG,l=s?.length?s:await h(process.cwd()).catch(()=>{i.warn("The feedback is sent without a project, because `project` could not be read from the application spec. Pass --projectSlug to name the project.")});try{await G({serverUrl:e.serverUrl??et(a),message:e.message,type:e.type,contact:e.contact,agent:e.agent,project:l,sdkVersion:ed.version,clientInfo:`${n()} ${r()}, Node.js ${process.versions.node}`},{logger:i})}catch(e){i.error(eu(e)),process.exit(1)}}).command({command:"deployment:register",aliases:["dep:register","dr"],describe:"Register deployment configuration",deprecated:"Switch to a new workflow and use deployment:prepare and deployment:finish instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the deployment ID to",default:".env.generated"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip uploading assets",default:!1}).option("activate",{alias:"a",type:"boolean",description:"Activate deployment after registration",default:!0}).option("overrideSchema",{alias:"os",type:"boolean",description:"Override existing schema",default:!1}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await x({server:o.server,apiKey:o.apiKey,outFile:o.outFile,skipUpload:o.skipUpload,activate:o.activate,overrideSchema:o.overrideSchema,debug:i},{logger:r})}}).command({command:"deployment:activate",aliases:["dep:activate","da"],describe:"Activate a deployment",deprecated:"Switch to a new workflow and use deployment:prepare and deployment:finish instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("uuid",{alias:"u",type:"string",description:"UUID of the deployment to activate"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await _({server:o.server,apiKey:o.apiKey,uuid:o.uuid,debug:i},{logger:r})}}).command(["deployment:prepare","dep:prepare","dp"],"Prepare environment and register deployment (env: ENVIRONMENT_API_KEY, PROJECT_KEY, PROJECT_SLUG, PROJECT_REF, PROJECT_SHA, ENVIRONMENT_SLUG, OUT_FILE, SKIP_UPLOAD, OVERRIDE_SCHEMA, SERVER_URL)",e=>e.option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (will be created if it does not exist) (env: ENVIRONMENT_SLUG, required)"}).option("projectRef",{type:"string",description:"Source branch, tag, or ref recorded as deployment provenance (env: PROJECT_REF)"}).option("projectSha",{type:"string",description:"Full commit SHA of the checked-out project revision (env: PROJECT_SHA)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("overrideSchema",{alias:"os",type:"boolean",description:"Allows to override deployment schemas (env: OVERRIDE_SCHEMA, default: false)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("uploadLinksFile",{alias:"ulf",type:"string",description:"File to write upload links to (used by finish command) (default: .upload-links.json)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, required)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),PROJECT_REF:o({default:void 0}),PROJECT_SHA:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),OUT_FILE:o({default:".env.generated"}),SKIP_UPLOAD:e({default:!1}),OVERRIDE_SCHEMA:e({default:!1}),SERVER_URL:o({default:void 0})})(),r=t.debug??i.DEBUG,n=t.apiKey??i.ENVIRONMENT_API_KEY;if(!n)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let a=t.projectKey??i.PROJECT_KEY;if(!a)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let s=t.projectSlug??i.PROJECT_SLUG;if(!s)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");let l=t.environmentSlug??i.ENVIRONMENT_SLUG;if(!l)throw Error("Environment slug is required, provide via --environmentSlug or -e, or set ENVIRONMENT_SLUG environment variable");let p=t.serverUrl??i.SERVER_URL;if(!p)throw Error("Server URL is required, provide via --serverUrl or -s, or set SERVER_URL environment variable");let d=await ec(),c=ea({debug:r}),u=el(t.applicationSpec,d.applicationFlow,{logger:c});await (u?q:y.runPrepareDeploymentCommand)({apiKey:n,projectKey:a,projectSlug:s,projectRef:t.projectRef??i.PROJECT_REF,projectSha:t.projectSha??i.PROJECT_SHA,environmentSlug:l,outFile:t.outFile??i.OUT_FILE,skipUpload:t.skipUpload??i.SKIP_UPLOAD,overrideSchema:t.overrideSchema??i.OVERRIDE_SCHEMA,uploadLinksFile:t.uploadLinksFile??".upload-links.json",serverUrl:p,debug:r,projectVersion:ed.version},{logger:c})}).command(["deployment:prepare-dev","dep:prepare-dev","dpd"],"Prepare a development deployment (env: SERVER_URL, PROJECT_SLUG, ENVIRONMENT_SLUG, DEVELOPMENT_KEY, OUT_FILE, SKIP_UPLOAD, OVERRIDE_SCHEMA)",e=>e.option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required unless --local)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the development environment (env: ENVIRONMENT_SLUG, required unless --local)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("overrideSchema",{alias:"os",type:"boolean",description:"Allows overriding deployment schemas (env: OVERRIDE_SCHEMA, default: true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}).option("local",{type:"boolean",description:"Use local-mode development environment defaults (env: PHOENIX_LOCAL, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),SERVER_URL:o({default:void 0}),DEVELOPMENT_KEY:o({default:void 0}),PHOENIX_LOCAL:e({default:!1}),OUT_FILE:o({default:".env.generated"}),SKIP_UPLOAD:e({default:!1}),OVERRIDE_SCHEMA:e({default:!0})})(),r=t.debug??i.DEBUG,n=ea({debug:r}),a=t.local??i.PHOENIX_LOCAL,s=i.SERVER_URL,l=t.projectSlug??i.PROJECT_SLUG,p=t.environmentSlug??i.ENVIRONMENT_SLUG,d=i.DEVELOPMENT_KEY;if(a&&(s=s?.length?s:"http://localhost:3000",l=l?.length?l:"local",p=p?.length?p:"dev-local",d=d?.length?d:"dev_local-dev-key-12345"),!s||!l||!p||!d)throw Error("phoenix deployment:prepare-dev needs SERVER_URL, PROJECT_SLUG, ENVIRONMENT_SLUG, and DEVELOPMENT_KEY in .env. Create a development environment for your project in Studio and paste its .env block, or pass --local to use the local-mode server.");let c=await ec(),u=el(t.applicationSpec,c.applicationFlow,{logger:n}),E={serverUrl:s,projectSlug:l,environmentSlug:p,outFile:t.outFile??i.OUT_FILE,skipUpload:t.skipUpload??i.SKIP_UPLOAD,overrideSchema:t.overrideSchema??i.OVERRIDE_SCHEMA,debug:r,projectVersion:ed.version};try{u?await R({...E,credential:{developmentKey:d}},{logger:n}):await y.prepareDevelopmentEnvironment({...E,developmentKey:d},{logger:n})}catch(e){n.error(`Development environment preparation failed: ${e instanceof Error?e.message:String(e)}`,e),process.exit(1)}}).command(["deployment:prepare-local","dep:prepare-local","dpl"],"Prepare local environment for development (env: PROJECT_KEY, PROJECT_SLUG, OUT_FILE, SKIP_UPLOAD, OVERRIDE_SCHEMA, SERVER_URL, LAMBDA_URL)",e=>e.option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, default: local)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, default: project name in package.json)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("overrideSchema",{alias:"os",type:"boolean",description:"Allows to override deployment schemas (env: OVERRIDE_SCHEMA, default: true)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, default: http://localhost:3000)"}).option("lambdaUrl",{alias:"l",type:"string",description:"Webhook URL (env: LAMBDA_URL, default: http://localhost:8080)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),ENVIRONMENT_SLUG:o({default:void 0}),PROJECT_KEY:o({default:"project_local-dev-key-12345"}),PROJECT_SLUG:o({default:"local"}),OUT_FILE:o({default:".env.generated"}),SKIP_UPLOAD:e({default:!1}),OVERRIDE_SCHEMA:e({default:!0}),SERVER_URL:o({default:"http://localhost:3000"}),LAMBDA_URL:o({default:"http://localhost:8080"}),ENVIRONMENT_API_KEY:o({default:"local-dev-key-12345"})})(),r=t.debug??i.DEBUG,n=t.projectKey??i.PROJECT_KEY;if(!n)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let a=await ec(),s=t.environmentSlug??i.ENVIRONMENT_SLUG??a.name;if(!s)throw Error("Environment slug is required, provide via --environmentSlug or -e, or set ENVIRONMENT_SLUG environment variable");let l=t.apiKey??i.ENVIRONMENT_API_KEY;if(!l)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let p=ea({debug:r}),d=el(t.applicationSpec,a.applicationFlow,{logger:p});try{await (d?S:y.prepareLocalEnvironment)({apiKey:l,projectKey:n,projectSlug:t.projectSlug??i.PROJECT_SLUG,environmentSlug:s,outFile:t.outFile??i.OUT_FILE,skipUpload:t.skipUpload??i.SKIP_UPLOAD,overrideSchema:t.overrideSchema??i.OVERRIDE_SCHEMA,serverUrl:t.serverUrl??i.SERVER_URL,lambdaUrl:t.lambdaUrl??i.LAMBDA_URL,debug:r,projectVersion:ed.version},{logger:p})}catch(e){p.error(`Local environment preparation failed: ${e instanceof Error?e.message:String(e)}`,e),process.exit(1)}}).command(["deployment:extract-sources <archive> <folder>"],"Validate the source archive of a phoenix deploy and extract its project files into a new folder. Links, special files, unsafe paths and oversized content are refused; entries that are not project files are left out",e=>e.positional("archive",{type:"string",demandOption:!0,description:"The source archive (.tgz)"}).positional("folder",{type:"string",demandOption:!0,description:"New or empty folder to extract the project files into"}),async e=>{let o=ea();try{await j({archivePath:e.archive,targetDir:e.folder},{logger:o})}catch(e){o.error(e instanceof Error?e.message:String(e)),process.exit(1)}}).command(["deployment:build-envs","dep:build-envs","dbe"],"Write the environment variables for the build step of a prepared deployment that builds apart from its deploy (env: DEPLOYMENT_ID, ENVIRONMENT_API_KEY, PROJECT_KEY, PROJECT_SLUG, OUT_FILE, SERVER_URL)",e=>e.option("uuid",{alias:"u",type:"string",description:"Id of the prepared deployment (env: DEPLOYMENT_ID, required)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, required)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),DEPLOYMENT_ID:o({default:void 0}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),OUT_FILE:o({default:".env.generated"}),SERVER_URL:o({default:void 0})})(),r=t.debug??i.DEBUG,n=t.uuid??i.DEPLOYMENT_ID;if(!n)throw Error("Deployment ID is required, provide via --uuid or -u, or set DEPLOYMENT_ID environment variable");let a=t.apiKey??i.ENVIRONMENT_API_KEY;if(!a)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let s=t.projectKey??i.PROJECT_KEY;if(!s)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let l=t.projectSlug??i.PROJECT_SLUG;if(!l)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");let p=t.serverUrl??i.SERVER_URL;if(!p)throw Error("Server URL is required, provide via --serverUrl or -s, or set SERVER_URL environment variable");let d=ea({debug:r});await w({uuid:n,apiKey:a,projectKey:s,projectSlug:l,outFile:t.outFile??i.OUT_FILE,serverUrl:p,debug:r},{logger:d})}).command(["deployment:finish","dep:finish","df"],"Upload files to S3 and activate deployment (env: DEPLOYMENT_ID, ENVIRONMENT_API_KEY, PROJECT_KEY, PROJECT_SLUG, LAMBDA_URL, SERVER_URL, SKIP_UPLOAD)",e=>e.option("uuid",{alias:"u",type:"string",description:"Id of the deployment to be activated (env: DEPLOYMENT_ID, required)"}).option("uploadLinksFile",{alias:"ulf",type:"string",description:"File containing upload links (generated by prepare command) (default: .upload-links.json)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required)"}).option("lambdaUrl",{alias:"l",type:"string",description:"Lambda webhook URL for the deployment (env: LAMBDA_URL, required)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, required)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),DEPLOYMENT_ID:o({default:void 0}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),LAMBDA_URL:o({default:void 0}),SERVER_URL:o({default:void 0}),SKIP_UPLOAD:e({default:!1})})(),r=t.debug??i.DEBUG,n=t.uuid??i.DEPLOYMENT_ID;if(!n)throw Error("Deployment ID is required, provide via --uuid or -u, or set DEPLOYMENT_ID environment variable");let a=t.apiKey??i.ENVIRONMENT_API_KEY;if(!a)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let s=t.projectKey??i.PROJECT_KEY;if(!s)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let l=t.projectSlug??i.PROJECT_SLUG;if(!l)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");let p=t.lambdaUrl??i.LAMBDA_URL;if(!p)throw Error("Lambda URL is required, provide via --lambdaUrl or -l, or set LAMBDA_URL environment variable");let d=t.serverUrl??i.SERVER_URL;if(!d)throw Error("Server URL is required, provide via --serverUrl or -s, or set SERVER_URL environment variable");let c=ea({debug:r});await C({uuid:n,uploadLinksFile:t.uploadLinksFile??".upload-links.json",apiKey:a,projectKey:s,projectSlug:l,lambdaUrl:p,serverUrl:d,skipUpload:t.skipUpload??i.SKIP_UPLOAD,debug:r},{logger:c})}).demandCommand(1,"Please specify a command").help().alias("help","h").version(ed.version).alias("version","v").strict().parse();
2
+ import{bool as e,str as o}from"envalid";import{readFileSync as t}from"fs";import{readFile as i}from"fs/promises";import{arch as r,platform as n}from"os";import{dirname as a,join as s,resolve as l}from"path";import{P as p,match as d}from"ts-pattern";import{fileURLToPath as c}from"url";import u from"yargs";import{hideBin as E}from"yargs/helpers";import{z as v}from"zod";import{createEnvReader as f}from"@salsita-ai/common/env";import{DEFAULT_PROJECT_ALIAS as g,FeedbackType as m}from"@salsita-ai/contracts/domain";import{phoenixCli as y}from"#package/legacy";import{readSpecProject as h}from"./application-spec/read-spec-project.js";import{prepareDevelopmentEnvironment as R,prepareLocalEnvironment as S,runActivateDeploymentCommand as _,runBuildCommand as U,runChangelogCommand as O,runCheckCommand as P,runCleanCommand as b,runCleanupEnvironmentCommand as L,runCreateEnvironmentCommand as I,runDataCommand as N,runDeployCommand as T,runDeploymentBuildEnvsCommand as w,runDevCommand as k,runDocsCommand as D,runExtractSourcesCommand as j,runFeedbackCommand as G,runFinishDeploymentCommand as C,runFixCommand as A,runInitCommand as K,runInspectAssetsCommand as V,runLinkCommand as M,runListEnvironmentsCommand as J,runLoginCommand as B,runLogoutCommand as F,runPrepareCiCommand as Y,runPrepareDeploymentCommand as x,runRegisterDeploymentCommand as q,runSceneCommand as H,runScreenshotCommand as W,runStateCommand as $,runStoryCommand as X,runSyncCommand as z,runUnlinkCommand as Q}from"./commands/index.js";import{DEFAULT_PHOENIX_REGION as Z,PHOENIX_REGIONS as ee,PUBLIC_PHOENIX_REGIONS as eo,getRegionServerUrl as et,getRegionStudioUrl as ei,resolveSignedInDevelopmentEnvironment as er}from"./services/index.js";import{getIsEditorEnabled as en}from"./utils/get-is-editor-enabled.js";import{createLogger as ea}from"./utils/index.js";let es=(e,o,t)=>{e?.info(`Using ${o?"application-spec":"domain-spec"} flow (${t})`)},el=(e,o,t)=>{let i=t?.logger??ea();if(void 0!==e)return i.detail(`Application spec: ${e} (from CLI flag)`),es(t?.logger,e,"from CLI flag"),e;let r=process.env.USE_APPLICATION_SPEC;if(void 0!==r){let e="true"===r||"1"===r;return i.detail(`Application spec: ${e} (from environment variable)`),es(t?.logger,e,"from environment variable"),e}return void 0!==o?(i.detail(`Application spec: ${o} (from package.json phoenix.applicationFlow)`),es(t?.logger,o,"from package.json phoenix.applicationFlow"),o):(i.detail("Application spec: false (default)"),es(t?.logger,!1,"default"),!1)},ep=t(s(a(c(import.meta.url)),"../../package.json"),"utf-8");if(!ep)throw Error("Project package.json is required, please provide it in the package.json file");let ed=v.object({version:v.string({required_error:"Project version is required, please provide it in the package.json file"}),name:v.string({required_error:"Project name is required, please provide it in the package.json file"})}).parse(JSON.parse(ep)),ec=async()=>{try{let e=await i("./package.json","utf-8"),o=JSON.parse(e);return{name:o.name,applicationFlow:o.phoenix?.applicationFlow}}catch{return{name:void 0,applicationFlow:void 0}}},eu=e=>{if(!(e instanceof Error))return String(e);let o=(e=>{if(!(e instanceof Error))return;if(e.message.length>0)return e.message;let o=(e instanceof AggregateError?e.errors:[]).find(e=>e instanceof Error&&e.message.length>0);return o instanceof Error?o.message:"code"in e&&"string"==typeof e.code?e.code:void 0})(e.cause);return void 0===o?e.message:`${e.message}: ${o}`};await u(E(process.argv)).scriptName("phoenix").usage("$0 <command> [options]").command(["build","b"],"Build the project",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, defaults to project name in package.json)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("onlyFrontend",{alias:"F",type:"boolean",description:"Build only frontend bundle"}).option("onlyWebhook",{alias:"W",type:"boolean",description:"Build only webhooks"}).option("force",{alias:"f",type:"boolean",description:"Force full rebuild, skip cache (env: FORCE_REBUILD, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}).option("banner",{type:"string",requiresArg:!0,description:"Text for the comment at the top of every frontend .js file, public in the bundle (default: application version from the spec and the git commit when available)",coerce:e=>"string"==typeof e?e:e.join("\n")}),async t=>{let i,r=f({PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),ENABLE_EDITOR:e({default:!0}),DEBUG:e({default:!1}),BUILD_TARGET:o({choices:["frontend","webhook","both"],default:"both"}),FORCE_REBUILD:e({default:!1})})(),n=ea({debug:t.debug??r.DEBUG}),a=en(t.editor,r.ENABLE_EDITOR),s=t.force??r.FORCE_REBUILD,l=await ec(),p=el(t.applicationSpec,l.applicationFlow,{logger:n}),d=t.projectSlug??r.PROJECT_SLUG??l.name,c=t.environmentSlug??r.ENVIRONMENT_SLUG??l.name;if(!d)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!c)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");let u=t.onlyFrontend,E=t.onlyWebhook;if(u&&E)throw Error("Cannot use --onlyFrontend and --onlyWebhook flags together, they are mutually exclusive");i=u?"frontend":E?"webhook":r.BUILD_TARGET;let v={sdkVersion:ed.version,projectSlug:d,environmentSlug:c,cliUseWorkspace:t.workspace,enableEditor:a,buildTarget:i,force:s};await (p?U({...v,banner:t.banner},{logger:n}):y.runBuildCommand(v,{logger:n}))}).command(["clean","cl"],"Clean build artifacts, reinstall dependencies, and rebuild specs",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, defaults to project name in package.json)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}),async t=>{let i=f({PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),ENABLE_EDITOR:e({default:!0}),DEBUG:e({default:!1})})(),r=ea({debug:t.debug??i.DEBUG}),n=en(t.editor,i.ENABLE_EDITOR),a=await ec(),s=el(t.applicationSpec,a.applicationFlow,{logger:r}),l=t.projectSlug??i.PROJECT_SLUG??a.name,p=t.environmentSlug??i.ENVIRONMENT_SLUG??a.name;if(!l)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!p)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");await (s?b:y.runCleanCommand)({sdkVersion:ed.version,projectSlug:l,environmentSlug:p,cliUseWorkspace:t.workspace,enableEditor:n},{logger:r})}).command(["dev","d"],"Start development mode (Vite, spec watching, and the webhook tunnel)",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("editorWsPort",{alias:"ep",type:"string",description:"Port for the editor WebSocket server (defaults to EDITOR_WS_PORT env or 3020)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG; required in server mode unless --local; offline modes default to the package name)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG; required in server mode unless --local; offline modes default to the package name)"}).option("withLingui",{alias:"wl",type:"boolean",description:"Enable or disable i18n messages extraction and compilation (defaults to WITH_LINGUI env or false)"}).option("persistence",{alias:"P",type:"string",description:"Persistence mode for the configurator (defaults to PERSISTENCE_MODE env or server)",choices:["memory","local-storage","server"]}).option("force",{alias:"f",type:"boolean",description:"Force full rebuild, skip cache (env: FORCE_REBUILD, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}).option("tui",{alias:"T",type:"boolean",description:"Render logs in a terminal UI with per-stream pages and split view; requires an interactive terminal (env: PHOENIX_TUI, default: false)"}).option("local",{type:"boolean",description:"Use local-mode development environment defaults (env: PHOENIX_LOCAL, default: false)"}).option("region",{choices:eo,description:`Phoenix region of the workspace you are signed in to, used when .env has no SERVER_URL (default: ${Z})`}).option("serverUrl",{type:"string",description:"URL of the Phoenix server, instead of SERVER_URL or the region default"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket when the development deployment is prepared (env: SKIP_UPLOAD, default: false)"}),async t=>{let i=f({ENABLE_EDITOR:e({default:!0}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),EDITOR_WS_PORT:o({default:"3020"}),DEBUG:e({default:!1}),WITH_LINGUI:e({default:!1}),PERSISTENCE_MODE:o({default:void 0}),FORCE_REBUILD:e({default:!1}),PHOENIX_TUI:e({default:!1}),SERVER_URL:o({default:void 0}),DEVELOPMENT_KEY:o({default:void 0}),PHOENIX_LOCAL:e({default:!1}),PHOENIX_REGION:o({choices:ee,default:void 0}),SKIP_UPLOAD:e({default:!1})})(),r=t.debug??i.DEBUG,n=ea({debug:r}),a=en(t.editor,i.ENABLE_EDITOR),s=t.editorWsPort??i.EDITOR_WS_PORT,l=t.force??i.FORCE_REBUILD,c=t.withLingui??i.WITH_LINGUI,u=t.persistence??i.PERSISTENCE_MODE,E=!u||"server"===u,v=t.tui??i.PHOENIX_TUI,m=await ec(),R=el(t.applicationSpec,m.applicationFlow,{logger:n}),S=t.local??i.PHOENIX_LOCAL,_=t.projectSlug??i.PROJECT_SLUG,U=E&&R&&!S&&!_?.length?await h(process.cwd()):void 0,{serverUrl:O,developmentKey:P,apiToken:b,projectSlug:L,environmentSlug:I}=await d({useServer:E,local:S,serverUrl:t.serverUrl??i.SERVER_URL,developmentKey:i.DEVELOPMENT_KEY,projectSlug:_?.length?_:U,environmentSlug:t.environmentSlug??i.ENVIRONMENT_SLUG}).with({useServer:!1},async({serverUrl:e,developmentKey:o,projectSlug:t,environmentSlug:i})=>({serverUrl:e,developmentKey:o,apiToken:void 0,projectSlug:t??m.name,environmentSlug:i??m.name})).with({local:!0},async({serverUrl:e,developmentKey:o,projectSlug:t,environmentSlug:i})=>({serverUrl:e?.length?e:"http://localhost:3000",developmentKey:o?.length?o:"dev_local-dev-key-12345",apiToken:void 0,projectSlug:t?.length?t:"local",environmentSlug:i?.length?i:"dev-local"})).with({developmentKey:p.string.minLength(1)},()=>U===g,()=>{throw Error(`phoenix dev has a DEVELOPMENT_KEY, but the spec says \`project: ${g}\`, which only a signed-in workspace can resolve. Set PROJECT_SLUG in .env by pasting the .env block of your Studio development environment, or name the project's slug in the spec.`)}).with({serverUrl:p.string.minLength(1),developmentKey:p.string.minLength(1),projectSlug:p.string.minLength(1),environmentSlug:p.string.minLength(1)},async({serverUrl:e,developmentKey:o,projectSlug:t,environmentSlug:i})=>({serverUrl:e,developmentKey:o,apiToken:void 0,projectSlug:t,environmentSlug:i})).with({developmentKey:p.union(void 0,""),projectSlug:p.string.minLength(1)},()=>R,async({serverUrl:e,projectSlug:o})=>{let r=e?.length?e:et(t.region??i.PHOENIX_REGION??Z),a=await er({serverUrl:r,project:o});return n.info(`Developing in ${a.projectSlug}/${a.environmentSlug} of workspace "${a.workspaceName}" on ${r}`),{serverUrl:r,developmentKey:void 0,apiToken:a.apiToken,projectSlug:a.projectSlug,environmentSlug:a.environmentSlug}}).with({developmentKey:p.union(void 0,""),projectSlug:p.union(void 0,"")},()=>R,()=>{throw Error(`phoenix dev does not know which project to develop in. Add \`project: ${g}\` to spec/application.yaml to use the default project of the workspace you are signed in to, or paste the .env block of a Studio development environment into .env. Pass --local to use the local-mode server.`)}).otherwise(()=>{throw Error("phoenix dev needs SERVER_URL, PROJECT_SLUG, ENVIRONMENT_SLUG, and DEVELOPMENT_KEY in .env. Create a development environment for your project in Studio and paste its .env block, or pass --local to use the local-mode server.")});if(!L)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!I)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");let N={sdkVersion:ed.version,projectSlug:L,environmentSlug:I,cliUseWorkspace:t.workspace,enableEditor:a,editorWsPort:s,debug:r,withLingui:c,persistenceMode:u,force:l,tui:v,serverUrl:O,skipUpload:t.skipUpload??i.SKIP_UPLOAD};if(R){let e=P?{developmentKey:P}:b?{apiToken:b}:void 0;await k({...N,credential:e},{logger:n})}else await y.runDevCommand({...N,developmentKey:P},{logger:n})}).command(["link","l"],"Link local SDK for development",e=>e.option("sdk-path",{type:"string",description:"Path to the SDK repository",default:"../configurator-phoenix"}),async e=>{let o=ea();await M({sdkPath:e.sdkPath},{logger:o})}).command(["unlink","ul"],"Remove local SDK linking",()=>{},async()=>{let e=ea();await Q({logger:e})}).command(["sync","s"],"Sync project files and compile specs without building vite/webhooks",e=>e.option("workspace",{alias:"w",type:"boolean",description:"Override workspace mode (uses .phoenix.json config by default)"}).option("editor",{type:"boolean",description:"Enable or disable editor files generation (defaults to ENABLE_EDITOR env or true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, defaults to project name in package.json)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("force",{alias:"f",type:"boolean",description:"Force full rebuild, skip cache (env: FORCE_REBUILD, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}).option("analyze",{alias:"a",type:"boolean",description:"Print pipeline metrics flamegraph after build (requires --applicationSpec)"}),async t=>{let i=f({ENABLE_EDITOR:e({default:!0}),DEBUG:e({default:!1}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),FORCE_REBUILD:e({default:!1})})(),r=ea({debug:t.debug??i.DEBUG}),n=en(t.editor,i.ENABLE_EDITOR),a=t.force??i.FORCE_REBUILD,s=await ec(),l=el(t.applicationSpec,s.applicationFlow,{logger:r}),p=t.projectSlug??i.PROJECT_SLUG??s.name,d=t.environmentSlug??i.ENVIRONMENT_SLUG??s.name;if(!p)throw Error("Project slug is required, provide via --projectSlug, set PROJECT_SLUG env, or ensure package.json has a name field");if(!d)throw Error("Environment slug is required, provide via --environmentSlug, set ENVIRONMENT_SLUG env, or ensure package.json has a name field");await (l?z:y.runSyncCommand)({sdkVersion:ed.version,projectSlug:p,environmentSlug:d,cliUseWorkspace:t.workspace,enableEditor:n,force:a,analyze:t.analyze},{logger:r})}).command("init [folder]","Start a Phoenix project: write package.json when the folder has none, a starter spec and pnpm-workspace.yaml with the pnpm settings the install needs. Continue with phoenix sync, phoenix login and phoenix dev",e=>e.positional("folder",{type:"string",description:"Folder to create the project in (default: the working directory)"}).option("scaffold",{type:"boolean",hidden:!0,description:"Accepted for compatibility and ignored: init always only writes the starter project"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging"}),async e=>{let o=ea({debug:e.debug??!1});try{await K({sdkVersion:ed.version,projectRoot:void 0===e.folder?void 0:l(e.folder)},{logger:o})}catch(e){o.error(e instanceof Error?e.message:String(e)),process.exit(1)}}).command(["story","st"],"Storybook example utilities",e=>X(e),()=>{}).command(["check","c"],"Run checks (TypeScript, ESLint, Prettier). Runs all by default, or only selected when any of --types/--lint/--format is passed.",e=>e.option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("types",{type:"boolean",description:"Run TypeScript check"}).option("lint",{type:"boolean",description:"Run ESLint check"}).option("format",{type:"boolean",description:"Run Prettier check"}),async o=>{let t=f({DEBUG:e({default:!1})})(),i=ea({debug:o.debug??t.DEBUG});await P({types:o.types,lint:o.lint,format:o.format},{logger:i})}).command(["fix","f"],"Fix linting and formatting issues. Runs all by default, or only selected when any of --lint/--format is passed.",e=>e.option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("lint",{type:"boolean",description:"Run ESLint fix"}).option("format",{type:"boolean",description:"Run Prettier fix"}),async o=>{let t=f({DEBUG:e({default:!1})})(),i=ea({debug:o.debug??t.DEBUG});await A({lint:o.lint,format:o.format},{logger:i})}).command(["changelog","clog"],"Display SDK changelog",e=>e.option("ver",{type:"string",description:"Show specific version (e.g., 0.36.0)"}).option("all",{alias:"a",type:"boolean",description:"Show all versions (warning: large output)"}).option("page",{alias:"p",type:"number",description:"Page number (3 versions per page)"}).option("list",{alias:"l",type:"boolean",description:"List version numbers only"}),async e=>{let o=ea();await O({version:e.ver,all:e.all,page:e.page,list:e.list},{logger:o})}).command(["inspect:assets","ia"],"Inspect 3D assets (glTF/GLB) — nodes, transforms, bounds, origin, materials, morph targets, animations",e=>e.option("file",{alias:"f",type:"string",description:"Path to specific glTF/GLB file"}).option("objects",{alias:"O",type:"boolean",description:"Show only object/node names"}).option("materials",{alias:"m",type:"boolean",description:"Show only material names"}).option("morphs",{alias:"M",type:"boolean",description:"Show only morph target names"}).option("animations",{alias:"a",type:"boolean",description:"Show only animation names"}).option("json",{alias:"j",type:"boolean",description:"Output as JSON"}),async e=>{let o=ea();await V({file:e.file,objects:e.objects,materials:e.materials,morphs:e.morphs,animations:e.animations,json:e.json},{logger:o})}).command(["screenshot","ss"],"Capture a screenshot of the configurator canvas",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (defaults to SCREENSHOT_OUTPUT env or ./screenshot.png)"}).option("width",{alias:"w",type:"number",description:"Width in pixels (default: 1920)"}).option("height",{alias:"H",type:"number",description:"Height in pixels (default: 1080)"}).option("format",{alias:"f",type:"string",description:"Image format: PNG or JPEG (default: PNG)"}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"}),SCREENSHOT_OUTPUT:o({default:"./screenshot.png"})})(),i=ea();await W({port:e.port??t.EDITOR_WS_PORT,output:e.output??t.SCREENSHOT_OUTPUT,width:e.width,height:e.height,format:e.format},{logger:i})}).command(["inspect:state","is"],"Get the current editor state as JSON (entities, navigation, validation)",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (prints to stdout if omitted)"}).option("sections",{alias:"s",type:"string",description:"Comma-separated sections: entities,navigation,validation (default: all)"}).option("pretty",{alias:"P",type:"boolean",description:"Pretty-print JSON output (default: true)",default:!0}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"})})(),i=ea();await $({port:e.port??t.EDITOR_WS_PORT,output:e.output,sections:e.sections,pretty:e.pretty},{logger:i})}).command(["inspect:data","id"],"Get the current editor context data as JSON (published, frontend, backend, session, access, web component)",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (prints to stdout if omitted)"}).option("pretty",{alias:"P",type:"boolean",description:"Pretty-print JSON output (default: true)",default:!0}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"})})(),i=ea();await N({port:e.port??t.EDITOR_WS_PORT,output:e.output,pretty:e.pretty},{logger:i})}).command(["inspect:scene","isc"],"Get the current Three.js scene graph as JSON",e=>e.option("port",{alias:"p",type:"string",description:"WebSocket server port (defaults to EDITOR_WS_PORT env or 3020)"}).option("output",{alias:"o",type:"string",description:"Output file path (prints to stdout if omitted)"}).option("pretty",{alias:"P",type:"boolean",description:"Pretty-print JSON output (default: true)",default:!0}),async e=>{let t=f({EDITOR_WS_PORT:o({default:"3020"})})(),i=ea();await H({port:e.port??t.EDITOR_WS_PORT,output:e.output,pretty:e.pretty},{logger:i})}).command(["docs","doc"],"Browse SDK documentation",e=>e.option("read",{alias:"r",type:"string",description:"Read a specific doc file (e.g., docs/phoenix/admin.mdx)"}).option("category",{alias:"c",type:"string",description:"Show all docs in a category"}).option("list",{alias:"l",type:"boolean",description:"List all docs with paths and titles"}).option("search",{alias:"s",type:"string",description:"Search doc content for a term (case-insensitive)"}).option("dir",{type:"boolean",description:"Print the absolute path of the docs directory"}),async e=>{let o=ea();await D({read:e.read,category:e.category,list:e.list,search:e.search,dir:e.dir},{logger:o})}).command(["prepare:ci","pci","ci"],"Prepare CI environment by copying .env.ci to .env",()=>{},async()=>{let e=ea();await Y({logger:e})}).command({command:"environment:create",aliases:["env:create"],describe:"Create a new deployment environment",deprecated:"Switch to a new workflow and use deployment:prepare instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("name",{alias:"n",type:"string",description:"Name of the environment to be created"}).option("slug",{type:"string",description:"Slug of the customer to be created"}).option("uuid",{alias:"u",type:"string",description:"UUID of the environment to be created"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment UUID to",default:".env.generated"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await I({server:o.server,apiKey:o.apiKey,name:o.name,slug:o.slug,uuid:o.uuid,outFile:o.outFile,debug:i},{logger:r})}}).command({command:"environment:list",aliases:["env:list"],describe:"List all deployment environments",deprecated:"Switch to a new workflow and use the prepare environment flow instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await J({server:o.server,apiKey:o.apiKey,debug:i},{logger:r})}}).command(["environment:cleanup","env:cleanup","ec"],"Cleanup a transient deployment environment",e=>e.option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key (env: PROJECT_KEY, required)"}).option("projectSlug",{alias:"p",type:"string",description:"Project slug (env: PROJECT_SLUG, required)"}).option("environmentSlug",{alias:"e",type:"string",description:"Environment slug (env: ENVIRONMENT_SLUG, defaults to project name in package.json)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write cleanup result env variables to (env: OUT_FILE, default: .env.generated)",default:".env.generated"}),async t=>{let i=f({DEBUG:e({default:!1}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),SERVER_URL:o({default:void 0}),OUT_FILE:o({default:void 0})})(),r=t.debug??i.DEBUG,n=t.apiKey??i.ENVIRONMENT_API_KEY,a=t.projectKey??i.PROJECT_KEY,s=t.projectSlug??i.PROJECT_SLUG,l=await ec(),p=t.environmentSlug??i.ENVIRONMENT_SLUG??l.name,d=t.serverUrl??i.SERVER_URL,c=t.outFile??i.OUT_FILE??".env.generated";if(!n)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");if(!a)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");if(!s)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");if(!p)throw Error("Environment slug is required, provide via --environmentSlug or -e, or set ENVIRONMENT_SLUG environment variable");if(!d)throw Error("Server URL is required, provide via --serverUrl or -su, or set SERVER_URL environment variable");let u=ea({debug:r});await L({server:d,apiKey:n,projectKey:a,projectSlug:s,environmentSlug:p,debug:r,outFile:c},{logger:u})}).command(["login <customer>"],"Sign the CLI in to an SDK-builder workspace; you approve it in Studio",e=>e.positional("customer",{type:"string",demandOption:!0,description:"Slug of the SDK-builder workspace (customer)"}).option("region",{choices:eo,description:`Phoenix region the workspace lives in (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}).option("studioUrl",{type:"string",description:"URL of Studio for the workspace, instead of the region default"}).option("open",{type:"boolean",default:!0,description:"Open the approval page in the default browser (--no-open to only print the link)"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0})})(),i=e.region??t.PHOENIX_REGION??Z,r=ea();try{await B({customer:e.customer,serverUrl:e.serverUrl??et(i),studioUrl:e.studioUrl??ei(i,e.customer),open:e.open},{logger:r})}catch(e){r.error(eu(e)),process.exit(1)}}).command(["deploy"],"Upload this SDK-builder project and follow its build until it is live",e=>e.option("region",{choices:eo,description:`Phoenix region the workspace lives in (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}).option("wait",{type:"boolean",default:!0,description:"Follow the build until it finishes (--no-wait to return once it starts)"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0})})(),i=e.region??t.PHOENIX_REGION??Z,r=ea();try{await T({serverUrl:e.serverUrl??et(i),sdkVersion:ed.version,wait:e.wait,projectDir:process.cwd(),pollIntervalMs:3e3},{logger:r})}catch(e){r.error(eu(e)),process.exit(1)}}).command(["logout"],"Revoke the API token of an SDK-builder workspace and forget it on this computer",e=>e.option("region",{choices:eo,description:`Phoenix region to sign out of (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0})})(),i=e.region??t.PHOENIX_REGION??Z,r=ea();try{await F({serverUrl:e.serverUrl??et(i)},{logger:r})}catch(e){r.error(eu(e)),process.exit(1)}}).command(["feedback [message]"],"Send feedback about the SDK, CLI, docs or Studio to the Phoenix team",e=>e.positional("message",{type:"string",description:"What you want to tell the Phoenix team; leave it out when you pass --file"}).option("file",{type:"string",description:"Path of a text file that holds the message, for a long report instead of the argument"}).option("type",{choices:[m.Bug,m.Idea,m.Other],default:m.Other,description:"What the feedback is about"}).option("contact",{type:"string",description:"How to reach you, when you want a reply"}).option("agent",{type:"string",description:"Name of the coding agent that writes the feedback"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the workspace project the feedback is about (env: PROJECT_SLUG, defaults to `project` of the application spec)"}).option("region",{choices:eo,description:`Phoenix region the workspace lives in (default: ${Z})`}).option("serverUrl",{alias:"su",type:"string",description:"URL of the Phoenix server, instead of the region default"}),async e=>{let t=f({PHOENIX_REGION:o({choices:ee,default:void 0}),PROJECT_SLUG:o({default:void 0})})(),i=ea(),a=e.region??t.PHOENIX_REGION??Z,s=e.projectSlug??t.PROJECT_SLUG,l=s?.length?s:await h(process.cwd()).catch(()=>{i.warn("The feedback is sent without a project, because `project` could not be read from the application spec. Pass --projectSlug to name the project.")});try{await G({serverUrl:e.serverUrl??et(a),message:e.message,file:e.file,type:e.type,contact:e.contact,agent:e.agent,project:l,sdkVersion:ed.version,clientInfo:`${n()} ${r()}, Node.js ${process.versions.node}`},{logger:i})}catch(e){i.error(eu(e)),process.exit(1)}}).command({command:"deployment:register",aliases:["dep:register","dr"],describe:"Register deployment configuration",deprecated:"Switch to a new workflow and use deployment:prepare and deployment:finish instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the deployment ID to",default:".env.generated"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip uploading assets",default:!1}).option("activate",{alias:"a",type:"boolean",description:"Activate deployment after registration",default:!0}).option("overrideSchema",{alias:"os",type:"boolean",description:"Override existing schema",default:!1}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await q({server:o.server,apiKey:o.apiKey,outFile:o.outFile,skipUpload:o.skipUpload,activate:o.activate,overrideSchema:o.overrideSchema,debug:i},{logger:r})}}).command({command:"deployment:activate",aliases:["dep:activate","da"],describe:"Activate a deployment",deprecated:"Switch to a new workflow and use deployment:prepare and deployment:finish instead",builder:e=>e.option("server",{alias:"s",type:"string",description:"URL of the Phoenix server (defaults to SERVER_URL env)"}).option("apiKey",{alias:"k",type:"string",description:"API key for server access (defaults to ENVIRONMENT_API_KEY env)"}).option("uuid",{alias:"u",type:"string",description:"UUID of the deployment to activate"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (defaults to DEBUG env or false)"}),handler:async o=>{let t=f({DEBUG:e({default:!1})})(),i=o.debug??t.DEBUG,r=ea({debug:i});await _({server:o.server,apiKey:o.apiKey,uuid:o.uuid,debug:i},{logger:r})}}).command(["deployment:prepare","dep:prepare","dp"],"Prepare environment and register deployment (env: ENVIRONMENT_API_KEY, PROJECT_KEY, PROJECT_SLUG, PROJECT_REF, PROJECT_SHA, ENVIRONMENT_SLUG, OUT_FILE, SKIP_UPLOAD, OVERRIDE_SCHEMA, SERVER_URL)",e=>e.option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (will be created if it does not exist) (env: ENVIRONMENT_SLUG, required)"}).option("projectRef",{type:"string",description:"Source branch, tag, or ref recorded as deployment provenance (env: PROJECT_REF)"}).option("projectSha",{type:"string",description:"Full commit SHA of the checked-out project revision (env: PROJECT_SHA)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("overrideSchema",{alias:"os",type:"boolean",description:"Allows to override deployment schemas (env: OVERRIDE_SCHEMA, default: false)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("uploadLinksFile",{alias:"ulf",type:"string",description:"File to write upload links to (used by finish command) (default: .upload-links.json)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, required)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),PROJECT_REF:o({default:void 0}),PROJECT_SHA:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),OUT_FILE:o({default:".env.generated"}),SKIP_UPLOAD:e({default:!1}),OVERRIDE_SCHEMA:e({default:!1}),SERVER_URL:o({default:void 0})})(),r=t.debug??i.DEBUG,n=t.apiKey??i.ENVIRONMENT_API_KEY;if(!n)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let a=t.projectKey??i.PROJECT_KEY;if(!a)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let s=t.projectSlug??i.PROJECT_SLUG;if(!s)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");let l=t.environmentSlug??i.ENVIRONMENT_SLUG;if(!l)throw Error("Environment slug is required, provide via --environmentSlug or -e, or set ENVIRONMENT_SLUG environment variable");let p=t.serverUrl??i.SERVER_URL;if(!p)throw Error("Server URL is required, provide via --serverUrl or -s, or set SERVER_URL environment variable");let d=await ec(),c=ea({debug:r}),u=el(t.applicationSpec,d.applicationFlow,{logger:c});await (u?x:y.runPrepareDeploymentCommand)({apiKey:n,projectKey:a,projectSlug:s,projectRef:t.projectRef??i.PROJECT_REF,projectSha:t.projectSha??i.PROJECT_SHA,environmentSlug:l,outFile:t.outFile??i.OUT_FILE,skipUpload:t.skipUpload??i.SKIP_UPLOAD,overrideSchema:t.overrideSchema??i.OVERRIDE_SCHEMA,uploadLinksFile:t.uploadLinksFile??".upload-links.json",serverUrl:p,debug:r,projectVersion:ed.version},{logger:c})}).command(["deployment:prepare-dev","dep:prepare-dev","dpd"],"Prepare a development deployment (env: SERVER_URL, PROJECT_SLUG, ENVIRONMENT_SLUG, DEVELOPMENT_KEY, OUT_FILE, SKIP_UPLOAD, OVERRIDE_SCHEMA)",e=>e.option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required unless --local)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the development environment (env: ENVIRONMENT_SLUG, required unless --local)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("overrideSchema",{alias:"os",type:"boolean",description:"Allows overriding deployment schemas (env: OVERRIDE_SCHEMA, default: true)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}).option("local",{type:"boolean",description:"Use local-mode development environment defaults (env: PHOENIX_LOCAL, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),PROJECT_SLUG:o({default:void 0}),ENVIRONMENT_SLUG:o({default:void 0}),SERVER_URL:o({default:void 0}),DEVELOPMENT_KEY:o({default:void 0}),PHOENIX_LOCAL:e({default:!1}),OUT_FILE:o({default:".env.generated"}),SKIP_UPLOAD:e({default:!1}),OVERRIDE_SCHEMA:e({default:!0})})(),r=t.debug??i.DEBUG,n=ea({debug:r}),a=t.local??i.PHOENIX_LOCAL,s=i.SERVER_URL,l=t.projectSlug??i.PROJECT_SLUG,p=t.environmentSlug??i.ENVIRONMENT_SLUG,d=i.DEVELOPMENT_KEY;if(a&&(s=s?.length?s:"http://localhost:3000",l=l?.length?l:"local",p=p?.length?p:"dev-local",d=d?.length?d:"dev_local-dev-key-12345"),!s||!l||!p||!d)throw Error("phoenix deployment:prepare-dev needs SERVER_URL, PROJECT_SLUG, ENVIRONMENT_SLUG, and DEVELOPMENT_KEY in .env. Create a development environment for your project in Studio and paste its .env block, or pass --local to use the local-mode server.");let c=await ec(),u=el(t.applicationSpec,c.applicationFlow,{logger:n}),E={serverUrl:s,projectSlug:l,environmentSlug:p,outFile:t.outFile??i.OUT_FILE,skipUpload:t.skipUpload??i.SKIP_UPLOAD,overrideSchema:t.overrideSchema??i.OVERRIDE_SCHEMA,debug:r,projectVersion:ed.version};try{u?await R({...E,credential:{developmentKey:d}},{logger:n}):await y.prepareDevelopmentEnvironment({...E,developmentKey:d},{logger:n})}catch(e){n.error(`Development environment preparation failed: ${e instanceof Error?e.message:String(e)}`,e),process.exit(1)}}).command(["deployment:prepare-local","dep:prepare-local","dpl"],"Prepare local environment for development (env: PROJECT_KEY, PROJECT_SLUG, OUT_FILE, SKIP_UPLOAD, OVERRIDE_SCHEMA, SERVER_URL, LAMBDA_URL)",e=>e.option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, default: local)"}).option("environmentSlug",{alias:"e",type:"string",description:"Slug of the environment (env: ENVIRONMENT_SLUG, default: project name in package.json)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("overrideSchema",{alias:"os",type:"boolean",description:"Allows to override deployment schemas (env: OVERRIDE_SCHEMA, default: true)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, default: http://localhost:3000)"}).option("lambdaUrl",{alias:"l",type:"string",description:"Webhook URL (env: LAMBDA_URL, default: http://localhost:8080)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("applicationSpec",{alias:"as",type:"boolean",description:"Use application-spec pipeline (env: USE_APPLICATION_SPEC, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),ENVIRONMENT_SLUG:o({default:void 0}),PROJECT_KEY:o({default:"project_local-dev-key-12345"}),PROJECT_SLUG:o({default:"local"}),OUT_FILE:o({default:".env.generated"}),SKIP_UPLOAD:e({default:!1}),OVERRIDE_SCHEMA:e({default:!0}),SERVER_URL:o({default:"http://localhost:3000"}),LAMBDA_URL:o({default:"http://localhost:8080"}),ENVIRONMENT_API_KEY:o({default:"local-dev-key-12345"})})(),r=t.debug??i.DEBUG,n=t.projectKey??i.PROJECT_KEY;if(!n)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let a=await ec(),s=t.environmentSlug??i.ENVIRONMENT_SLUG??a.name;if(!s)throw Error("Environment slug is required, provide via --environmentSlug or -e, or set ENVIRONMENT_SLUG environment variable");let l=t.apiKey??i.ENVIRONMENT_API_KEY;if(!l)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let p=ea({debug:r}),d=el(t.applicationSpec,a.applicationFlow,{logger:p});try{await (d?S:y.prepareLocalEnvironment)({apiKey:l,projectKey:n,projectSlug:t.projectSlug??i.PROJECT_SLUG,environmentSlug:s,outFile:t.outFile??i.OUT_FILE,skipUpload:t.skipUpload??i.SKIP_UPLOAD,overrideSchema:t.overrideSchema??i.OVERRIDE_SCHEMA,serverUrl:t.serverUrl??i.SERVER_URL,lambdaUrl:t.lambdaUrl??i.LAMBDA_URL,debug:r,projectVersion:ed.version},{logger:p})}catch(e){p.error(`Local environment preparation failed: ${e instanceof Error?e.message:String(e)}`,e),process.exit(1)}}).command(["deployment:extract-sources <archive> <folder>"],"Validate the source archive of a phoenix deploy and extract its project files into a new folder. Links, special files, unsafe paths and oversized content are refused; entries that are not project files are left out",e=>e.positional("archive",{type:"string",demandOption:!0,description:"The source archive (.tgz)"}).positional("folder",{type:"string",demandOption:!0,description:"New or empty folder to extract the project files into"}),async e=>{let o=ea();try{await j({archivePath:e.archive,targetDir:e.folder},{logger:o})}catch(e){o.error(e instanceof Error?e.message:String(e)),process.exit(1)}}).command(["deployment:build-envs","dep:build-envs","dbe"],"Write the environment variables for the build step of a prepared deployment that builds apart from its deploy (env: DEPLOYMENT_ID, ENVIRONMENT_API_KEY, PROJECT_KEY, PROJECT_SLUG, OUT_FILE, SERVER_URL)",e=>e.option("uuid",{alias:"u",type:"string",description:"Id of the prepared deployment (env: DEPLOYMENT_ID, required)"}).option("outFile",{alias:"o",type:"string",description:"Output file to write the environment variables to (env: OUT_FILE, default: .env.generated)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, required)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),DEPLOYMENT_ID:o({default:void 0}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),OUT_FILE:o({default:".env.generated"}),SERVER_URL:o({default:void 0})})(),r=t.debug??i.DEBUG,n=t.uuid??i.DEPLOYMENT_ID;if(!n)throw Error("Deployment ID is required, provide via --uuid or -u, or set DEPLOYMENT_ID environment variable");let a=t.apiKey??i.ENVIRONMENT_API_KEY;if(!a)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let s=t.projectKey??i.PROJECT_KEY;if(!s)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let l=t.projectSlug??i.PROJECT_SLUG;if(!l)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");let p=t.serverUrl??i.SERVER_URL;if(!p)throw Error("Server URL is required, provide via --serverUrl or -s, or set SERVER_URL environment variable");let d=ea({debug:r});await w({uuid:n,apiKey:a,projectKey:s,projectSlug:l,outFile:t.outFile??i.OUT_FILE,serverUrl:p,debug:r},{logger:d})}).command(["deployment:finish","dep:finish","df"],"Upload files to S3 and activate deployment (env: DEPLOYMENT_ID, ENVIRONMENT_API_KEY, PROJECT_KEY, PROJECT_SLUG, LAMBDA_URL, SERVER_URL, SKIP_UPLOAD)",e=>e.option("uuid",{alias:"u",type:"string",description:"Id of the deployment to be activated (env: DEPLOYMENT_ID, required)"}).option("uploadLinksFile",{alias:"ulf",type:"string",description:"File containing upload links (generated by prepare command) (default: .upload-links.json)"}).option("apiKey",{alias:"a",type:"string",description:"API key for server access (env: ENVIRONMENT_API_KEY, required)"}).option("projectKey",{alias:"k",type:"string",description:"Project key to access the Project resources (env: PROJECT_KEY, required)"}).option("projectSlug",{alias:"p",type:"string",description:"Slug of the project (env: PROJECT_SLUG, required)"}).option("lambdaUrl",{alias:"l",type:"string",description:"Lambda webhook URL for the deployment (env: LAMBDA_URL, required)"}).option("serverUrl",{alias:"s",type:"string",description:"PHX server URL (env: SERVER_URL, required)"}).option("skipUpload",{alias:"su",type:"boolean",description:"Skip upload of resources to S3 bucket (env: SKIP_UPLOAD, default: false)"}).option("debug",{alias:"D",type:"boolean",description:"Enable debug mode for detailed logging (env: DEBUG, default: false)"}),async t=>{let i=f({DEBUG:e({default:!1}),DEPLOYMENT_ID:o({default:void 0}),ENVIRONMENT_API_KEY:o({default:void 0}),PROJECT_KEY:o({default:void 0}),PROJECT_SLUG:o({default:void 0}),LAMBDA_URL:o({default:void 0}),SERVER_URL:o({default:void 0}),SKIP_UPLOAD:e({default:!1})})(),r=t.debug??i.DEBUG,n=t.uuid??i.DEPLOYMENT_ID;if(!n)throw Error("Deployment ID is required, provide via --uuid or -u, or set DEPLOYMENT_ID environment variable");let a=t.apiKey??i.ENVIRONMENT_API_KEY;if(!a)throw Error("API key is required, provide via --apiKey or -a, or set ENVIRONMENT_API_KEY environment variable");let s=t.projectKey??i.PROJECT_KEY;if(!s)throw Error("Project key is required, provide via --projectKey or -k, or set PROJECT_KEY environment variable");let l=t.projectSlug??i.PROJECT_SLUG;if(!l)throw Error("Project slug is required, provide via --projectSlug or -p, or set PROJECT_SLUG environment variable");let p=t.lambdaUrl??i.LAMBDA_URL;if(!p)throw Error("Lambda URL is required, provide via --lambdaUrl or -l, or set LAMBDA_URL environment variable");let d=t.serverUrl??i.SERVER_URL;if(!d)throw Error("Server URL is required, provide via --serverUrl or -s, or set SERVER_URL environment variable");let c=ea({debug:r});await C({uuid:n,uploadLinksFile:t.uploadLinksFile??".upload-links.json",apiKey:a,projectKey:s,projectSlug:l,lambdaUrl:p,serverUrl:d,skipUpload:t.skipUpload??i.SKIP_UPLOAD,debug:r},{logger:c})}).demandCommand(1,"Please specify a command").help().alias("help","h").version(ed.version).alias("version","v").strict().parse();
@@ -8,5 +8,10 @@ export interface BuildCommandProps {
8
8
  readonly enableEditor?: boolean;
9
9
  readonly buildTarget?: BundleBuildTarget;
10
10
  readonly force?: boolean;
11
+ /**
12
+ * Text for the banner comment of every frontend JavaScript file; it is public in the bundles. Without it the
13
+ * comment names the application version and, in a git checkout, the commit.
14
+ */
15
+ readonly banner?: string;
11
16
  }
12
17
  export declare const runBuildCommand: (props: BuildCommandProps, context: CommandContext) => Promise<void>;
@@ -1 +1 @@
1
- import{rm as e}from"fs/promises";import{build as o}from"vite";import{getViteBuildConfigs as i}from"../services/index.js";import{checkBundleSizeBudgets as t}from"../utils/index.js";import{buildWebhooks as r}from"../webhooks/index.js";import{generateProjectFilesAndInstallDependencies as s}from"./generate-project-files.js";export const runBuildCommand=async(n,c)=>{let{logger:d}=c,{sdkVersion:l,projectSlug:u,environmentSlug:a,cliUseWorkspace:p,enableEditor:b,buildTarget:f="both",force:m=!1}=n;try{process.env.NODE_ENV="production",d.step("Building Phoenix project");let{templateFiles:n,applicationSpec:h}=await s({sdkVersion:l,projectSlug:u,environmentSlug:a,cliUseWorkspace:p,enableEditor:b,inlineTemplates:!0,force:m},c);if(d.success("Project files built successfully"),"frontend"===f||"both"===f){d.step("Cleaning frontend build directory");try{await e("./.phoenix/dist/frontend",{recursive:!0,force:!0}),d.debug("Frontend build directory cleaned")}catch(e){d.debug("No frontend build directory to clean")}for(let e of(d.step("Building Vite bundle"),await i({enableEditor:b,templateFiles:n})))await o(e);d.success("Vite build completed")}("webhook"===f||"both"===f)&&(d.step("Building webhooks"),await r({experimental:!0,webhookEntryPoint:"./.phoenix/.swc/.phoenix/webhook.js"}),d.success("Webhooks build completed")),void 0!==h&&await t({budgets:h.budgets,buildTarget:f},c),d.success("Build completed successfully!")}catch(e){d.error(`Build failed: ${e instanceof Error?e.message:String(e)}`,e),process.exit(1)}};
1
+ import{rm as e}from"fs/promises";import{build as o}from"vite";import{composeDefaultBanner as i,getViteBuildConfigs as t}from"../services/index.js";import{checkBundleSizeBudgets as r,readGitCommit as s}from"../utils/index.js";import{buildWebhooks as n}from"../webhooks/index.js";import{generateProjectFilesAndInstallDependencies as c}from"./generate-project-files.js";export const runBuildCommand=async(d,a)=>{let{logger:l}=a,{sdkVersion:p,projectSlug:u,environmentSlug:m,cliUseWorkspace:b,enableEditor:f,buildTarget:h="both",force:g=!1,banner:w}=d;try{process.env.NODE_ENV="production",l.step("Building Phoenix project");let{templateFiles:d,applicationSpec:y}=await c({sdkVersion:p,projectSlug:u,environmentSlug:m,cliUseWorkspace:b,enableEditor:f,inlineTemplates:!0,force:g},a);if(l.success("Project files built successfully"),"frontend"===h||"both"===h){l.step("Cleaning frontend build directory");try{await e("./.phoenix/dist/frontend",{recursive:!0,force:!0}),l.debug("Frontend build directory cleaned")}catch(e){l.debug("No frontend build directory to clean")}l.step("Building Vite bundle");let r=void 0===w?await s({directory:process.cwd(),trackedFile:"package.json"}):void 0;for(let e of(void 0===w&&void 0===r&&l.debug("No git commit found for the banner comment; it names the application version only"),await t({enableEditor:f,templateFiles:d,sdkVersion:p,banner:w??i({applicationVersion:y?.appMetadata.applicationVersion,commit:r})})))await o(e);l.success("Vite build completed")}("webhook"===h||"both"===h)&&(l.step("Building webhooks"),await n({experimental:!0,webhookEntryPoint:"./.phoenix/.swc/.phoenix/webhook.js"}),l.success("Webhooks build completed")),void 0!==y&&await r({budgets:y.budgets,buildTarget:h},a),l.success("Build completed successfully!")}catch(e){l.error(`Build failed: ${e instanceof Error?e.message:String(e)}`,e),process.exit(1)}};
@@ -1,4 +1,4 @@
1
- import{openAsBlob as e}from"node:fs";import{createApiBaseClient as t}from"#package/client";import{resolveApplicationSpecDeploymentData as i}from"../application-spec/index.js";import{createSourceArchive as r,getServerCredentials as o}from"../services/index.js";import{ensureWorkspaceInstallSettings as a}from"../utils/index.js";let s={queued:"Waiting for a build runner",preparing:"Preparing the deployment",building:"Building the project",deploying:"Deploying the frontend, webhooks and assets",live:"Live",failed:"Failed",cancelled:"Cancelled"},l=e=>new Promise(t=>setTimeout(t,e)),n=async(t,i)=>{let r=new FormData;for(let[e,i]of Object.entries(t.fields))r.append(e,i);r.append("file",await e(i,{type:"application/gzip"}),"sources.tgz");let o=await fetch(t.url,{method:"POST",body:r});if(!o.ok)throw Error(`Uploading the sources failed with HTTP ${o.status}: ${await o.text()}`)};export const runDeployCommand=async(e,{logger:d})=>{let u=await o(e.serverUrl),{pollIntervalMs:p}=e;if(!u)throw Error(`You are not signed in to ${e.serverUrl}. Run \`phoenix login <workspace>\` first.`);let c=t(e.serverUrl),f={authorization:`Bearer ${u.token}`};d.step("Validating the application spec");let h=await i({skipUpload:!0,logger:d});d.success(`The spec is valid (application version ${h.applicationVersion})`),d.step(`Packing the project for ${u.customerName}`),a(e.projectDir);let m=await r(e.projectDir);try{let t;d.info(` ${m.fileCount} files, ${(t=m.size)<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}`);let i=await c.POST("/deployments/builds",{body:{sdkVersion:e.sdkVersion,sizeBytes:m.size},headers:f});if(i.error||!i.data)throw Error(`The server did not create a build: ${i.error?.message??"no response"}`);let{buildId:r,upload:o}=i.data;d.step("Uploading the sources"),await n(o,m.path);let a=await c.POST("/deployments/builds/{buildId}/start",{params:{path:{buildId:r}},headers:{...f,"content-type":null}});if(a.error)throw Error(`The server did not start the build: ${a.error.message}`);if(a.data?.status==="failed")throw Error(`Build ${r} could not be started: ${a.data.error??"the server gave no reason"}`);if(d.success(`Build ${r} started`),u.studioUrl){let e=new URL(`/builder/deployments/${r}`,u.studioUrl);e.searchParams.set("customer",u.customerSlug),d.info(`Follow the build in Studio: ${e.toString()}`)}if(!e.wait)return;let h=null,g=0;for(;;){let{data:e,error:t}=await c.GET("/deployments/builds/{buildId}",{params:{path:{buildId:r}},headers:f}).catch(e=>({data:void 0,error:{message:String(e)}}));if(t||!e){if((g+=1)>=5)throw Error(`Following build ${r} failed: ${t?.message??"no response"}. The build may still finish; check Deployments in Studio.`);await l(p);continue}if(g=0,e.status!==h&&(h=e.status,d.step(s[e.status])),"live"===e.status)return void d.success(`Your configurator is live at ${e.configuratorUrl}`);if("failed"===e.status||"cancelled"===e.status||e.timedOut){let t=await c.GET("/deployments/builds/{buildId}/log",{params:{path:{buildId:r}},headers:f}).catch(()=>({data:void 0})),i=(t.data?.log??"").trim().split("\n").slice(-40).join("\n");i&&d.info(`
1
+ import{openAsBlob as e}from"node:fs";import{createApiBaseClient as t}from"#package/client";import{resolveApplicationSpecDeploymentData as i}from"../application-spec/index.js";import{createSourceArchive as r,getServerCredentials as a}from"../services/index.js";import{ensureWorkspaceInstallSettings as o}from"../utils/index.js";let s={queued:"Waiting for a build runner",preparing:"Preparing the deployment",building:"Building the project",deploying:"Deploying the frontend, webhooks and assets",live:"Live",failed:"Failed",cancelled:"Cancelled"},l=e=>new Promise(t=>setTimeout(t,e)),n=async(t,i)=>{let r=new FormData;for(let[e,i]of Object.entries(t.fields))r.append(e,i);r.append("file",await e(i,{type:"application/gzip"}),"sources.tgz");let a=await fetch(t.url,{method:"POST",body:r});if(!a.ok)throw Error(`Uploading the sources failed with HTTP ${a.status}: ${await a.text()}`)};export const runDeployCommand=async(e,{logger:d})=>{let u=await a(e.serverUrl),{pollIntervalMs:p}=e;if(!u)throw Error(`You are not signed in to ${e.serverUrl}. Run \`phoenix login <workspace>\` first.`);let c=t(e.serverUrl),m={authorization:`Bearer ${u.token}`};d.step("Validating the application spec");let h=await i({skipUpload:!0,logger:d});d.success(`The spec is valid (application version ${h.applicationVersion})`),d.step(`Packing the project for ${u.customerName}`),o(e.projectDir);let f=await r(e.projectDir);try{let t;d.info(` ${f.fileCount} files, ${(t=f.size)<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}`);let i=await c.POST("/deployments/builds",{body:{sdkVersion:e.sdkVersion,sizeBytes:f.size,configurationSchema:{version:h.schemaVersion,schema:h.schema},adminConfigurationSchema:h.adminSchema?{version:h.adminSchemaVersion,schema:h.adminSchema}:void 0},headers:m});if(i.error||!i.data)throw Error(`The server did not create a build: ${i.error?.message??"no response"}`);let{buildId:r,upload:a}=i.data;d.step("Uploading the sources"),await n(a,f.path);let o=await c.POST("/deployments/builds/{buildId}/start",{params:{path:{buildId:r}},headers:{...m,"content-type":null}});if(o.error)throw Error(`The server did not start the build: ${o.error.message}`);if(o.data?.status==="failed")throw Error(`Build ${r} could not be started: ${o.data.error??"the server gave no reason"}`);if(d.success(`Build ${r} started`),u.studioUrl){let e=new URL(`/builder/deployments/${r}`,u.studioUrl);e.searchParams.set("customer",u.customerSlug),d.info(`Follow the build in Studio: ${e.toString()}`)}if(!e.wait)return;let g=null,w=0;for(;;){let{data:e,error:t}=await c.GET("/deployments/builds/{buildId}",{params:{path:{buildId:r}},headers:m}).catch(e=>({data:void 0,error:{message:String(e)}}));if(t||!e){if((w+=1)>=5)throw Error(`Following build ${r} failed: ${t?.message??"no response"}. The build may still finish; check Deployments in Studio.`);await l(p);continue}if(w=0,e.status!==g&&(g=e.status,d.step(s[e.status])),"live"===e.status)return void d.success(`Your configurator is live at ${e.configuratorUrl}`);if("failed"===e.status||"cancelled"===e.status||e.timedOut){let t=await c.GET("/deployments/builds/{buildId}/log",{params:{path:{buildId:r}},headers:m}).catch(()=>({data:void 0})),i=(t.data?.log??"").trim().split("\n").slice(-40).join("\n");i&&d.info(`
2
2
  Last lines of the build log:
3
3
  ${i}
4
- `);let o=e.timedOut?"it took too long":e.error??"see the build log";throw Error(`Build ${r} did not go live: ${o}`)}await l(p)}}finally{await m.cleanup()}};
4
+ `);let a=e.timedOut?"it took too long":e.error??"see the build log";throw Error(`Build ${r} did not go live: ${a}`)}await l(p)}}finally{await f.cleanup()}};
@@ -2,7 +2,8 @@ import { type FeedbackType } from '@salsita-ai/contracts/domain';
2
2
  import type { CommandContext } from './types.js';
3
3
  export interface FeedbackCommandProps {
4
4
  readonly serverUrl: string;
5
- readonly message: string;
5
+ readonly message: string | undefined;
6
+ readonly file: string | undefined;
6
7
  readonly type: FeedbackType;
7
8
  readonly contact: string | undefined;
8
9
  readonly agent: string | undefined;
@@ -1 +1 @@
1
- import{FEEDBACK_CONTACT_MAX_LENGTH as e,FEEDBACK_MESSAGE_MAX_LENGTH as t}from"@salsita-ai/contracts/domain";import{createApiBaseClient as a}from"#package/client";import{getServerCredentials as r}from"../services/index.js";export const runFeedbackCommand=async(o,{logger:n})=>{let s=o.message.trim(),c=o.contact?.trim(),i=o.agent?.trim();if(0===s.length)throw Error('The feedback message is empty. Pass what you want to tell us: phoenix feedback "<message>".');if(s.length>t)throw Error(`The feedback message has ${s.length} characters, but at most ${t} are accepted. Shorten it and send it again.`);if(c&&c.length>e)throw Error(`The contact detail has ${c.length} characters, but at most ${e} are accepted. Shorten --contact and send the feedback again.`);let h=await r(o.serverUrl);if(!h)throw Error(`You are not signed in to ${o.serverUrl}, so the feedback was not sent. Run \`phoenix login <workspace>\` first, then send it again.`);let{error:d}=await a(o.serverUrl).POST("/feedback",{body:{message:s,type:o.type,clientVersion:o.sdkVersion,clientInfo:o.clientInfo,...c?{contact:c}:{},...i?{agent:i}:{},...o.project?{project:o.project}:{}},headers:{authorization:`Bearer ${h.token}`}});if(d)throw Error(`The server did not accept the feedback: ${d.message}`);n.success(`Feedback sent to the Phoenix team from workspace ${h.customerName}. Thank you.`)};
1
+ import{readFile as e}from"node:fs/promises";import{FEEDBACK_CONTACT_MAX_LENGTH as t,FEEDBACK_MESSAGE_MAX_LENGTH as a}from"@salsita-ai/contracts/domain";import{createApiBaseClient as r}from"#package/client";import{getServerCredentials as o}from"../services/index.js";let s=async t=>{if(void 0!==t.message&&void 0!==t.file)throw Error("Both a message and --file were given, so it is unclear which one to send. Pass the message as an argument or put it in the file, not both.");if(void 0!==t.file)return e(t.file,"utf8").catch(e=>{throw Error(`The feedback file ${t.file} could not be read: ${e instanceof Error?e.message:String(e)}. Check the path passed to --file and send the feedback again.`)});if(void 0===t.message)throw Error('No feedback message was given. Pass it as an argument, phoenix feedback "<message>", or in a text file with --file <path>.');return t.message};export const runFeedbackCommand=async(e,{logger:i})=>{let n=(await s(e)).trim(),c=e.contact?.trim(),h=e.agent?.trim();if(0===n.length)throw Error('The feedback message is empty. Pass what you want to tell us: phoenix feedback "<message>", or a text file with --file <path>.');if(n.length>a)throw Error(`The feedback message has ${n.length} characters, but at most ${a} are accepted. Shorten it and send it again.`);if(c&&c.length>t)throw Error(`The contact detail has ${c.length} characters, but at most ${t} are accepted. Shorten --contact and send the feedback again.`);let d=await o(e.serverUrl);if(!d)throw Error(`You are not signed in to ${e.serverUrl}, so the feedback was not sent. Run \`phoenix login <workspace>\` first, then send it again.`);let{error:f}=await r(e.serverUrl).POST("/feedback",{body:{message:n,type:e.type,clientVersion:e.sdkVersion,clientInfo:e.clientInfo,...c?{contact:c}:{},...h?{agent:h}:{},...e.project?{project:e.project}:{}},headers:{authorization:`Bearer ${d.token}`}});if(f)throw Error(`The server did not accept the feedback: ${f.message}`);i.success(`Feedback sent to the Phoenix team from workspace ${d.customerName}. Thank you.`)};
@@ -5,19 +5,37 @@ export interface LoginCommandProps {
5
5
  readonly studioUrl: string;
6
6
  readonly open: boolean;
7
7
  }
8
+ type LoginOutcome = {
9
+ readonly signedIn: true;
10
+ } | {
11
+ readonly signedIn: false;
12
+ readonly message: string;
13
+ };
14
+ interface LoginCallback {
15
+ readonly code: string;
16
+ readonly tokenName: string | null;
17
+ readonly finish: (outcome: LoginOutcome) => Promise<void>;
18
+ }
8
19
  interface LoginCallbackListener {
9
20
  readonly port: number;
10
- readonly code: Promise<string>;
21
+ readonly callback: Promise<LoginCallback>;
11
22
  readonly close: () => void;
12
23
  }
24
+ interface LoginCallbackListenerProps {
25
+ readonly state: string;
26
+ readonly studioUrl: string;
27
+ readonly customer: string;
28
+ }
13
29
  /**
14
- * Receives the one-time code from Studio on 127.0.0.1. Only a callback carrying this session's state is accepted,
15
- * so another page cannot feed the CLI a code of its own.
30
+ * Receives Studio's answer on 127.0.0.1: the one-time code of an approval, or a denial. Only a callback carrying
31
+ * this session's state is accepted, so another page cannot feed the CLI a code of its own. The browser ends on a
32
+ * Studio page; its address is built from the CLI's own Studio URL, never from the request.
16
33
  */
17
- export declare const startLoginCallbackListener: (state: string) => Promise<LoginCallbackListener>;
34
+ export declare const startLoginCallbackListener: (props: LoginCallbackListenerProps) => Promise<LoginCallbackListener>;
18
35
  /**
19
- * Signs the CLI in to an SDK-builder workspace: the user approves in Studio, Studio returns a one-time code to this
20
- * CLI's loopback listener, and the CLI exchanges it with its PKCE verifier for an API token.
36
+ * Signs the CLI in to an SDK-builder workspace: the user names the token and approves in Studio, Studio returns a
37
+ * one-time code to this CLI's loopback listener, and the CLI exchanges it with its PKCE verifier for an API token.
38
+ * The browser waits on the callback meanwhile and ends on Studio's page for the outcome.
21
39
  */
22
40
  export declare const runLoginCommand: (props: LoginCommandProps, { logger }: CommandContext) => Promise<void>;
23
41
  export {};
@@ -1,4 +1,4 @@
1
- import{spawn as e}from"node:child_process";import{createHash as t,randomBytes as r}from"node:crypto";import{createServer as o}from"node:http";import{hostname as n}from"node:os";import{createApiBaseClient as i}from"#package/client";import{getServerCredentials as s,saveServerCredentials as a}from"../services/index.js";let l=(e,t)=>`<!doctype html><html><head><meta charset="utf-8"><title>${e}</title></head><body style="font-family:system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0"><main style="text-align:center"><h1>${e}</h1><p>${t}</p></main></body></html>`;export const startLoginCallbackListener=async e=>{let t=null,r=new Promise((e,r)=>{t={resolve:e,reject:r}}),n=o((r,o)=>{let n=new URL(r.url??"/","http://127.0.0.1"),i=n.searchParams.get("code");if("/callback"!==n.pathname)return void o.writeHead(404).end();if(n.searchParams.get("state")!==e||!i){o.writeHead(400,{"content-type":"text/html"}),o.end(l("Sign-in failed","This response does not belong to the waiting CLI. Run phoenix login again.")),t?.reject(Error("The sign-in response did not match this CLI session. Run `phoenix login` again."));return}o.writeHead(200,{"content-type":"text/html"}),o.end(l("Phoenix CLI signed in","You can close this tab and return to the terminal.")),t?.resolve(i)}),i=await new Promise((e,t)=>{n.once("error",t),n.listen(0,"127.0.0.1",()=>{let r=n.address();null===r||"string"==typeof r?t(Error("The login callback listener did not get a port. Run `phoenix login` again.")):e(r.port)})}),s=setTimeout(()=>{t?.reject(Error("Nobody approved the sign-in within 5 minutes. Run `phoenix login` again."))},3e5);return{port:i,code:r,close:()=>{clearTimeout(s),n.close()}}};let c=async(e,t)=>{try{let{error:r,response:o}=await i(e).DELETE("/auth/token",{headers:{authorization:`Bearer ${t}`,"content-type":null}});return r&&401!==o.status?r.message:null}catch(e){return e instanceof Error?e.message:String(e)}};export const runLoginCommand=async(o,{logger:l})=>{let d=r(32).toString("base64url"),h=t("sha256").update(d).digest("base64url"),u=r(16).toString("base64url"),m=await startLoginCallbackListener(u);try{let t=new URL("/builder/cli-login",o.studioUrl);t.searchParams.set("customer",o.customer),t.searchParams.set("port",String(m.port)),t.searchParams.set("state",u),t.searchParams.set("challenge",h),l.step(`Signing in to workspace "${o.customer}" on ${o.serverUrl}`),l.info(`Approve the CLI in your browser:
1
+ import{spawn as e}from"node:child_process";import{createHash as t,randomBytes as r}from"node:crypto";import{createServer as o}from"node:http";import{hostname as n}from"node:os";import{createApiBaseClient as s}from"#package/client";import{getServerCredentials as i,saveServerCredentials as a}from"../services/index.js";let l={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},c=(e,t)=>`<!doctype html><html><head><meta charset="utf-8"><title>${e}</title></head><body style="font-family:system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0"><main style="text-align:center"><h1>${e}</h1><p>${t.replace(/[&<>"']/g,e=>l[e]??e)}</p></main></body></html>`,d=(e,t,r,o)=>new Promise(n=>{e.destroyed?n():(e.once("close",n),e.writeHead(t,{...r,connection:"close"}).end(o))});export const startLoginCallbackListener=async e=>{let{state:t,studioUrl:r,customer:n}=e,s=(e,t)=>{let o=new URL(e,r);return o.searchParams.set("customer",n),t&&o.searchParams.set("name",t),o.toString()},i=null,a=!1,l=new Promise((e,t)=>{i={resolve:e,reject:t}}),m=o((e,r)=>{let o=new URL(e.url??"/","http://127.0.0.1"),n=o.searchParams.get("code"),l="access_denied"===o.searchParams.get("error");if("/callback"!==o.pathname)return void r.writeHead(404).end();if(o.searchParams.get("state")!==t||a||!n&&!l){d(r,400,{"content-type":"text/html"},c("Sign-in failed","This response does not belong to the waiting CLI. Run phoenix login again.")),a||i?.reject(Error("The sign-in response did not match this CLI session. Run `phoenix login` again."));return}if(a=!0,l||!n)return void d(r,302,{location:s("/builder/cli-login/denied",null)}).then(()=>{i?.reject(Error("The sign-in was denied in Studio. Run `phoenix login` again to sign in."))});let m=o.searchParams.get("name");i?.resolve({code:n,tokenName:m,finish:e=>e.signedIn?d(r,302,{location:s("/builder/cli-login/done",m)}):d(r,200,{"content-type":"text/html"},c("Sign-in failed",e.message))})}),h=await new Promise((e,t)=>{m.once("error",t),m.listen(0,"127.0.0.1",()=>{let r=m.address();null===r||"string"==typeof r?t(Error("The login callback listener did not get a port. Run `phoenix login` again.")):e(r.port)})}),u=setTimeout(()=>{i?.reject(Error("Nobody approved the sign-in within 5 minutes. Run `phoenix login` again."))},3e5);return{port:h,callback:l,close:()=>{clearTimeout(u),m.close()}}};let m=async(e,t)=>{try{let{error:r,response:o}=await s(e).DELETE("/auth/token",{headers:{authorization:`Bearer ${t}`,"content-type":null}});return r&&401!==o.status?r.message:null}catch(e){return e instanceof Error?e.message:String(e)}},h=async(e,t)=>{let{data:r,error:o}=await s(e.serverUrl).POST("/auth/token",{body:t});if(o||!r)throw Error(`The server did not accept the sign-in: ${o?.message??"no response"}`);if(r.customer.slug!==e.customer)throw await m(e.serverUrl,r.token),Error(`The sign-in was approved in workspace "${r.customer.slug}", not "${e.customer}". Check --region or --studioUrl and run \`phoenix login ${e.customer}\` again.`);let n=await i(e.serverUrl),l=await a(e.serverUrl,{token:r.token,userId:r.userId,customerSlug:r.customer.slug,customerName:r.customer.name,studioUrl:e.studioUrl,createdAt:new Date().toISOString()}),c=n?await m(e.serverUrl,n.token):null;return{customerName:r.customer.name,path:l,revokeError:c}};export const runLoginCommand=async(o,{logger:s})=>{let i=r(32).toString("base64url"),a=t("sha256").update(i).digest("base64url"),l=r(16).toString("base64url"),c=n(),d=`phoenix CLI on ${c}`,m=await startLoginCallbackListener({state:l,studioUrl:o.studioUrl,customer:o.customer});try{let t=new URL("/builder/cli-login",o.studioUrl);t.searchParams.set("customer",o.customer),t.searchParams.set("port",String(m.port)),t.searchParams.set("state",l),t.searchParams.set("challenge",a),t.searchParams.set("name",d),t.searchParams.set("host",c),t.searchParams.set("started",String(Date.now())),s.step(`Signing in to workspace "${o.customer}" on ${o.serverUrl}`),s.info(`Approve the CLI in your browser:
2
2
 
3
3
  ${t.toString()}
4
- `),o.open&&(t=>{let[r,o]="darwin"===process.platform?["open",[t]]:"win32"===process.platform?["rundll32",["url.dll,FileProtocolHandler",t]]:["xdg-open",[t]];e(r,o,{stdio:"ignore",detached:!0}).on("error",()=>void 0).unref()})(t.toString());let r=await m.code,{data:p,error:g}=await i(o.serverUrl).POST("/auth/token",{body:{code:r,codeVerifier:d,port:m.port,name:`phoenix CLI on ${n()}`}});if(g||!p)throw Error(`The server did not accept the sign-in: ${g?.message??"no response"}`);if(p.customer.slug!==o.customer)throw await c(o.serverUrl,p.token),Error(`The sign-in was approved in workspace "${p.customer.slug}", not "${o.customer}". Check --region or --studioUrl and run \`phoenix login ${o.customer}\` again.`);let w=await s(o.serverUrl),y=await a(o.serverUrl,{token:p.token,userId:p.userId,customerSlug:p.customer.slug,customerName:p.customer.name,studioUrl:o.studioUrl,createdAt:new Date().toISOString()}),f=w?await c(o.serverUrl,w.token):null;f&&l.warn(`The server did not revoke the token this sign-in replaces (${f}). It stays valid on the server. Contact Phoenix support to revoke it.`),l.success(`Signed in to ${p.customer.name}. The token is stored in ${y}; revoke it with phoenix logout.`)}finally{m.close()}};
4
+ `),o.open&&(t=>{let[r,o]="darwin"===process.platform?["open",[t]]:"win32"===process.platform?["rundll32",["url.dll,FileProtocolHandler",t]]:["xdg-open",[t]];e(r,o,{stdio:"ignore",detached:!0}).on("error",()=>void 0).unref()})(t.toString());let r=await m.callback;try{let e=await h(o,{code:r.code,codeVerifier:i,port:m.port,name:d});e.revokeError&&s.warn(`The server did not revoke the token this sign-in replaces (${e.revokeError}). It stays valid on the server. Contact Phoenix support to revoke it.`),await r.finish({signedIn:!0}),s.success(`Signed in to ${e.customerName}. The token is stored in ${e.path}; revoke it with phoenix logout.`)}catch(e){throw await r.finish({signedIn:!1,message:e instanceof Error?e.message:String(e)}),e}}finally{m.close()}};
@@ -11,6 +11,7 @@ export { patchConsole, type PatchConsoleOptions } from './console-capture.js';
11
11
  export { WebhookTunnelMonitor, type TunnelEvent, type TunnelRequestEntry, type TunnelRequestSummary, type TunnelStatus, type TunnelStatusState, } from './webhook-tunnel-monitor.js';
12
12
  export { compileWithSwc, watchWithSwc } from './swc.js';
13
13
  export { STORY_DEV_MARKER_PATH, readActiveStoryDevMarker, type StoryDevMarker } from './story-dev-marker.js';
14
+ export { composeDefaultBanner } from './phx-banner-plugin.js';
14
15
  export { getViteBuildConfigs, getViteDevConfig, setViteLogSink, type ViteLogSink, type ViteLogSinkOptions, } from './vite-config.js';
15
16
  export { getServerCredentials, removeServerCredentials, saveServerCredentials } from './cli-credentials.js';
16
17
  export { createSourceArchive, extractSourceArchive } from './source-archive.js';
@@ -1 +1 @@
1
- export{PhoenixPubSub}from"./phoenix-pubsub.js";export{MockTemplateWatcher}from"./mock-template-watcher.js";export{ApplicationSpecProjectWatcher}from"./application-spec-project-watcher.js";export{ApplicationSpecStoryWatcher}from"./application-spec-story-watcher.js";export{LinguiWatcher}from"./lingui-watcher.js";export{loadMockTemplates,parseMockTemplateYaml}from"./spec-files.js";export{LOG_STREAMS,LogBus}from"./log-bus.js";export{createBusLogger}from"./bus-logger.js";export{patchConsole}from"./console-capture.js";export{WebhookTunnelMonitor}from"./webhook-tunnel-monitor.js";export{compileWithSwc,watchWithSwc}from"./swc.js";export{STORY_DEV_MARKER_PATH,readActiveStoryDevMarker}from"./story-dev-marker.js";export{getViteBuildConfigs,getViteDevConfig,setViteLogSink}from"./vite-config.js";export{getServerCredentials,removeServerCredentials,saveServerCredentials}from"./cli-credentials.js";export{createSourceArchive,extractSourceArchive}from"./source-archive.js";export{resolveSignedInDevelopmentEnvironment}from"./signed-in-development-environment.js";export{DEFAULT_PHOENIX_REGION,PHOENIX_REGIONS,PUBLIC_PHOENIX_REGIONS,getRegionServerUrl,getRegionStudioUrl}from"./phoenix-regions.js";
1
+ export{PhoenixPubSub}from"./phoenix-pubsub.js";export{MockTemplateWatcher}from"./mock-template-watcher.js";export{ApplicationSpecProjectWatcher}from"./application-spec-project-watcher.js";export{ApplicationSpecStoryWatcher}from"./application-spec-story-watcher.js";export{LinguiWatcher}from"./lingui-watcher.js";export{loadMockTemplates,parseMockTemplateYaml}from"./spec-files.js";export{LOG_STREAMS,LogBus}from"./log-bus.js";export{createBusLogger}from"./bus-logger.js";export{patchConsole}from"./console-capture.js";export{WebhookTunnelMonitor}from"./webhook-tunnel-monitor.js";export{compileWithSwc,watchWithSwc}from"./swc.js";export{STORY_DEV_MARKER_PATH,readActiveStoryDevMarker}from"./story-dev-marker.js";export{composeDefaultBanner}from"./phx-banner-plugin.js";export{getViteBuildConfigs,getViteDevConfig,setViteLogSink}from"./vite-config.js";export{getServerCredentials,removeServerCredentials,saveServerCredentials}from"./cli-credentials.js";export{createSourceArchive,extractSourceArchive}from"./source-archive.js";export{resolveSignedInDevelopmentEnvironment}from"./signed-in-development-environment.js";export{DEFAULT_PHOENIX_REGION,PHOENIX_REGIONS,PUBLIC_PHOENIX_REGIONS,getRegionServerUrl,getRegionStudioUrl}from"./phoenix-regions.js";
@@ -0,0 +1,32 @@
1
+ import type { Plugin } from 'vite';
2
+ export interface BannerBundleChunk {
3
+ readonly type: 'chunk';
4
+ readonly fileName: string;
5
+ code: string;
6
+ }
7
+ export interface BannerBundleAsset {
8
+ readonly type: 'asset';
9
+ readonly fileName: string;
10
+ source: string | Uint8Array;
11
+ }
12
+ export type BannerBundleItem = BannerBundleChunk | BannerBundleAsset;
13
+ export type BannerBundle = Record<string, BannerBundleItem>;
14
+ /** What the comment at the top of every frontend JavaScript file is composed from. */
15
+ export interface BannerCommentProps {
16
+ /** Version of the SDK running the build, named in the Salsita notice. */
17
+ readonly sdkVersion: string;
18
+ /** The caller's `--banner` text, or the default line when the option is not given. It is public in every bundle. */
19
+ readonly banner: string | undefined;
20
+ }
21
+ /** What `phoenix build` knows about the application on its own, for the banner line used when `--banner` is not given. */
22
+ export interface DefaultBannerProps {
23
+ /** `applicationVersion` of the application spec. */
24
+ readonly applicationVersion: string | undefined;
25
+ /** Commit checked out in the project; undefined when the build does not run in a git checkout. */
26
+ readonly commit: string | undefined;
27
+ }
28
+ export declare const composeDefaultBanner: (props: DefaultBannerProps) => string | undefined;
29
+ export declare const composeBannerComment: (props: BannerCommentProps) => string;
30
+ export declare const prependBannerToBundle: (bundle: BannerBundle, comment: string) => void;
31
+ /** Must be the last plugin of a build config: whatever prepends to a bundle after it takes byte 0 from the comment. */
32
+ export declare const phxBannerPlugin: (props: BannerCommentProps) => Plugin;
@@ -0,0 +1 @@
1
+ import{THIRD_PARTY_LICENSES_FILE_NAME as e}from"./phx-licenses-plugin.js";let n=/\r\n|[\n\r\u2028\u2029]/,o=e=>e.split(n).map(e=>e.trim()).filter(e=>e.length>0).map(e=>` * ${e.replaceAll("*/","*\\/")}`);export const composeDefaultBanner=e=>{let n=[...void 0===e.applicationVersion?[]:[`App version: ${e.applicationVersion}`],...void 0===e.commit?[]:[`Commit: ${e.commit}`]];return 0===n.length?void 0:n.join("; ")};export const composeBannerComment=n=>["/*!",...o(n.banner??""),...o(`Built with Salsita SDK ${n.sdkVersion}. Copyright (c) Salsita s.r.o. All rights reserved.`),...o(`Third-party licences: ${e}`)," */",""].join("\n");export const prependBannerToBundle=(e,n)=>{for(let o of Object.values(e))o.fileName.endsWith(".js")&&("chunk"===o.type?o.code=`${n}${o.code}`:"string"==typeof o.source?o.source=`${n}${o.source}`:o.source=Buffer.concat([Buffer.from(n),o.source]))};export const phxBannerPlugin=e=>{let n=composeBannerComment(e);return{name:"vite:phx-banner",enforce:"post",generateBundle(e,o){prependBannerToBundle(o,n)}}};
@@ -0,0 +1,55 @@
1
+ import type { Plugin } from 'vite';
2
+ /** Name of the licences file the frontend build writes next to its bundles; the banner comment points to it. */
3
+ export declare const THIRD_PARTY_LICENSES_FILE_NAME = "THIRD-PARTY-LICENSES.txt";
4
+ /** A third-party package whose code ended up in a frontend bundle, as it is listed in the licences file. */
5
+ export interface LicensedPackage {
6
+ readonly name: string;
7
+ readonly version: string;
8
+ /** Licence declared in the package's `package.json`; `UNKNOWN` when it declares none. */
9
+ readonly license: string;
10
+ /** Content of the package's licence file; undefined when the package ships none. */
11
+ readonly text: string | undefined;
12
+ }
13
+ /**
14
+ * Packages found so far by one `phoenix build`. Its frontend builds share one collection, so the licences file each
15
+ * of them writes into the common output folder is cumulative and the last one is complete.
16
+ */
17
+ export interface LicenseCollection {
18
+ /** Listed packages by `name@version`. */
19
+ readonly packages: Map<string, LicensedPackage>;
20
+ /** Resolution cache by module directory, so a package's files are read once per build command. */
21
+ readonly packageByDirectory: Map<string, LicensedPackage | undefined>;
22
+ }
23
+ export interface LicensesBundleChunk {
24
+ readonly type: 'chunk';
25
+ readonly modules: Readonly<Record<string, {
26
+ readonly renderedLength: number;
27
+ }>>;
28
+ }
29
+ export interface LicensesBundleAsset {
30
+ readonly type: 'asset';
31
+ }
32
+ export type LicensesBundle = Record<string, LicensesBundleChunk | LicensesBundleAsset>;
33
+ /**
34
+ * Finds the package a bundled module belongs to: the nearest named `package.json` above the module's real path that
35
+ * is still under a `node_modules` folder. Project source, workspace-linked packages and virtual modules have none.
36
+ */
37
+ export declare const resolvePackageForModule: (id: string) => LicensedPackage | undefined;
38
+ export declare const createLicenseCollection: () => LicenseCollection;
39
+ /**
40
+ * Adds the packages behind every module that left code or styles in the bundle; tree-shaken modules are not listed.
41
+ *
42
+ * Known gap: only Rollup modules are seen. What a stylesheet pulls in itself (CSS `@import`, Sass `@use`, files behind
43
+ * `url()`) is inlined or emitted by Vite's CSS handling without becoming a module, so those packages are not listed.
44
+ */
45
+ export declare const addBundlePackages: (bundle: LicensesBundle, collection: LicenseCollection) => void;
46
+ export declare const formatLicenses: (packages: readonly LicensedPackage[]) => string;
47
+ /**
48
+ * Lists the third-party packages bundled into the frontend output. Create one instance per `phoenix build` and add it
49
+ * to every frontend build config, so all of them contribute to the one file.
50
+ *
51
+ * Known gap: packages used only inside a web worker are not listed. Vite bundles a worker in a build of its own that
52
+ * runs `worker.plugins` instead of these; registering the plugin there would make every worker build emit a partial
53
+ * file under the same name.
54
+ */
55
+ export declare const phxLicensesPlugin: () => Plugin;
@@ -0,0 +1,8 @@
1
+ import{readFileSync as e,readdirSync as t,realpathSync as s}from"fs";import{dirname as n,isAbsolute as r,join as a}from"path";import{z as i}from"zod";export const THIRD_PARTY_LICENSES_FILE_NAME="THIRD-PARTY-LICENSES.txt";let c=/[\\/]node_modules[\\/]/,o=[/^license/i,/^licence/i,/^copying/i],l="-".repeat(80),p=/\.(css|scss|sass|less|styl|stylus|pcss|postcss|sss)(\?|$)/,u=i.object({name:i.string().min(1),version:i.string().min(1),license:i.unknown(),licenses:i.unknown()}),f=i.object({type:i.string().min(1)}),m=s=>{let n,r;try{n=e(a(s,"package.json"),"utf-8")}catch{return}try{r=JSON.parse(n)}catch{return}let c=u.safeParse(r);if(c.success)return{name:c.data.name,version:c.data.version,license:(e=>{if("string"==typeof e.license&&e.license.length>0)return e.license;let t=i.array(f).safeParse(Array.isArray(e.licenses)?e.licenses:[e.license]);return t.success&&0!==t.data.length?t.data.map(e=>e.type).join(" OR "):"UNKNOWN"})(c.data),text:(s=>{let n=t(s,{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name).sort();for(let t of o){let r=n.find(e=>t.test(e));if(void 0!==r)return e(a(s,r),"utf-8").trim()}})(s)}},d=(e,t)=>e.name!==t.name?e.name<t.name?-1:1:e.version.localeCompare(t.version,"en",{numeric:!0});export const resolvePackageForModule=e=>{let t=e.replace(/[?#].*$/,"");if(e.startsWith("\0")||!r(t))return;let a=n((e=>{try{return s(e)}catch{return e}})(t));for(;c.test(a);){let e=m(a);if(void 0!==e)return e;a=n(a)}};export const createLicenseCollection=()=>({packages:new Map,packageByDirectory:new Map});export const addBundlePackages=(e,t)=>{for(let s of Object.values(e))if("chunk"===s.type)for(let[e,r]of Object.entries(s.modules)){if(0===r.renderedLength&&!p.test(e))continue;let s=n(e);t.packageByDirectory.has(s)||t.packageByDirectory.set(s,resolvePackageForModule(e));let a=t.packageByDirectory.get(s);if(void 0===a)continue;let i=`${a.name}@${a.version}`;t.packages.has(i)||t.packages.set(i,a)}};export const formatLicenses=e=>["Third-party software bundled into the JavaScript files in this folder, with the licence of each package.",...[...e].sort(d).map(e=>{let t=`${e.name} ${e.version}
2
+ License: ${e.license}`;return void 0===e.text?t:`${t}
3
+
4
+ ${e.text}`})].join(`
5
+
6
+ ${l}
7
+
8
+ `).concat("\n");export const phxLicensesPlugin=()=>{let e=createLicenseCollection();return{name:"vite:phx-licenses",enforce:"post",generateBundle(t,s){addBundlePackages(s,e),this.emitFile({type:"asset",fileName:"THIRD-PARTY-LICENSES.txt",source:formatLicenses([...e.packages.values()])})}}};