@salsita-ai/sdk 0.49.0-develop.f5fc5cfc25 → 0.49.0-develop.fc391028c9

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 (23) hide show
  1. package/dist/application-spec/generate-application/code/templates/env-example.js +1 -0
  2. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.d.ts +6 -3
  3. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.js +1 -1
  4. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.js +1 -1
  5. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
  6. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +32 -32
  7. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
  8. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
  9. package/dist/docs/index.json +1 -1
  10. package/dist/docs/phoenix/csp.mdx +6 -2
  11. package/dist/docs/phoenix/phoenix-cli.mdx +14 -13
  12. package/dist/domain/application/application-config.d.ts +3 -1
  13. package/dist/domain/application/assistant-mutations.d.ts +1 -1
  14. package/dist/domain/application/assistant-mutations.js +1 -1
  15. package/dist/legacy/domain-cli/utils/cache.d.ts +1 -1
  16. package/dist/legacy/domain-cli/utils/cache.js +1 -1
  17. package/dist/legacy/phoenix-cli/commands/dev.d.ts +2 -0
  18. package/dist/legacy/phoenix-cli/commands/dev.js +5 -5
  19. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/env-example.d.ts +1 -1
  20. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/env-example.js +1 -0
  21. package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
  22. package/dist/phoenix/cli.js +1 -1
  23. package/package.json +3 -3
@@ -46,6 +46,7 @@ export const generateApplicationSpecEnvExample=()=>`# This file documents develo
46
46
 
47
47
  # deployment:prepare-dev and deployment:prepare-local output and behavior overrides:
48
48
  # OUT_FILE=.env.generated
49
+ # SKIP_UPLOAD also applies to the deployment phoenix dev prepares at startup.
49
50
  # SKIP_UPLOAD=false
50
51
  # OVERRIDE_SCHEMA=true
51
52
 
@@ -19,23 +19,26 @@ export declare const ASSISTANT_OPTION_COMPONENT_TYPES: readonly ['materialSwatch
19
19
  export type AssistantOptionComponentType = (typeof ASSISTANT_OPTION_COMPONENT_TYPES)[number];
20
20
  /**
21
21
  * What the integrator promises about a list of choices, so the agent can read it once and reuse it:
22
- * `sameForAllInstances` when every entity of the type gets the same list, `stable` when the list
22
+ * `sameForAllInstances` when every entity of the type gets the same list, `constantDuringSession` when the list
23
23
  * does not change during a session. A hint only adds a sentence to a generated description; nothing
24
24
  * verifies it.
25
25
  */
26
- export declare const ASSISTANT_HINTS: readonly ['sameForAllInstances', 'stable'];
26
+ export declare const ASSISTANT_HINTS: readonly ['sameForAllInstances', 'constantDuringSession'];
27
27
  export type AssistantHint = (typeof ASSISTANT_HINTS)[number];
28
28
  /**
29
29
  * The component that holds the choices of a writable field: the instance `instanceName` of the
30
30
  * system component `componentType` on the entity type. It generates the `<field>Options` edge under
31
31
  * `meta`, named by `as` when given, and makes `modify<Type>` reject a value outside the choices
32
- * unless `validate` is `false`. The component is named explicitly and never inferred from a `$bind`.
32
+ * unless `validate` is `false`. `allowDryRuns: false` turns the dry-run of the choices off, for
33
+ * fields with too many of them to try out. The component is named explicitly and never inferred from
34
+ * a `$bind`.
33
35
  */
34
36
  export interface RawAssistantFieldOptions {
35
37
  readonly componentType: AssistantOptionComponentType;
36
38
  readonly instanceName: string;
37
39
  readonly as?: string;
38
40
  readonly validate?: boolean;
41
+ readonly allowDryRuns?: boolean;
39
42
  readonly hints?: readonly AssistantHint[];
40
43
  }
41
44
  /**
@@ -1 +1 @@
1
- import{z as t}from"zod";import{ASSISTANT_AI_PROVIDERS as e,ASSISTANT_MODEL_TIERS as o,ASSISTANT_REASONING_LEVELS as i}from"@salsita-ai/contracts/assistant";export const ASSISTANT_OPTION_COMPONENT_TYPES=["materialSwatch","attributeSelection","distanceDimensionSelect"];export const ASSISTANT_HINTS=["sameForAllInstances","stable"];let n=t.string().regex(/^(?!__)[_A-Za-z][_0-9A-Za-z]*$/,'must be a GraphQL name: letters, digits and "_", not starting with a digit or "__"'),r=e=>t.enum(e,{errorMap:()=>({message:`must be one of: ${e.join(", ")}`})}),s=t.object({description:t.string().optional(),as:n.optional()}).strict(),a=t.array(r(ASSISTANT_HINTS)),c=t.object({options:t.object({componentType:r(ASSISTANT_OPTION_COMPONENT_TYPES),instanceName:t.string().min(1,"must not be empty; name the component instance that holds the choices"),as:n.optional(),validate:t.boolean().optional(),hints:a.optional()}).strict().optional()}).strict(),l=t.object({as:t.string().trim().min(1,"must not be empty; remove the key to use the instance name").optional(),description:t.string().optional(),allowDryRuns:t.boolean().optional()}).strict(),p=e=>t.object({hints:a.optional(),groups:t.record(t.string(),l.nullable(),{required_error:`is required: the recipe groups of the type go under "groups", keyed by the instance name of a "${e}" component`})}).strict(),m=`is required: declare provider (${e.join(", ")}), model (${o.join(", ")}) and reasoning (${i.join(", ")})`,d=t.object({provider:r(e),model:r(o),reasoning:r(i)},{required_error:m,invalid_type_error:m}).strict();export const rawAssistantSchema=t.object({entities:t.record(t.string(),t.record(t.string(),s.nullable())).optional(),deletable:t.record(t.string(),t.object({}).strict().nullable()).optional(),writable:t.record(t.string(),t.record(t.string(),c.nullable())).optional(),childRecipes:t.record(t.string(),p("childEntityRecipes")).optional(),replaceRecipes:t.record(t.string(),p("replaceEntityRecipes")).optional(),instructions:t.string().trim().min(1,"must not be empty; remove the key when there are no instructions").optional(),ai:d}).strict();
1
+ import{z as t}from"zod";import{ASSISTANT_AI_PROVIDERS as e,ASSISTANT_MODEL_TIERS as o,ASSISTANT_REASONING_LEVELS as i}from"@salsita-ai/contracts/assistant";export const ASSISTANT_OPTION_COMPONENT_TYPES=["materialSwatch","attributeSelection","distanceDimensionSelect"];export const ASSISTANT_HINTS=["sameForAllInstances","constantDuringSession"];let n=t.string().regex(/^(?!__)[_A-Za-z][_0-9A-Za-z]*$/,'must be a GraphQL name: letters, digits and "_", not starting with a digit or "__"'),r=e=>t.enum(e,{errorMap:()=>({message:`must be one of: ${e.join(", ")}`})}),s=t.object({description:t.string().optional(),as:n.optional()}).strict(),a=t.array(r(ASSISTANT_HINTS)),c=t.object({options:t.object({componentType:r(ASSISTANT_OPTION_COMPONENT_TYPES),instanceName:t.string().min(1,"must not be empty; name the component instance that holds the choices"),as:n.optional(),validate:t.boolean().optional(),allowDryRuns:t.boolean().optional(),hints:a.optional()}).strict().optional()}).strict(),l=t.object({as:t.string().trim().min(1,"must not be empty; remove the key to use the instance name").optional(),description:t.string().optional(),allowDryRuns:t.boolean().optional()}).strict(),p=e=>t.object({hints:a.optional(),groups:t.record(t.string(),l.nullable(),{required_error:`is required: the recipe groups of the type go under "groups", keyed by the instance name of a "${e}" component`})}).strict(),m=`is required: declare provider (${e.join(", ")}), model (${o.join(", ")}) and reasoning (${i.join(", ")})`,d=t.object({provider:r(e),model:r(o),reasoning:r(i)},{required_error:m,invalid_type_error:m}).strict();export const rawAssistantSchema=t.object({entities:t.record(t.string(),t.record(t.string(),s.nullable())).optional(),deletable:t.record(t.string(),t.object({}).strict().nullable()).optional(),writable:t.record(t.string(),t.record(t.string(),c.nullable())).optional(),childRecipes:t.record(t.string(),p("childEntityRecipes")).optional(),replaceRecipes:t.record(t.string(),p("replaceEntityRecipes")).optional(),instructions:t.string().trim().min(1,"must not be empty; remove the key when there are no instructions").optional(),ai:d}).strict();
@@ -1 +1 @@
1
- import{GraphQLBoolean as e,GraphQLFloat as t,GraphQLID as r,GraphQLInt as n,GraphQLList as i,GraphQLNonNull as l,GraphQLScalarType as a,GraphQLString as o,getNamedType as s}from"graphql";import{isArray as f}from"@salsita-ai/common/utils";import{COMMON_SHORT_PREFIX as u,DEFINITION_REF_PATTERN as p,INTERNAL_REF_PATTERN as d,extractPhxDefName as y}from"../../../../core/index.js";export const GraphQLJSON=new a({name:"JSON",description:"Any JSON value, returned as stored. Always plain serializable data."});let c={number:t,integer:n,string:o,boolean:e},m=new Set(["Localizable","EnhancedLocalizable","MessageDescriptor","EnhancedMessageDescriptor","MultilingualString"]),v={type:GraphQLJSON},h=e=>e.startsWith(u)?e.slice(u.length):d.exec(e)?.[2],g=e=>y(e)??p.exec(e)?.[1];export const createAssistantRefResolver=(e,t)=>r=>{let n=g(r);if(void 0!==n)return t[n]?.schema;let i=h(r);return void 0===i?void 0:e.get(i)?.schema};let S=(e,t,r=new Set)=>{if(e.$ref){if(r.has(e.$ref))return!1;let n=t(e.$ref);return void 0===n||S(n,t,new Set([...r,e.$ref]))}let n=[...e.anyOf??[],...e.oneOf??[]];return"null"===e.type||f(e.type)&&e.type.includes("null")||e.enum?.includes(null)===!0||null===e.const||n.some(e=>S(e,t,r))},O=({anyOf:e,oneOf:t})=>[...e??[],...t??[]].filter(e=>"null"!==e.type),w=(e,t,n)=>{let l;if(void 0!==(l=void 0===e.$ref?void 0:g(e.$ref))&&m.has(l))return{type:o,localized:!0};if(e.tsType)return v;if(e.$ref){var a=e.$ref;if("DomainEntityId"===y(a))return{type:r};let i=h(a),l=void 0===i||n.has(i)?void 0:t(a);return void 0!==i&&l?w(l,t,new Set([...n,i])):v}if(e.anyOf||e.oneOf)return((e,t,r)=>{let n=O(e).map(e=>w(e,t,r)),[i]=n;if(1===n.length&&i)return i;let l=n.flatMap(({type:e,enumValues:t})=>e===o&&t?[t]:[]);if(n.length<2||l.length!==n.length||e.anyOf&&e.oneOf)return v;let a=l.flatMap(e=>[...new Set(e)]);return{type:o,enumValues:e.oneOf?a.filter(e=>a.indexOf(e)===a.lastIndexOf(e)):[...new Set(a)]}})(e,t,n);if(e.enum){let t;return(t=e.enum.filter(e=>null!==e)).every(e=>"string"==typeof e)?{type:o,enumValues:t}:v}if(f(e.type)){let r=e.type.filter(e=>"null"!==e),[i]=r;return 1===r.length&&i?w({...e,type:i},t,n):v}if("array"===e.type){var u=e.items;if(!u||f(u))return v;let r=$(u,t,n);return s(r.type)===GraphQLJSON?v:{type:new i(r.type),enumValues:r.enumValues,localized:r.localized}}let p="string"==typeof e.type?c[e.type]:void 0;return p?{type:p}:v},$=(e,t,r)=>{let n=w(e,t,r);return{...n,type:S(e,t)?n.type:new l(n.type)}},x=(e,t,r)=>{let n=h(e),i=void 0===n||r.has(n)?void 0:t(e);if(void 0!==n&&i)return void 0===i.description&&i.$ref?x(i.$ref,t,new Set([...r,n])):i.description};export const assistantFieldType=(e,t)=>{let r=O(e),n=e.$ref??(1===r.length?r[0]?.$ref:void 0),i=void 0===e.description&&n?x(n,t,new Set):e.description;return{...$(e,t,new Set),...void 0===i?{}:{description:i}}};
1
+ import{GraphQLBoolean as e,GraphQLFloat as t,GraphQLID as r,GraphQLInt as n,GraphQLList as i,GraphQLNonNull as l,GraphQLScalarType as a,GraphQLString as o,getNamedType as s}from"graphql";import{isArray as u}from"@salsita-ai/common/utils";import{COMMON_SHORT_PREFIX as f,DEFINITION_REF_PATTERN as p,INTERNAL_REF_PATTERN as d,extractPhxDefName as y}from"../../../../core/index.js";export const GraphQLJSON=new a({name:"JSON",description:"Any JSON value, returned as stored. Always plain serializable data."});let c={number:t,integer:n,string:o,boolean:e},m=new Set(["Localizable","EnhancedLocalizable","MessageDescriptor","EnhancedMessageDescriptor","MultilingualString"]),v={type:GraphQLJSON},h=e=>e.startsWith(f)?e.slice(f.length):d.exec(e)?.[2],g=e=>y(e)??p.exec(e)?.[1];export const createAssistantRefResolver=(e,t)=>r=>{let n=g(r);if(void 0!==n)return t[n]?.schema;let i=h(r);return void 0===i?void 0:e.get(i)?.schema};let S=(e,t,r=new Set)=>{if(e.$ref){if(r.has(e.$ref))return!1;let n=t(e.$ref);return void 0===n||S(n,t,new Set([...r,e.$ref]))}let n=[...e.anyOf??[],...e.oneOf??[]];return"null"===e.type||u(e.type)&&e.type.includes("null")||e.enum?.includes(null)===!0||null===e.const||n.some(e=>S(e,t,r))},O=({anyOf:e,oneOf:t})=>[...e??[],...t??[]].filter(e=>"null"!==e.type),w=(e,t,n)=>{let l;if(void 0!==(l=void 0===e.$ref?void 0:g(e.$ref))&&m.has(l))return{type:o,localized:!0};if(e.tsType)return v;if(e.$ref){var a=e.$ref;if("DomainEntityId"===y(a))return{type:r};let i=h(a),l=void 0===i||n.has(i)?void 0:t(a);return void 0!==i&&l?w(l,t,new Set([...n,i])):v}if(e.anyOf||e.oneOf)return((e,t,r)=>{let n=O(e).map(e=>w(e,t,r)),[i]=n;if(1===n.length&&i)return i;let l=n.flatMap(({type:e,enumValues:t})=>e===o&&t?[t]:[]);if(n.length<2||l.length!==n.length||e.anyOf&&e.oneOf)return v;let a=l.flatMap(e=>[...new Set(e)]);return{type:o,enumValues:e.oneOf?a.filter(e=>a.indexOf(e)===a.lastIndexOf(e)):[...new Set(a)]}})(e,t,n);if(e.enum){let t;return(t=e.enum.filter(e=>null!==e)).every(e=>"string"==typeof e)?{type:o,enumValues:t}:v}if(u(e.type)){let r=e.type.filter(e=>"null"!==e),[i]=r;return 1===r.length&&i?w({...e,type:i},t,n):v}if("array"===e.type){var f=e.items;if(!f||u(f))return v;let r=$(f,t,n);return s(r.type)===GraphQLJSON?v:{type:new i(r.type),enumValues:r.enumValues,localized:r.localized}}let p="string"==typeof e.type?c[e.type]:void 0;return p?{type:p}:v},$=(e,t,r)=>{let n=w(e,t,r);return{...n,type:S(e,t)?n.type:new l(n.type)}},x=e=>{let t=O(e);return e.$ref??(1===t.length?t[0]?.$ref:void 0)},z=(e,t,r)=>{let n=h(e),i=void 0===n||r.has(n)?void 0:t(e);if(void 0===n||!i)return;let l=x(i);return void 0===i.description&&l?z(l,t,new Set([...r,n])):i.description};export const assistantFieldType=(e,t)=>{let r=x(e),n=void 0===e.description&&r?z(r,t,new Set):e.description;return{...$(e,t,new Set),...void 0===n?{}:{description:n}}};
@@ -1 +1 @@
1
- import{GraphQLBoolean as e,GraphQLID as t,GraphQLInputObjectType as n,GraphQLInterfaceType as i,GraphQLList as r,GraphQLNonNull as o,GraphQLObjectType as s,GraphQLSchema as a,GraphQLString as p,getNullableType as l,isInputType as d,printSchema as c,validateSchema as h}from"graphql";import{DiagnosticCode as f,diagnosticMessages as y}from"../../../../errors/index.js";import{ASSISTANT_HINTS as u}from"../../../raw-spec/index.js";import{GraphQLJSON as g,assistantFieldType as m,createAssistantRefResolver as S}from"./assistant-field-type.js";let T="AnyDomainEntity",w="RootEntity",N="RecipeGroup",E="Recipe",A="RecipeDryRun",_="RecipeDryRunError",I="FieldOption",O={section:"childRecipes",component:"childEntityRecipes",mutation:"addChild"},v={section:"replaceRecipes",component:"replaceEntityRecipes",mutation:"replaceEntity"},b=new Set(["id","type","meta"]),$=new Set(["Query","Mutation","Navigation",N,E,A,_,I,"JSON","String","Int","Float","Boolean","ID"]),R=(e,t)=>{if(!t||0===t.length)return e;let n=`One of: ${t.map(e=>`"${e}"`).join(", ")}.`;return e?/[.!?]$/.test(e)?`${e} ${n}`:`${e}. ${n}`:n},M=new Set(["id","type"]),j="The raw stored value: a string, a message descriptor or a multilingual object.",D=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],P=(e,t,{model:n,components:i})=>{let r=new Set([e,...[...n.aliases].filter(([,t])=>t.includes(e)).map(([e])=>e)]);return i.filter(({componentName:e,typeOrAlias:n})=>e===t&&r.has(n)).map(({instanceName:e})=>String(e))},U=(...e)=>u.filter(t=>e.some(e=>e?.includes(t))),C=(e,t,n,i)=>{let{model:r}=n,o=new Map,s=new Map;for(let[a,{groups:p,hints:l}]of Object.entries(e)){let e=r.entityTypes.find(e=>e===a),d=e?[e]:[...r.aliases].find(([e])=>e===a)?.[1];if(!d){i.at(a).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE(t.section,a));continue}for(let[e,r]of(d.forEach(e=>s.set(e,U(s.get(e),l))),Object.entries(p))){let s=i.at(a,"groups",e),p=`${a}.groups.${e}`,l={groupId:r?.as??e,instanceName:e,...r?.description===void 0?{}:{description:r.description},dryRuns:r?.allowDryRuns??!0};for(let i of d){let r=P(i,t.component,n),d=o.get(i)??[],c=d.find(e=>e.group.groupId===l.groupId);r.includes(e)?c?s.error(f.ASSISTANT_DUPLICATE_RECIPE_GROUP,y.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,i,l.groupId,[c.entry,p])):o.set(i,[...d,{group:l,entry:p,entryCtx:s}]):s.error(f.ASSISTANT_UNKNOWN_RECIPE_GROUP,y.ASSISTANT_UNKNOWN_RECIPE_GROUP(t,a,e,i,r))}}}let a=r.entityTypes.flatMap(e=>{let t=o.get(e);return t?[{entityType:e,groups:t}]:[]});return{groups:Object.fromEntries(a.map(({entityType:e,groups:t})=>[e,t.map(({group:e})=>e)])),hints:s,metaEntries:new Map(a.flatMap(({entityType:e,groups:[t]})=>t?[[e,t.entryCtx]]:[]))}},k=e=>`${e}Meta`,W={sameForAllInstances:e=>`All ${e} instances have the same recipe groups and recipes.`,stable:()=>"They do not change during the session."},L={sameForAllInstances:e=>`All ${e} instances have the same options.`,stable:()=>"The options do not change during the session."},F=(e,t,n)=>e.map(e=>` ${t[e](n)}`).join(""),K=({section:e},{groups:t,hints:n},{entityType:i,purpose:s,recipeGroup:a})=>{let p=t.filter(({dryRuns:e})=>!e).map(({groupId:e})=>e);return 0===t.length?{}:{[e]:{type:new o(new r(new o(a))),description:`The recipe groups for ${s} this ${i}: ${t.map(({groupId:e})=>e).join(", ")}. A group is listed only while the configurator offers it on the entity.${p.length>0?` Recipes of these groups cannot be dry-run: ${p.join(", ")}.`:""}${F(n,W,i)}`}}},G=({entityType:e,childRecipes:t,replaceRecipes:n,optionsEdges:i},{recipeGroup:a,fieldOption:p})=>new s({name:k(e),fields:Object.assign(K(O,t,{entityType:e,purpose:"adding children to",recipeGroup:a}),K(v,n,{entityType:e,purpose:"replacing",recipeGroup:a}),...i.map(({options:{edgeName:t,field:n,validate:i},hints:s})=>({[t]:{type:new r(new o(p)),description:`The values "${n}" of this ${e} can take, as the configurator offers them in the current state of the entity. Null when the configurator does not offer a choice on this entity. ${i?`modify${e} rejects a "${n}" value that is not in the list.`:`modify${e} does not check "${n}" against the list.`}${F(s,L,e)}`}})))}),Y=e=>Object.entries(e).map(([e,t])=>`${e} (${t.map(({groupId:e})=>e).join(", ")})`),V=(e,t)=>{let{type:n,enumValues:i,localized:r,description:o}=m(e,t);return{type:{kind:"value",type:n},localized:!0===r,description:o,enumValues:i}},x=(e,t,n,i,r)=>{let o=t.startsWith("$")?((e,t,n,i)=>{let r=((e,t,{expressions:n,entityTypes:i})=>{let r=i.find(t=>t===e);for(let i of void 0===r?[e]:n.entityExpressions.get(r)?.shapeGroups??[]){let e=[...n.expressions.get(i)?.values()??[]].find(e=>e.name===t);if(e?.declaredSchema)return{implementation:e.implementation,declaredSchema:e.declaredSchema}}})(e.name,t,n);if(!r)return void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t));let{implementation:o}=r;if("violations"===o.kind)return void i.error(f.ASSISTANT_UNSUPPORTED_EXPRESSION,y.ASSISTANT_UNSUPPORTED_EXPRESSION(e.name,t));if("relation"===o.kind){let[{target:e,cardinality:t}]=o.params;return{type:{kind:"edge",target:e,cardinality:t},localized:!1,description:void 0}}return V(r.declaredSchema,n.resolveRef)})(e,t,i,r):((e,t,{resolveRef:n},i)=>{let r=Object.entries(e.shape.properties).find(([e])=>e===t)?.[1];return r?V(r,n):void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t))})(e,t,i,r);if(!o)return;let s=n?.as??(t.startsWith("$")?`_${t.slice(1)}`:t);return b.has(s)?void r.error(f.ASSISTANT_RESERVED_FIELD_NAME,y.ASSISTANT_RESERVED_FIELD_NAME(e.name,t,s)):{name:s,source:t,type:o.type,localized:o.localized,description:R(n?.description??o.description,o.enumValues),describedByManifest:n?.description!==void 0}},B=(e,t,n,i)=>{let r=new Map,o=new Set(n);for(let s of[...t.flat(),...n]){let t=r.get(s.name);t?t.source!==s.source?i.error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,s.name,[t.source,s.source])):o.has(s)&&s.describedByManifest&&r.set(s.name,{...t,description:s.description,describedByManifest:!0}):r.set(s.name,s)}return[...r.values()]},q=({target:e,cardinality:t},n)=>{let i=n(e);switch(t){case"1-1":return new o(i);case"0-1":return i;case"0-N":case"1-N":return new o(new r(new o(i)))}},z=(e,n,i)=>{let r={id:{type:new o(t),description:i?`Unique id of the entity, e.g. "${i}-1".`:void 0},type:{type:new o(p),description:i?`Entity type name, e.g. "${i}".`:void 0}};for(let t of e)r[t.name]={type:"edge"===t.type.kind?q(t.type,n):t.type.type,description:t.description};return r},H=e=>Object.fromEntries(e.map(({name:e,source:t,localized:n})=>[e,n?{source:t,localized:!0}:{source:t}]));export const createAssistantSchema=(u,{model:b,states:W,phxDefinitions:L,expressions:F,components:K},V)=>{let q,Q,X,J,Z=V.errors.length,ee=V.at("entities"),et=S(b.commonTypes,L),en=b.rootEntityTypes[0]??b.entityTypes[0];for(let e of b.resolvedShapes.keys())$.has(e)&&V.error(f.ASSISTANT_RESERVED_TYPE_NAME,y.ASSISTANT_RESERVED_TYPE_NAME(e,[...$]));let ei=((e,t,n)=>{let i=new Map;for(let r of e){let e=[];for(let[i,o]of Object.entries(r.entries)){let s=x(r,i,o,t,n.at(r.name,i));s&&e.push(s)}i.set(r.name,e)}return i})(((e,t,n)=>{let i=[];for(let[n,r]of t.resolvedShapes){let t=e[n];t&&i.push({name:n,shape:r,entries:t})}let r=new Set(t.resolvedShapes.keys());for(let t of Object.keys(e))r.has(t)||n.at(t).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("entities",t));return i})(u.entities??{},b,ee),{resolveRef:et,expressions:F,entityTypes:b.entityTypes},ee),er=B(T,[],ei.get(T)??[],V),eo=new Map,es=C(u.childRecipes??{},O,{model:b,components:K},V.at(O.section)),ea=C(u.replaceRecipes??{},v,{model:b,components:K},V.at(v.section)),ep=es.groups,el=ea.groups,ed=new Map,ec=e=>{let[t,...n]=[...b.aliases].find(([t])=>t===e)?.[1]??[];return(t&&0===n.length?eo.get(t):void 0)??ey.get(e)??ef},eh=e=>eo.get(e)??ec(e),ef=new i({name:T,description:"Every domain entity.",fields:()=>z(er,eh,en)}),ey=new Map([[T,ef]]),eu=new Map([[T,er]]);for(let e of b.aliases.keys()){if(e===T)continue;let t=B(e,[er],ei.get(e)??[],V);eu.set(e,t),ey.set(e,new i({name:e,interfaces:[ef],fields:()=>z(t,eh)}))}let eg={};for(let e of b.entityTypes){let t=[T,...[...b.aliases].filter(([t,n])=>t!==T&&n.includes(e)).map(([e])=>e)],n=B(e,t.map(e=>eu.get(e)??[]),ei.get(e)??[],V);eg[e]=H(n),eo.set(e,new s({name:e,interfaces:t.flatMap(e=>ey.get(e)??[]),fields:()=>{let t=ed.get(e);return{...z(n,eh),...t?{meta:{type:new o(t),description:"What the configurator offers on this entity besides its fields."}}:{}}}}))}let em=((e,t,n)=>{let i=new Set;for(let r of Object.keys(e)){let e=t.entityTypes.find(e=>e===r),o=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1];o?o.forEach(e=>i.add(e)):n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("deletable",r))}return t.entityTypes.filter(e=>i.has(e))})(u.deletable??{},b,V.at("deletable")),eS=((e,t,n)=>{let{model:i}=t,r=((e,t,n)=>{let i=new Map;for(let[r,o]of Object.entries(e)){let e=t.entityTypes.find(e=>e===r),s=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1],a=[...t.resolvedShapes].find(([e])=>e===r)?.[1];if(!s||!a){n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("writable",r));continue}for(let e of Object.keys(o)){let t=n.at(r,e);e.startsWith("$")||M.has(e)?t.error(f.ASSISTANT_NOT_WRITABLE,y.ASSISTANT_NOT_WRITABLE(r,e)):D(a.properties,e)?s.forEach(t=>{let n=i.get(t)??new Map;i.set(t,n.has(e)?n:n.set(e,r))}):t.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("writable",r,e))}}return i})(e,i,n);return i.entityTypes.flatMap(e=>{let o=[...i.resolvedShapes].find(([t])=>t===e)?.[1],s=[...r.get(e)??[]].flatMap(([i,r])=>{let s=o&&D(o.properties,i);return(s&&((e,{property:t,writableKey:n},i,{resolveRef:r,exposed:o,sources:s},a)=>{let p=Object.entries(D(s,e)??{}),c=o.get(e)?.find(({source:e})=>e===t)?.name??p.find(([,{source:e}])=>e===t)?.[0],h=void 0===c?p.find(([e])=>e===t)?.[1]:void 0;if(h)return void a.at(n,t).error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,t,[h.source,t],`${n}.${t}`));let{type:u,enumValues:S,localized:T,description:w}=m(i,r),N=l(u),E=c??t,A=void 0===c?R(w,S):void 0;return T?{name:E,property:t,type:g,description:A?`${A} ${j}`:j}:{name:E,property:t,type:d(N)?N:g,description:A}})(e,{property:i,writableKey:r},s,t,n))??[]});return s.length>0?[{entityType:e,fields:s}]:[]})})(u.writable??{},{model:b,resolveRef:et,exposed:ei,sources:eg},V.at("writable")),eT=((e,t,n,i)=>{let{model:r}=n,o=new Map;for(let[s,a]of Object.entries(e)){let e=r.entityTypes.find(e=>e===s),p=e?[e]:[...r.aliases].find(([e])=>e===s)?.[1]??[];for(let[e,r]of Object.entries(a)){let a=r?.options;if(!a)continue;let l=i.at(s,e,"options"),d=`${s}.${e}`;for(let i of p){let r=t.find(e=>e.entityType===i)?.fields.find(t=>t.property===e);if(!r)continue;let s=a.as??`${r.name}Options`,p=P(i,a.componentType,n),c=o.get(i)??[],h=c.find(e=>e.options.edgeName===s||e.options.field===r.name);if(p.includes(a.instanceName))if(s===O.section||s===v.section)l.error(f.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,y.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(d,s,r.name));else if(h)l.error(f.ASSISTANT_DUPLICATE_OPTIONS_EDGE,y.ASSISTANT_DUPLICATE_OPTIONS_EDGE(i,h.options.edgeName===s?{edgeName:s}:{field:r.name},[h.entry,d]));else{let e={field:r.name,edgeName:s,componentType:a.componentType,instanceName:a.instanceName,validate:a.validate??!0};o.set(i,[...c,{options:e,hints:U(a.hints),entry:d,entryCtx:l}])}else l.error(f.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,y.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(d,a,i,p))}}}return o})(u.writable??{},eS,{model:b,components:K},V.at("writable"));var ew,eN,eE,eA=[es.metaEntries,ea.metaEntries,new Map([...eT].flatMap(([e,[t]])=>t?[[e,t.entryCtx]]:[]))];for(let e of b.entityTypes){let t=eA.flatMap(t=>t.get(e)??[])[0],n=k(e);t&&[...b.resolvedShapes.keys()].some(e=>e===n)&&t.error(f.ASSISTANT_META_TYPE_NAME_CONFLICT,y.ASSISTANT_META_TYPE_NAME_CONFLICT(e,n))}let e_={recipeGroup:(ew=[...Object.keys(ep).length>0?[O.mutation]:[],...Object.keys(el).length>0?[v.mutation]:[]],eN=()=>ec(ey.has(w)?w:T),eE=()=>ec(T),q=ew.join(" or "),Q=new s({name:_,description:"One reason a recipe cannot be used right now.",fields:{type:{type:new o(p),description:'Kind of the problem, or "uncaught".'},entityId:{type:t,description:"The entity the problem is on, when it is on one."},message:{type:p,description:"The problem as the configurator words it for the user."}}}),X=new s({name:A,description:"What using a recipe would do, tried out on the configuration the query reads. Nothing is changed.",fields:()=>({ok:{type:new o(e),description:`Whether ${q} would succeed with this recipe.`},root:{type:eN(),description:"The root entity of the configuration as it would be after the change; null when ok is false. Everything selected under it reads that configuration."},newEntities:{type:new o(new r(new o(eE()))),description:`The entities ${q} would return, read from that configuration; empty when ok is false.`},errors:{type:new o(new r(new o(Q))),description:"Why the recipe cannot be used; empty when ok is true."}})}),J=new s({name:E,description:"One recipe of a recipe group: something that can be added to the entity, or something the entity can be replaced with, depending on the edge the group is listed under.",fields:{key:{type:new o(p),description:`Identifies the recipe within its group; pass it to ${q} as recipeKey. Keys can change with the configuration and with the language, so read them from the listing rather than remembering them.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Thumbnail shown to the user."},entityType:{type:new o(p),description:"Type of the entity the recipe adds under the parent, or of the entity it replaces the current one with."},dryRun:{type:X,description:"Tries the recipe out. Each selected dry-run costs a full recalculation, so select it only on the recipes you are deciding between. Null for a group whose recipes cannot be dry-run."}}}),new s({name:N,description:"A group of recipes of an entity, as the configurator offers them to the user.",fields:{groupId:{type:new o(p),description:`Identifies the group on its entity; pass it to ${q} as recipeGroupId.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},recipes:{type:new o(new r(new o(J)))}}})),fieldOption:new s({name:I,description:"One choice of a field, as the configurator offers it to the user.",fields:{value:{type:new o(g),description:"The value to write to the field."},name:{type:p,description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Image shown to the user."},color:{type:p,description:'Color shown to the user, as "#rrggbb".'}}})};for(let e of b.entityTypes){let t=D(ep,e)??[],n=D(el,e)??[],i=eT.get(e)??[];(t.length>0||n.length>0||i.length>0)&&ed.set(e,G({entityType:e,childRecipes:{groups:t,hints:es.hints.get(e)??[]},replaceRecipes:{groups:n,hints:ea.hints.get(e)??[]},optionsEdges:i},e_))}let eI=Object.fromEntries(b.entityTypes.flatMap(e=>{let t=eT.get(e);return t?[[e,t.map(({options:e})=>e)]]:[]}));if(V.errors.length>Z)return;let eO=((e,t)=>{let n;try{let t=e();if(n=h(t).map(e=>e.message),0===n.length)return c(t)}catch(e){n=[e instanceof Error?e.message:String(e)]}t.error(f.ASSISTANT_INVALID_SCHEMA,y.ASSISTANT_INVALID_SCHEMA(n))})(()=>{var e,i;let l;return new a({query:(e=ec(ey.has(w)?w:T),i=ec(T),l=(e=>{let t={};for(let[n,i,r]of[["navigationState","Active navigation state.",e.navigationStates],["viewState","Active view state.",e.viewStates],["toolState","Active tool state.",e.toolStates]])r.length>1&&(t[n]={type:new o(p),description:R(i,r)});if(0!==Object.keys(t).length)return new s({name:"Navigation",description:"The active UI states of the configurator.",fields:t})})(W),new s({name:"Query",fields:{root:{type:new o(e),description:"The root entity of the configuration."},entities:{type:new o(new r(i)),args:{ids:{type:new r(new o(t))}},description:`Every entity of the configuration, or, when ids are given, those entities in the same order with null for an unknown id. Ids have the form "<Type>-<number>"${en?`, e.g. "${en}-1"`:""}; any other id is an error.`},selectedEntity:{type:new o(i),description:"The selected entity, or the root entity when nothing is selected."},...l?{navigation:{type:new o(l)}}:{}}})),mutation:(({deletableTypes:e,writableTypes:i,childRecipes:a,replaceRecipes:l,objectTypes:d,anyDomainEntity:c})=>{let h,f;if(0!==e.length||0!==i.length||0!==Object.keys(a).length||0!==Object.keys(l).length)return new s({name:"Mutation",fields:Object.assign(0===e.length?{}:{deleteEntity:{type:new o(new r(new o(t))),args:{id:{type:new o(t)}},description:`Deletes the entity with the given id, together with the entities composed into it, and returns the ids of every entity the deletion removed, the given one first. Deletable entity types: ${e.join(", ")}. Nothing can be read from removed entities afterwards, so query what you need from them before deleting.`}},0===(h=Y(a)).length?{}:{addChild:{type:new o(new r(new o(c))),args:{parentId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Adds a child to the entity with the id parentId by one recipe of one of its recipe groups. Entity types with recipe groups: ${h.join("; ")}. Read the groupId and the recipe key from "meta { childRecipes }" of the parent. Returns every entity the change added, the recipe's own first and then whatever the configurator added in response, such as a part the new child needs; the list is empty when the configurator removed them again.`}},0===(f=Y(l)).length?{}:{replaceEntity:{type:new o(new r(new o(c))),args:{entityId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Replaces the entity with the id entityId by one recipe of one of its replace recipe groups. Entity types with replace recipe groups: ${f.join("; ")}. Read the groupId and the recipe key from "meta { replaceRecipes }" of the entity. The replacement is a new entity with a new id: the id passed in no longer exists afterwards, and the replacement has the field values of its recipe, not those of the entity it replaces. Returns every entity the change added, the replacement first and then whatever the configurator added in response, such as a part the replacement needs; the list is empty when the configurator removed them again.`}},...i.flatMap(e=>{let i=d.get(e.entityType);return i?[(({entityType:e,fields:i},r)=>{let s=Object.fromEntries(i.map(({name:e,type:t,description:n})=>[e,{type:t,description:n}]));return{[`modify${e}`]:{type:r,args:{id:{type:new o(t)},delta:{type:new o(new n({name:`${e}Delta`,fields:s}))}},description:`Changes writable fields of the one ${e} with the given id: ${i.map(({name:e})=>e).join(", ")}. The delta sets only the fields it names and needs at least one; values are in stored units, as the field descriptions say. Returns the entity as it is after the change, including what the configurator adjusted in response, or null when the change caused the entity to be removed.`}}})(e,i)]:[]}))})})({deletableTypes:em,writableTypes:eS,childRecipes:ep,replaceRecipes:el,objectTypes:eo,anyDomainEntity:ec(T)}),types:[...ey.values(),...eo.values()]})},V);return void 0===eO?void 0:{sdl:eO,fields:eg,deletableTypes:em,writableFields:Object.fromEntries(eS.map(({entityType:e,fields:t})=>[e,Object.fromEntries(t.map(({name:e,property:t})=>[e,t]))])),childRecipes:ep,replaceRecipes:el,fieldOptions:eI}};
1
+ import{GraphQLBoolean as e,GraphQLID as t,GraphQLInputObjectType as n,GraphQLInterfaceType as i,GraphQLList as r,GraphQLNonNull as o,GraphQLObjectType as s,GraphQLSchema as a,GraphQLString as p,getNullableType as d,isInputType as l,printSchema as c,validateSchema as h}from"graphql";import{DiagnosticCode as f,diagnosticMessages as y}from"../../../../errors/index.js";import{ASSISTANT_HINTS as u}from"../../../raw-spec/index.js";import{GraphQLJSON as g,assistantFieldType as m,createAssistantRefResolver as S}from"./assistant-field-type.js";let w="AnyDomainEntity",T="RootEntity",N="RecipeGroup",E="Recipe",A="DryRun",I="DryRunError",_="FieldOption",v={section:"childRecipes",component:"childEntityRecipes",mutation:"addChild"},O={section:"replaceRecipes",component:"replaceEntityRecipes",mutation:"replaceEntity"},b=new Set(["id","type","meta"]),R=new Set(["Query","Mutation","Navigation",N,E,A,I,_,"JSON","String","Int","Float","Boolean","ID"]),$=(e,t)=>{if(!t||0===t.length)return e;let n=`One of: ${t.map(e=>`"${e}"`).join(", ")}.`;return e?/[.!?]$/.test(e)?`${e} ${n}`:`${e}. ${n}`:n},D=new Set(["id","type"]),M="The raw stored value: a string, a message descriptor or a multilingual object.",j=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],P=(e,t,{model:n,components:i})=>{let r=new Set([e,...[...n.aliases].filter(([,t])=>t.includes(e)).map(([e])=>e)]);return i.filter(({componentName:e,typeOrAlias:n})=>e===t&&r.has(n)).map(({instanceName:e})=>String(e))},U=(...e)=>u.filter(t=>e.some(e=>e?.includes(t))),C=(e,t,n,i)=>{let{model:r}=n,o=new Map,s=new Map;for(let[a,{groups:p,hints:d}]of Object.entries(e)){let e=r.entityTypes.find(e=>e===a),l=e?[e]:[...r.aliases].find(([e])=>e===a)?.[1];if(!l){i.at(a).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE(t.section,a));continue}for(let[e,r]of(l.forEach(e=>s.set(e,U(s.get(e),d))),Object.entries(p))){let s=i.at(a,"groups",e),p=`${a}.groups.${e}`,d={groupId:r?.as??e,instanceName:e,...r?.description===void 0?{}:{description:r.description},dryRuns:r?.allowDryRuns??!0};for(let i of l){let r=P(i,t.component,n),l=o.get(i)??[],c=l.find(e=>e.group.groupId===d.groupId);r.includes(e)?c?s.error(f.ASSISTANT_DUPLICATE_RECIPE_GROUP,y.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,i,d.groupId,[c.entry,p])):o.set(i,[...l,{group:d,entry:p,entryCtx:s}]):s.error(f.ASSISTANT_UNKNOWN_RECIPE_GROUP,y.ASSISTANT_UNKNOWN_RECIPE_GROUP(t,a,e,i,r))}}}let a=r.entityTypes.flatMap(e=>{let t=o.get(e);return t?[{entityType:e,groups:t}]:[]});return{groups:Object.fromEntries(a.map(({entityType:e,groups:t})=>[e,t.map(({group:e})=>e)])),hints:s,metaEntries:new Map(a.flatMap(({entityType:e,groups:[t]})=>t?[[e,t.entryCtx]]:[]))}},k=e=>`${e}Meta`,W={sameForAllInstances:e=>`All ${e} instances have the same recipe groups and recipes.`,constantDuringSession:()=>"They do not change during the session."},L={sameForAllInstances:e=>`All ${e} instances have the same options.`,constantDuringSession:()=>"The options do not change during the session."},F=(e,t,n)=>e.map(e=>` ${t[e](n)}`).join(""),K=({section:e},{groups:t,hints:n},{entityType:i,purpose:s,recipeGroup:a})=>{let p=t.filter(({dryRuns:e})=>!e).map(({groupId:e})=>e);return 0===t.length?{}:{[e]:{type:new o(new r(new o(a))),description:`The recipe groups for ${s} this ${i}: ${t.map(({groupId:e})=>e).join(", ")}. A group is listed only while the configurator offers it on the entity.${p.length>0?` Recipes of these groups cannot be dry-run: ${p.join(", ")}.`:""}${F(n,W,i)}`}}},G=({entityType:e,childRecipes:t,replaceRecipes:n,optionsEdges:i},{recipeGroup:a,fieldOption:p})=>new s({name:k(e),fields:Object.assign(K(v,t,{entityType:e,purpose:"adding children to",recipeGroup:a}),K(O,n,{entityType:e,purpose:"replacing",recipeGroup:a}),...i.map(({options:{edgeName:t,field:n,validate:i,dryRuns:s},hints:a})=>({[t]:{type:new r(new o(p)),description:`The values "${n}" of this ${e} can take, as the configurator offers them in the current state of the entity. Null when the configurator does not offer a choice on this entity. ${i?`modify${e} rejects a "${n}" value that is not in the list.`:`modify${e} does not check "${n}" against the list.`}${s?"":" Its options cannot be dry-run."}${F(a,L,e)}`}})))}),V=e=>Object.entries(e).map(([e,t])=>`${e} (${t.map(({groupId:e})=>e).join(", ")})`),Y=(e,t)=>{let{type:n,enumValues:i,localized:r,description:o}=m(e,t);return{type:{kind:"value",type:n},localized:!0===r,description:o,enumValues:i}},x=(e,t,n,i,r)=>{let o=t.startsWith("$")?((e,t,n,i)=>{let r=((e,t,{expressions:n,entityTypes:i})=>{let r=i.find(t=>t===e);for(let i of void 0===r?[e]:n.entityExpressions.get(r)?.shapeGroups??[]){let e=[...n.expressions.get(i)?.values()??[]].find(e=>e.name===t);if(e?.declaredSchema)return{implementation:e.implementation,declaredSchema:e.declaredSchema}}})(e.name,t,n);if(!r)return void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t));let{implementation:o}=r;if("violations"===o.kind)return void i.error(f.ASSISTANT_UNSUPPORTED_EXPRESSION,y.ASSISTANT_UNSUPPORTED_EXPRESSION(e.name,t));if("relation"===o.kind){let[{target:e,cardinality:t}]=o.params;return{type:{kind:"edge",target:e,cardinality:t},localized:!1,description:void 0}}return Y(r.declaredSchema,n.resolveRef)})(e,t,i,r):((e,t,{resolveRef:n},i)=>{let r=Object.entries(e.shape.properties).find(([e])=>e===t)?.[1];return r?Y(r,n):void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t))})(e,t,i,r);if(!o)return;let s=n?.as??(t.startsWith("$")?`_${t.slice(1)}`:t);return b.has(s)?void r.error(f.ASSISTANT_RESERVED_FIELD_NAME,y.ASSISTANT_RESERVED_FIELD_NAME(e.name,t,s)):{name:s,source:t,type:o.type,localized:o.localized,description:$(n?.description??o.description,o.enumValues),describedByManifest:n?.description!==void 0,enumValues:o.enumValues,valueDescription:n?.description??o.description}},q=(e,t,n,i,r)=>{let o=new Map,s=new Set(n);for(let i of[...t.flat(),...n]){let t=o.get(i.name);t?t.source!==i.source?r.error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,i.name,[t.source,i.source])):s.has(i)&&i.describedByManifest&&o.set(i.name,{...t,description:i.description,describedByManifest:!0,valueDescription:i.valueDescription}):o.set(i.name,i)}return[...o.values()].map(e=>{let t=e.enumValues&&i(e.source);return t?{...e,enumValues:t,description:$(e.valueDescription,t)}:e})},B=({target:e,cardinality:t},n)=>{let i=n(e);switch(t){case"1-1":return new o(i);case"0-1":return i;case"0-N":case"1-N":return new o(new r(new o(i)))}},z=(e,n,i)=>{let r={id:{type:new o(t),description:i?`Unique id of the entity, e.g. "${i}-1".`:void 0},type:{type:new o(p),description:i?`Entity type name, e.g. "${i}".`:void 0}};for(let t of e)r[t.name]={type:"edge"===t.type.kind?B(t.type,n):t.type.type,description:t.description};return r},H=e=>Object.fromEntries(e.map(({name:e,source:t,localized:n})=>[e,n?{source:t,localized:!0}:{source:t}]));export const createAssistantSchema=(u,{model:b,states:W,phxDefinitions:L,expressions:F,components:K},Y)=>{let B,Q,X,J=Y.errors.length,Z=Y.at("entities"),ee=S(b.commonTypes,L),et=b.rootEntityTypes[0]??b.entityTypes[0];for(let e of b.resolvedShapes.keys())R.has(e)&&Y.error(f.ASSISTANT_RESERVED_TYPE_NAME,y.ASSISTANT_RESERVED_TYPE_NAME(e,[...R]));let en=((e,t,n)=>{let i=new Map;for(let r of e){let e=[];for(let[i,o]of Object.entries(r.entries)){let s=x(r,i,o,t,n.at(r.name,i));s&&e.push(s)}i.set(r.name,e)}return i})(((e,t,n)=>{let i=[];for(let[n,r]of t.resolvedShapes){let t=e[n];t&&i.push({name:n,shape:r,entries:t})}let r=new Set(t.resolvedShapes.keys());for(let t of Object.keys(e))r.has(t)||n.at(t).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("entities",t));return i})(u.entities??{},b,Z),{resolveRef:ee,expressions:F,entityTypes:b.entityTypes},Z),ei=q(w,[],en.get(w)??[],()=>void 0,Y),er=new Map,eo=C(u.childRecipes??{},v,{model:b,components:K},Y.at(v.section)),es=C(u.replaceRecipes??{},O,{model:b,components:K},Y.at(O.section)),ea=eo.groups,ep=es.groups,ed=new Map,el=e=>{let[t,...n]=[...b.aliases].find(([t])=>t===e)?.[1]??[];return(t&&0===n.length?er.get(t):void 0)??ef.get(e)??eh},ec=e=>er.get(e)??el(e),eh=new i({name:w,description:"Every domain entity.",fields:()=>z(ei,ec,et)}),ef=new Map([[w,eh]]),ey=new Map([[w,ei]]);for(let e of b.aliases.keys()){if(e===w)continue;let t=q(e,[ei],en.get(e)??[],()=>void 0,Y);ey.set(e,t),ef.set(e,new i({name:e,interfaces:[eh],fields:()=>z(t,ec)}))}let eu={};for(let e of b.entityTypes){let t=[w,...[...b.aliases].filter(([t,n])=>t!==w&&n.includes(e)).map(([e])=>e)],n=[...b.resolvedShapes].find(([t])=>t===e)?.[1],i=q(e,t.map(e=>ey.get(e)??[]),en.get(e)??[],e=>{let t=Object.entries(n?.properties??{}).find(([t])=>t===e)?.[1];return t&&m(t,ee).enumValues},Y);eu[e]=H(i),er.set(e,new s({name:e,interfaces:t.flatMap(e=>ef.get(e)??[]),fields:()=>{let t=ed.get(e);return{...z(i,ec),...t?{meta:{type:new o(t),description:"What the configurator offers on this entity besides its fields."}}:{}}}}))}let eg=((e,t,n)=>{let i=new Set;for(let r of Object.keys(e)){let e=t.entityTypes.find(e=>e===r),o=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1];o?o.forEach(e=>i.add(e)):n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("deletable",r))}return t.entityTypes.filter(e=>i.has(e))})(u.deletable??{},b,Y.at("deletable")),em=((e,t,n)=>{let{model:i}=t,r=((e,t,n)=>{let i=new Map;for(let[r,o]of Object.entries(e)){let e=t.entityTypes.find(e=>e===r),s=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1],a=[...t.resolvedShapes].find(([e])=>e===r)?.[1];if(!s||!a){n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("writable",r));continue}for(let e of Object.keys(o)){let t=n.at(r,e);e.startsWith("$")||D.has(e)?t.error(f.ASSISTANT_NOT_WRITABLE,y.ASSISTANT_NOT_WRITABLE(r,e)):j(a.properties,e)?s.forEach(t=>{let n=i.get(t)??new Map;i.set(t,n.has(e)?n:n.set(e,r))}):t.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("writable",r,e))}}return i})(e,i,n);return i.entityTypes.flatMap(e=>{let o=[...i.resolvedShapes].find(([t])=>t===e)?.[1],s=[...r.get(e)??[]].flatMap(([i,r])=>{let s=o&&j(o.properties,i);return(s&&((e,{property:t,writableKey:n},i,{resolveRef:r,exposed:o,sources:s},a)=>{let p=Object.entries(j(s,e)??{}),c=o.get(e)?.find(({source:e})=>e===t)?.name??p.find(([,{source:e}])=>e===t)?.[0],h=void 0===c?p.find(([e])=>e===t)?.[1]:void 0;if(h)return void a.at(n,t).error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,t,[h.source,t],`${n}.${t}`));let{type:u,enumValues:S,localized:w,description:T}=m(i,r),N=d(u),E=c??t,A=void 0===c?$(T,S):void 0;return w?{name:E,property:t,type:g,description:A?`${A} ${M}`:M}:{name:E,property:t,type:l(N)?N:g,description:A}})(e,{property:i,writableKey:r},s,t,n))??[]});return s.length>0?[{entityType:e,fields:s}]:[]})})(u.writable??{},{model:b,resolveRef:ee,exposed:en,sources:eu},Y.at("writable")),eS=((e,t,n,i)=>{let{model:r}=n,o=new Map;for(let[s,a]of Object.entries(e)){let e=r.entityTypes.find(e=>e===s),p=e?[e]:[...r.aliases].find(([e])=>e===s)?.[1]??[];for(let[e,r]of Object.entries(a)){let a=r?.options;if(!a)continue;let d=i.at(s,e,"options"),l=`${s}.${e}`;for(let i of p){let r=t.find(e=>e.entityType===i)?.fields.find(t=>t.property===e);if(!r)continue;let s=a.as??`${r.name}Options`,p=P(i,a.componentType,n),c=o.get(i)??[],h=c.find(e=>e.options.edgeName===s||e.options.field===r.name);if(p.includes(a.instanceName))if(s===v.section||s===O.section)d.error(f.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,y.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(l,s,r.name));else if(h)d.error(f.ASSISTANT_DUPLICATE_OPTIONS_EDGE,y.ASSISTANT_DUPLICATE_OPTIONS_EDGE(i,h.options.edgeName===s?{edgeName:s}:{field:r.name},[h.entry,l]));else{let e={field:r.name,edgeName:s,componentType:a.componentType,instanceName:a.instanceName,validate:a.validate??!0,dryRuns:a.allowDryRuns??!0};o.set(i,[...c,{options:e,hints:U(a.hints),entry:l,entryCtx:d}])}else d.error(f.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,y.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(l,a,i,p))}}}return o})(u.writable??{},em,{model:b,components:K},Y.at("writable"));var ew,eT,eN,eE=[eo.metaEntries,es.metaEntries,new Map([...eS].flatMap(([e,[t]])=>t?[[e,t.entryCtx]]:[]))];for(let e of b.entityTypes){let t=eE.flatMap(t=>t.get(e)??[])[0],n=k(e);t&&[...b.resolvedShapes.keys()].some(e=>e===n)&&t.error(f.ASSISTANT_META_TYPE_NAME_CONFLICT,y.ASSISTANT_META_TYPE_NAME_CONFLICT(e,n))}let eA=(ew=()=>el(ef.has(T)?T:w),eT=()=>el(w),B=new s({name:I,description:"One reason a change cannot be made right now.",fields:{type:{type:new o(p),description:'Kind of the problem, or "uncaught".'},entityId:{type:t,description:"The entity the problem is on, when it is on one."},message:{type:p,description:"The problem as the configurator words it for the user."}}}),new s({name:A,description:"What using a recipe or writing an option would do, tried out on the configuration the query reads. Nothing is changed.",fields:()=>({ok:{type:new o(e),description:"Whether the change would succeed on the configuration the query reads."},root:{type:ew(),description:"The root entity of the configuration as it would be after the change; null when ok is false. Everything selected under it reads that configuration."},changedEntities:{type:new o(new r(new o(eT()))),description:"Every entity the change would add or modify, read from that configuration; empty when ok is false. An entity whose id the configuration does not have yet would be added, and its id may differ in the real mutation. An entity that is written to is listed even when it gets the values it already has."},deletedEntityIds:{type:new o(new r(new o(t))),description:"The ids of the entities the change would remove; empty when ok is false."},errors:{type:new o(new r(new o(B))),description:"Why the change cannot be made; empty when ok is true."}})})),eI={recipeGroup:(eN=[...Object.keys(ea).length>0?[v.mutation]:[],...Object.keys(ep).length>0?[O.mutation]:[]],Q=eN.join(" or "),X=new s({name:E,description:"One recipe of a recipe group: something that can be added to the entity, or something the entity can be replaced with, depending on the edge the group is listed under.",fields:{key:{type:new o(p),description:`Identifies the recipe within its group; pass it to ${Q} as recipeKey. Keys can change with the configuration and with the language, so read them from the listing rather than remembering them.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Thumbnail shown to the user."},dryRun:{type:eA,description:"Tries the recipe out. Each selected dry-run costs a full recalculation, so select it only on the recipes you are deciding between. Null for a group whose recipes cannot be dry-run."}}}),new s({name:N,description:"A group of recipes of an entity, as the configurator offers them to the user.",fields:{groupId:{type:new o(p),description:`Identifies the group on its entity; pass it to ${Q} as recipeGroupId.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},recipes:{type:new o(new r(new o(X)))}}})),fieldOption:new s({name:_,description:"One choice of a field, as the configurator offers it to the user.",fields:{value:{type:new o(g),description:"The value to write to the field."},name:{type:p,description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Image shown to the user."},color:{type:p,description:'Color shown to the user, as "#rrggbb".'},dryRun:{type:eA,description:"Tries writing the value to the field. Each selected dry-run costs a full recalculation, so select it only on the options you are deciding between. Null for a field whose options cannot be dry-run."}}})};for(let e of b.entityTypes){let t=j(ea,e)??[],n=j(ep,e)??[],i=eS.get(e)??[];(t.length>0||n.length>0||i.length>0)&&ed.set(e,G({entityType:e,childRecipes:{groups:t,hints:eo.hints.get(e)??[]},replaceRecipes:{groups:n,hints:es.hints.get(e)??[]},optionsEdges:i},eI))}let e_=Object.fromEntries(b.entityTypes.flatMap(e=>{let t=eS.get(e);return t?[[e,t.map(({options:e})=>e)]]:[]}));if(Y.errors.length>J)return;let ev=((e,t)=>{let n;try{let t=e();if(n=h(t).map(e=>e.message),0===n.length)return c(t)}catch(e){n=[e instanceof Error?e.message:String(e)]}t.error(f.ASSISTANT_INVALID_SCHEMA,y.ASSISTANT_INVALID_SCHEMA(n))})(()=>{var e,i;let d;return new a({query:(e=el(ef.has(T)?T:w),i=el(w),d=(e=>{let t={};for(let[n,i,r]of[["navigationState","Active navigation state.",e.navigationStates],["viewState","Active view state.",e.viewStates],["toolState","Active tool state.",e.toolStates]])r.length>1&&(t[n]={type:new o(p),description:$(i,r)});if(0!==Object.keys(t).length)return new s({name:"Navigation",description:"The active UI states of the configurator.",fields:t})})(W),new s({name:"Query",fields:{root:{type:new o(e),description:"The root entity of the configuration."},entities:{type:new o(new r(i)),args:{ids:{type:new r(new o(t))}},description:`Every entity of the configuration, or, when ids are given, those entities in the same order with null for an unknown id. Ids have the form "<Type>-<number>"${et?`, e.g. "${et}-1"`:""}; any other id is an error.`},selectedEntity:{type:new o(i),description:"The selected entity, or the root entity when nothing is selected."},...d?{navigation:{type:new o(d)}}:{}}})),mutation:(({deletableTypes:e,writableTypes:i,childRecipes:a,replaceRecipes:d,objectTypes:l,anyDomainEntity:c})=>{let h,f;if(0!==e.length||0!==i.length||0!==Object.keys(a).length||0!==Object.keys(d).length)return new s({name:"Mutation",fields:Object.assign(0===e.length?{}:{deleteEntity:{type:new o(new r(new o(t))),args:{id:{type:new o(t)}},description:`Deletes the entity with the given id, together with the entities composed into it, and returns the ids of every entity the deletion removed, the given one first. Deletable entity types: ${e.join(", ")}. Nothing can be read from removed entities afterwards, so query what you need from them before deleting.`}},0===(h=V(a)).length?{}:{addChild:{type:new o(new r(new o(c))),args:{parentId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Adds a child to the entity with the id parentId by one recipe of one of its recipe groups. Entity types with recipe groups: ${h.join("; ")}. Read the groupId and the recipe key from "meta { childRecipes }" of the parent. Returns every entity the change added, the recipe's own first and then whatever the configurator added in response, such as a part the new child needs; the list is empty when the configurator removed them again.`}},0===(f=V(d)).length?{}:{replaceEntity:{type:new o(new r(new o(c))),args:{entityId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Replaces the entity with the id entityId by one recipe of one of its replace recipe groups. Entity types with replace recipe groups: ${f.join("; ")}. Read the groupId and the recipe key from "meta { replaceRecipes }" of the entity. The replacement is a new entity with a new id: the id passed in no longer exists afterwards, and the replacement has the field values of its recipe, not those of the entity it replaces. Returns every entity the change added, the replacement first and then whatever the configurator added in response, such as a part the replacement needs; the list is empty when the configurator removed them again.`}},...i.flatMap(e=>{let i=l.get(e.entityType);return i?[(({entityType:e,fields:i},r)=>{let s=Object.fromEntries(i.map(({name:e,type:t,description:n})=>[e,{type:t,description:n}]));return{[`modify${e}`]:{type:r,args:{id:{type:new o(t)},delta:{type:new o(new n({name:`${e}Delta`,fields:s}))}},description:`Changes writable fields of the one ${e} with the given id: ${i.map(({name:e})=>e).join(", ")}. The delta sets only the fields it names and needs at least one; values are in stored units, as the field descriptions say. Returns the entity as it is after the change, including what the configurator adjusted in response, or null when the change caused the entity to be removed.`}}})(e,i)]:[]}))})})({deletableTypes:eg,writableTypes:em,childRecipes:ea,replaceRecipes:ep,objectTypes:er,anyDomainEntity:el(w)}),types:[...ef.values(),...er.values()]})},Y);return void 0===ev?void 0:{sdl:ev,fields:eu,deletableTypes:eg,writableFields:Object.fromEntries(em.map(({entityType:e,fields:t})=>[e,Object.fromEntries(t.map(({name:e,property:t})=>[e,t]))])),childRecipes:ea,replaceRecipes:ep,fieldOptions:e_}};
@@ -1,5 +1,6 @@
1
- import { type $DomainEntity, type AssistantManifest, type AssistantRecipeContext, type DomainEntity, type DomainEntityId, type DomainState, type StateUpdate, type StateUpdateEmission } from '#package/domain';
1
+ import { type $DomainEntity, type AssistantManifest, type AssistantRecipeContext, type DomainEntity, type DomainEntityId, type DomainState, type EntityId, type StateUpdate, type StateUpdateEmission } from '#package/domain';
2
2
  type AnyDomainState = DomainState<DomainEntity<string>>;
3
+ type AnyStateUpdate = StateUpdate<DomainEntity<string>, DomainEntity<string>>;
3
4
  /** An entity and the state it was read on, which everything under its `meta` field resolves against. */
4
5
  export interface EntityMetaSource {
5
6
  readonly entity: DomainEntity<string>;
@@ -9,9 +10,22 @@ export interface EntityMetaContext {
9
10
  readonly manifest: AssistantManifest;
10
11
  readonly recipes: AssistantRecipeContext;
11
12
  /** Prepares the emission of a dry-run from the state being read; nothing is staged or committed. */
12
- readonly prepareStateEmission: (updates: ReadonlyArray<StateUpdate<DomainEntity<string>, DomainEntity<string>>>, state: AnyDomainState, kind: 'committed') => StateUpdateEmission<DomainEntity<string>, Record<string, $DomainEntity<DomainEntity<string>>>>;
13
+ readonly prepareStateEmission: (updates: readonly AnyStateUpdate[], state: AnyDomainState, kind: 'committed') => StateUpdateEmission<DomainEntity<string>, Record<string, $DomainEntity<DomainEntity<string>>>>;
13
14
  /** Reads the entities of a dry-run's resulting state; `null` when the entity is not in it. */
14
15
  readonly find$Entity: (id: DomainEntityId<string>, state: AnyDomainState) => unknown;
16
+ /** Checks an entity an option dry-run would write against its shape, which the emission does not do. */
17
+ readonly validateEntity: (entity: DomainEntity<string>) => {
18
+ readonly success: true;
19
+ } | {
20
+ readonly success: false;
21
+ readonly errors: readonly string[];
22
+ };
23
+ }
24
+ /** One reason a dry-run reports for a change that cannot be made; a violation can sit on a virtual entity. */
25
+ interface DryRunError {
26
+ readonly type: string;
27
+ readonly entityId: EntityId<DomainEntity<string>> | null;
28
+ readonly message: string | null;
15
29
  }
16
30
  /**
17
31
  * The value of an entity's `meta` field: its built-ins, resolved lazily against the state the entity
@@ -28,25 +42,18 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
28
42
  name: string;
29
43
  description: string | null;
30
44
  imageUrl: string | null;
31
- entityType: () => string | undefined;
32
45
  dryRun: () => {
33
46
  ok: boolean;
34
- root: unknown;
35
- newEntities: {}[];
36
- errors: never[];
47
+ root: null;
48
+ changedEntities: never[];
49
+ deletedEntityIds: never[];
50
+ errors: readonly DryRunError[];
37
51
  } | {
38
52
  ok: boolean;
39
- root: null;
40
- newEntities: never[];
41
- errors: {
42
- type: string;
43
- entityId: null;
44
- message: string;
45
- }[] | {
46
- type: never;
47
- entityId: import("#package/domain").EntityId<DomainEntity<string>>;
48
- message: string | null;
49
- }[];
53
+ root: unknown;
54
+ changedEntities: {}[];
55
+ deletedEntityIds: DomainEntityId<string>[];
56
+ errors: never[];
50
57
  } | null;
51
58
  }[];
52
59
  }[];
@@ -59,25 +66,18 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
59
66
  name: string;
60
67
  description: string | null;
61
68
  imageUrl: string | null;
62
- entityType: () => string | undefined;
63
69
  dryRun: () => {
64
70
  ok: boolean;
65
- root: unknown;
66
- newEntities: {}[];
67
- errors: never[];
71
+ root: null;
72
+ changedEntities: never[];
73
+ deletedEntityIds: never[];
74
+ errors: readonly DryRunError[];
68
75
  } | {
69
76
  ok: boolean;
70
- root: null;
71
- newEntities: never[];
72
- errors: {
73
- type: string;
74
- entityId: null;
75
- message: string;
76
- }[] | {
77
- type: never;
78
- entityId: import("#package/domain").EntityId<DomainEntity<string>>;
79
- message: string | null;
80
- }[];
77
+ root: unknown;
78
+ changedEntities: {}[];
79
+ deletedEntityIds: DomainEntityId<string>[];
80
+ errors: never[];
81
81
  } | null;
82
82
  }[];
83
83
  }[];
@@ -1 +1 @@
1
- import{assistantAddedEntityIds as e,findAssistantFieldOptions as t,findAssistantRecipeGroups as r,prepareAssistantRecipeUpdates as i,readAssistantFieldOptions as n,readAssistantRecipeGroup as a}from"#package/domain";let s=(e,t,{entity:r,state:n},{recipes:a})=>{try{return{updates:i(e,t,r.id,n,a),error:void 0}}catch(e){if("child"===t.target.kind)throw e;return{updates:void 0,error:e instanceof Error?e.message:String(e)}}};export const createEntityMeta=(i,o)=>{let l=t=>()=>r(o.manifest,t,i.entity.type).flatMap(r=>{let n=a(t,r,i.entity.id,i.state,o.recipes);return n?[((t,r,i)=>{let{group:n,label:a,description:o,recipes:l}=t,{resolveLocalizable:p}=i.recipes;return{groupId:n.groupId,name:void 0===a?n.instanceName:p(a),description:n.description??(void 0===o?null:p(o)),recipes:l.map(n=>((t,r,i,n)=>{let{key:a,item:o}=t,{entity:l}=i,{resolveLocalizable:p}=n.recipes;return{key:a,name:p(o.title),description:void 0===o.description?null:p(o.description),imageUrl:void 0===o.thumbnailUrl?null:p(o.thumbnailUrl),entityType:()=>{let e=s(t,r,i,n).updates?.find(e=>"replaceDomainEntity"===e.kind||e.parentId===l.id);return e?"replaceDomainEntity"===e.kind?e.replacementEntity.type:e.entity.type:o.recipes[0]?.type},dryRun:()=>r.group.dryRuns?((t,r,i,n)=>{let{entity:a,state:o}=i,{recipes:l,prepareStateEmission:p,find$Entity:d}=n,{updates:u,error:c}=s(t,r,i,n);if(void 0===u)return{ok:!1,root:null,newEntities:[],errors:[{type:"uncaught",entityId:null,message:c}]};let{validity:y,state:m}=p(u,o,"committed");return y.valid?{ok:!0,root:d(m.rootEntityId,m),newEntities:e(u,a.id,{previousState:o,state:m}).flatMap(e=>d(e,m)??[]),errors:[]}:{ok:!1,root:null,newEntities:[],errors:"uncaught"===y.severity?[{type:"uncaught",entityId:null,message:y.error.message}]:y.entityViolations.filter(({violation:e})=>e.severity===y.severity).map(({entityId:e,violation:t})=>({type:t.type,entityId:e,message:void 0===t.message?null:l.resolveLocalizable(t.message)}))}})(t,r,i,n):null}})(n,t,r,i))}})(n,i,o)]:[]});return{...Object.fromEntries(t(o.manifest,i.entity.type).map(e=>[e.edgeName,()=>n(e,i.entity.id,i.state,o.recipes)])),childRecipes:l("child"),replaceRecipes:l("replace")}};
1
+ import{findAssistantFieldOptions as e,findAssistantRecipeGroups as t,modifyEntityUpdateTag as i,prepareAssistantRecipeUpdates as r,readAssistantFieldOptions as n,readAssistantRecipeGroup as s,systemUpdateFactory as a}from"#package/domain";let o=e=>({ok:!1,root:null,changedEntities:[],deletedEntityIds:[],errors:e}),d=(e,{state:t},{recipes:i,prepareStateEmission:r,find$Entity:n})=>{let{validity:s,state:a}=r(e,t,"committed");if(s.valid){let e=new Map(t.entities.map(e=>[e.id,e])),i=new Set(a.entities.map(e=>e.id));return{ok:!0,root:n(a.rootEntityId,a),changedEntities:a.entities.filter(t=>e.get(t.id)!==t).flatMap(e=>n(e.id,a)??[]),deletedEntityIds:t.entities.map(e=>e.id).filter(e=>!i.has(e)),errors:[]}}return o("uncaught"===s.severity?[{type:"uncaught",entityId:null,message:s.error.message}]:s.entityViolations.filter(({violation:e})=>e.severity===s.severity).map(({entityId:e,violation:t})=>({type:t.type,entityId:e,message:void 0===t.message?null:i.resolveLocalizable(t.message)})))};export const createEntityMeta=(l,c)=>{let p=e=>()=>t(c.manifest,e,l.entity.type).flatMap(t=>{let i=s(e,t,l.entity.id,l.state,c.recipes);return i?[((e,t,i)=>{let{group:n,label:s,description:a,recipes:l}=e,{resolveLocalizable:c}=i.recipes;return{groupId:n.groupId,name:void 0===s?n.instanceName:c(s),description:n.description??(void 0===a?null:c(a)),recipes:l.map(n=>((e,t,i,n)=>{let{key:s,item:a}=e,{resolveLocalizable:l}=n.recipes;return{key:s,name:l(a.title),description:void 0===a.description?null:l(a.description),imageUrl:void 0===a.thumbnailUrl?null:l(a.thumbnailUrl),dryRun:()=>t.group.dryRuns?((e,t,i,n)=>{let{updates:s,error:a}=((e,t,{entity:i,state:n},{recipes:s})=>{try{return{updates:r(e,t,i.id,n,s),error:void 0}}catch(e){if("child"===t.target.kind)throw e;return{updates:void 0,error:e instanceof Error?e.message:String(e)}}})(e,t,i,n);return void 0===s?o([{type:"uncaught",entityId:null,message:a}]):d(s,i,n)})(e,t,i,n):null}})(n,e,t,i))}})(i,l,c)]:[]});return{...Object.fromEntries(e(c.manifest,l.entity.type).map(e=>[e.edgeName,()=>n(e,l.entity.id,l.state,c.recipes)?.map(t=>({...t,dryRun:()=>e.dryRuns?(({field:e},{value:t},r,n)=>{let{entity:s}=r,l=Object.entries(Object.entries(n.manifest.writableFields??{}).find(([e])=>e===s.type)?.[1]??{}).find(([t])=>t===e)?.[1];if(void 0===l)throw Error(`The options of "${e}" on "${s.id}" cannot be dry-run: the schema lists them, but the configurator has no writable field "${e}" on ${s.type}. Regenerate the application so the schema matches the configurator.`);let c=r.state.entities.find(e=>e.id===s.id),p={[l]:t},u=c?n.validateEntity({...c,...p}):{success:!0};return u.success?d([a.DomainEntityModification({entityId:s.id,stateDelta:p,updateTag:i})],r,n):o([{type:"uncaught",entityId:s.id,message:`Writing ${JSON.stringify(t)} to "${e}" would make "${s.id}" an invalid ${s.type}: ${u.errors.join("; ")}.${e===l?"":` The message names the stored property: ${e} is stored as ${l}.`} The option comes from the configurator and cannot be corrected from here, so do not write it.`}])})(e,t,l,c):null}))??null])),childRecipes:p("child"),replaceRecipes:p("replace")}};
@@ -1 +1 @@
1
- import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";let p={errors:[new e('No assistant manifest in the application spec. The GraphQL schema is generated from the "assistant" section. Add an "assistant" section to a spec file to expose a schema.')]},u={errors:[new e("The configuration is not loaded yet, so there is no state to query. Run the query again once the configurator has finished loading.")]},f=new RegExp(h.pattern),y=e=>"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"id"in e&&"string"==typeof e.id,g=(e,t)=>"object"==typeof e&&null!==e?Reflect.get(e,t):void 0,v=e=>e instanceof Error?e.message:String(e),S=e=>/[.!?]$/.test(e)?e:`${e}.`,_=e=>"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype,w=(e,t)=>{let i=_(e)?e._raw:void 0;if(y(i))return i;if(!Array.isArray(e)&&!_(e))return e;if(t.has(e))throw Error("The value contains itself. Return ids or copies of the values instead of objects that reference each other.");let o=new Set([...t,e]);return Array.isArray(e)?e.map(e=>w(e,o)):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,w(t,o)]))},x=(e,t)=>Array.isArray(e)?e.map(e=>x(e,t)):"string"==typeof e||l(e)||c(e)?t(e):e,$=t=>new e(`The GraphQL schema generated from the "assistant" manifest is invalid: ${S(t)} Regenerate the application so the schema is rebuilt from the current spec.`),E=e=>(e.errors?.length??0)>0,b=t=>({errors:[new e(`Not run: operation ${t+1} failed, so the operations after it were skipped and no change of the list takes effect. Fix the failing operation and send the whole list again.`)]});export class GraphQLSystem{_context;_selectSchema=s([s.leaf(e=>e)],e=>{try{let i=t(e),o=n(i);return o.length>0?$(o.map(e=>e.message).join(" ")):i}catch(e){return $(v(e))}});_selectFieldResolver=s([s.leaf(e=>e)],t=>(a,n,r,s)=>{if(s.parentType===s.schema.getQueryType())return i(a,n,r,s);if(s.parentType===s.schema.getMutationType())return this._resolveMutation(s.fieldName,String(s.path.key),n,r);if(!y(a))return i(a,n,r,s);if("meta"===s.fieldName){let e;return m({entity:a,state:("object"==typeof(e=g(a,"_state"))&&null!==e&&"entities"in e&&"rootEntityId"in e?e:void 0)??r.state},{manifest:r.manifest,recipes:this._recipeContext(),prepareStateEmission:(e,t,i)=>this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(e,t,i),find$Entity:(e,t)=>this._find$Entity(e,t)})}let{source:l,localized:c}=t[s.parentType.name]?.[s.fieldName]??{source:s.fieldName},h=((t,i)=>{try{return g(t,i)}catch(o){throw new e(`Expression "${i}" failed on ${y(t)?t.id:"an entity"}: ${S(v(o))} The expression threw while the query read it; fix the expression or the configuration state it reads.`,{originalError:o instanceof Error?o:void 0})}})(a,l);return c?x(h,this._context.domainServicesSelectors.getResolveLocalizable()):l.startsWith("$")&&"JSON"===o(s.returnType).name?((t,i,o)=>{try{return w(o,new Set)}catch(o){throw new e(`Expression "${i}" returned a value that is not plain serializable data on ${y(t)?t.id:"an entity"}: ${S(v(o))} A JSON field can only return data that serializes to JSON.`,{originalError:o instanceof Error?o:void 0})}})(a,l,h):h});constructor(e){this._context=e}_get$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().get$Entity(e,t);_find$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().getEntity(e,t)?this._get$Entity(e,t):null;_recipeContext=()=>({componentReader:this._context.domainContextSelectors.getComponentReader(),recipeCooker:this._context.domainContextSelectors.getRecipeCookerSystem(),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});_rootValue={root:(e,{state:t})=>this._get$Entity(t.rootEntityId,t),entities:({ids:t},{state:i})=>{if(null==t)return i.entities.map(e=>this._get$Entity(e.id,i));var o=i.rootEntityId;let a=t.filter(e=>!f.test(e));if(a.length>0)throw new e(`${a.map(e=>`"${e}"`).join(", ")} ${1===a.length?"is not an entity id":"are not entity ids"}. Entity ids have the form "<Type>-<number>", e.g. "${o}". Use ids as returned by the "id" field.`);return t.map(e=>f.test(e)?this._find$Entity(e,i):null)},selectedEntity:(e,{state:t})=>this._find$Entity(this._context.domainContextSelectors.getNavigationSystem().getActiveSelectionState(t),t),navigation:(e,{state:t})=>{let i=this._context.domainContextSelectors.getNavigationSystem();return{navigationState:i.getActiveNavigationState(t),viewState:i.getActiveViewState(t),toolState:i.getActiveToolState(t)}}};_resolveType=e=>y(e)?e.type:void 0;initialize=()=>{};_resolveMutation=(t,i,o,a)=>{if(void 0!==a.failedMutationField)throw new e(`Not run: the earlier field "${a.failedMutationField}" of this operation failed, so "${i}" was skipped and no change of the operation takes effect. Fix the failing field and send the operation again.`);try{return this._runMutation(t,o,a)}catch(e){throw a.failedMutationField=i,e}};_runMutation=(t,i,o)=>{let a=d(t,o.manifest);if(!a)throw new e(`The schema declares the mutation "${t}", but the configurator has no implementation for it. Regenerate the application so the schema matches the configurator.`);let n=o.state,r=a.implementation(i,n,{manifest:o.manifest,domain:this._context.domainContextSelectors.getDomain(),...this._recipeContext()});if(r.updates.length>0){let i=this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(r.updates,n,"committed");if(!i.validity.valid)throw new e(`The changes of "${t}" were not applied, because the resulting configuration is invalid: ${(e=>{if("uncaught"===e.severity)return`validating it threw: ${S(v(e.error))}`;let t=[...new Set(e.entityViolations.filter(({violation:t})=>t.severity===e.severity).map(({entityId:e})=>e))];return`it has ${e.severity} violations on ${t.join(", ")}.`})(i.validity)} Change the request so the configuration stays valid.`);o.emissions.push(i),o.state=i.state}return r.readResult({previousState:n,state:o.state})};_setup=()=>{let t=this._context.specSelectors.getAssistant();if(!t)return{ready:!1,result:p};let i=this._selectSchema(t.sdl);return i instanceof e?{ready:!1,result:{errors:[i]}}:{ready:!0,assistant:t,schema:i,fieldResolver:this._selectFieldResolver(t.fields)}};prepare=async(e,t)=>{let i,o=this._setup();if(!o.ready)return t.map(()=>({result:o.result,emissions:[]}));let n={manifest:o.assistant,state:e,emissions:[],failedMutationField:void 0},r=[];for(let[e,s]of t.entries())if(void 0===i){let t=n.emissions.length;n.failedMutationField=void 0;let l=await a({schema:o.schema,source:s.document,rootValue:this._rootValue,contextValue:n,variableValues:s.variables,operationName:s.operationName,fieldResolver:o.fieldResolver,typeResolver:this._resolveType});r.push({result:l,emissions:n.emissions.slice(t)}),E(l)&&(i=e)}else r.push({result:b(i),emissions:[]});return r};_prepareAndCommit=async e=>{let t,i,o,a=this._context.domainContextSelectors.getStoreSystem(),n=await this.prepare(a.stateSlices.committed.value.state,e),s=n.map(({result:e})=>e),l=n.flatMap(e=>e.emissions);return s.some(E)||0===l.length?{results:s,outcome:"none"}:{results:s,outcome:a.commitPrepared((t=r(l[0]),i=r(l[l.length-1]),o=l.some(e=>void 0!==e.transformationLog),{kind:"committed",previousState:t.previousState,state:i.state,updates:l.flatMap(e=>e.updates),validity:i.validity,transformationLog:o?l.flatMap(e=>e.transformationLog??[]):void 0}))}};execute=async e=>{if(!this._context.domainContextSelectors.getStoreSystem().isInitialized)return{results:e.map(()=>u),committed:!1};let t=await this._prepareAndCommit(e),{results:i,outcome:o}="conflict"===t.outcome?await this._prepareAndCommit(e):t;return"committed"===o?{results:i,committed:!0}:"held"===o?{results:i,committed:!1,message:"The changes were not committed yet: the application held them, usually to ask the user for approval. They may still be applied once the user approves, and the next turn shows whether they were. Do not send the operations again."}:"conflict"===o?{results:i,committed:!1,message:"The changes were not committed, because the configuration changed while they were being applied. The results describe a state that was discarded. Query the current configuration and send the operations again if they still make sense."}:{results:i,committed:!1}}}
1
+ import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";let p={errors:[new e('No assistant manifest in the application spec. The GraphQL schema is generated from the "assistant" section. Add an "assistant" section to a spec file to expose a schema.')]},u={errors:[new e("The configuration is not loaded yet, so there is no state to query. Run the query again once the configurator has finished loading.")]},f=new RegExp(h.pattern),y=e=>"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"id"in e&&"string"==typeof e.id,g=(e,t)=>"object"==typeof e&&null!==e?Reflect.get(e,t):void 0,v=e=>e instanceof Error?e.message:String(e),S=e=>/[.!?]$/.test(e)?e:`${e}.`,_=e=>"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype,x=(e,t)=>{let i=_(e)?e._raw:void 0;if(y(i))return i;if(!Array.isArray(e)&&!_(e))return e;if(t.has(e))throw Error("The value contains itself. Return ids or copies of the values instead of objects that reference each other.");let o=new Set([...t,e]);return Array.isArray(e)?e.map(e=>x(e,o)):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,x(t,o)]))},w=(e,t)=>Array.isArray(e)?e.map(e=>w(e,t)):"string"==typeof e||l(e)||c(e)?t(e):e,$=t=>new e(`The GraphQL schema generated from the "assistant" manifest is invalid: ${S(t)} Regenerate the application so the schema is rebuilt from the current spec.`),E=e=>(e.errors?.length??0)>0,b=t=>({errors:[new e(`Not run: operation ${t+1} failed, so the operations after it were skipped and no change of the list takes effect. Fix the failing operation and send the whole list again.`)]});export class GraphQLSystem{_context;_selectSchema=s([s.leaf(e=>e)],e=>{try{let i=t(e),o=n(i);return o.length>0?$(o.map(e=>e.message).join(" ")):i}catch(e){return $(v(e))}});_selectFieldResolver=s([s.leaf(e=>e)],t=>(a,n,r,s)=>{if(s.parentType===s.schema.getQueryType())return i(a,n,r,s);if(s.parentType===s.schema.getMutationType())return this._resolveMutation(s.fieldName,String(s.path.key),n,r);if(!y(a))return i(a,n,r,s);if("meta"===s.fieldName){let e;return m({entity:a,state:("object"==typeof(e=g(a,"_state"))&&null!==e&&"entities"in e&&"rootEntityId"in e?e:void 0)??r.state},{manifest:r.manifest,recipes:this._recipeContext(),prepareStateEmission:(e,t,i)=>this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(e,t,i),find$Entity:(e,t)=>this._find$Entity(e,t),validateEntity:e=>this._context.domainContextSelectors.getDomain().validateEntity(e)})}let{source:l,localized:c}=t[s.parentType.name]?.[s.fieldName]??{source:s.fieldName},h=((t,i)=>{try{return g(t,i)}catch(o){throw new e(`Expression "${i}" failed on ${y(t)?t.id:"an entity"}: ${S(v(o))} The expression threw while the query read it; fix the expression or the configuration state it reads.`,{originalError:o instanceof Error?o:void 0})}})(a,l);return c?w(h,this._context.domainServicesSelectors.getResolveLocalizable()):l.startsWith("$")&&"JSON"===o(s.returnType).name?((t,i,o)=>{try{return x(o,new Set)}catch(o){throw new e(`Expression "${i}" returned a value that is not plain serializable data on ${y(t)?t.id:"an entity"}: ${S(v(o))} A JSON field can only return data that serializes to JSON.`,{originalError:o instanceof Error?o:void 0})}})(a,l,h):h});constructor(e){this._context=e}_get$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().get$Entity(e,t);_find$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().getEntity(e,t)?this._get$Entity(e,t):null;_recipeContext=()=>({componentReader:this._context.domainContextSelectors.getComponentReader(),recipeCooker:this._context.domainContextSelectors.getRecipeCookerSystem(),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});_rootValue={root:(e,{state:t})=>this._get$Entity(t.rootEntityId,t),entities:({ids:t},{state:i})=>{if(null==t)return i.entities.map(e=>this._get$Entity(e.id,i));var o=i.rootEntityId;let a=t.filter(e=>!f.test(e));if(a.length>0)throw new e(`${a.map(e=>`"${e}"`).join(", ")} ${1===a.length?"is not an entity id":"are not entity ids"}. Entity ids have the form "<Type>-<number>", e.g. "${o}". Use ids as returned by the "id" field.`);return t.map(e=>f.test(e)?this._find$Entity(e,i):null)},selectedEntity:(e,{state:t})=>this._find$Entity(this._context.domainContextSelectors.getNavigationSystem().getActiveSelectionState(t),t),navigation:(e,{state:t})=>{let i=this._context.domainContextSelectors.getNavigationSystem();return{navigationState:i.getActiveNavigationState(t),viewState:i.getActiveViewState(t),toolState:i.getActiveToolState(t)}}};_resolveType=e=>y(e)?e.type:void 0;initialize=()=>{};_resolveMutation=(t,i,o,a)=>{if(void 0!==a.failedMutationField)throw new e(`Not run: the earlier field "${a.failedMutationField}" of this operation failed, so "${i}" was skipped and no change of the operation takes effect. Fix the failing field and send the operation again.`);try{return this._runMutation(t,o,a)}catch(e){throw a.failedMutationField=i,e}};_runMutation=(t,i,o)=>{let a=d(t,o.manifest);if(!a)throw new e(`The schema declares the mutation "${t}", but the configurator has no implementation for it. Regenerate the application so the schema matches the configurator.`);let n=o.state,r=a.implementation(i,n,{manifest:o.manifest,domain:this._context.domainContextSelectors.getDomain(),...this._recipeContext()});if(r.updates.length>0){let i=this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(r.updates,n,"committed");if(!i.validity.valid)throw new e(`The changes of "${t}" were not applied, because the resulting configuration is invalid: ${(e=>{if("uncaught"===e.severity)return`validating it threw: ${S(v(e.error))}`;let t=[...new Set(e.entityViolations.filter(({violation:t})=>t.severity===e.severity).map(({entityId:e})=>e))];return`it has ${e.severity} violations on ${t.join(", ")}.`})(i.validity)} Change the request so the configuration stays valid.`);o.emissions.push(i),o.state=i.state}return r.readResult({previousState:n,state:o.state})};_setup=()=>{let t=this._context.specSelectors.getAssistant();if(!t)return{ready:!1,result:p};let i=this._selectSchema(t.sdl);return i instanceof e?{ready:!1,result:{errors:[i]}}:{ready:!0,assistant:t,schema:i,fieldResolver:this._selectFieldResolver(t.fields)}};prepare=async(e,t)=>{let i,o=this._setup();if(!o.ready)return t.map(()=>({result:o.result,emissions:[]}));let n={manifest:o.assistant,state:e,emissions:[],failedMutationField:void 0},r=[];for(let[e,s]of t.entries())if(void 0===i){let t=n.emissions.length;n.failedMutationField=void 0;let l=await a({schema:o.schema,source:s.document,rootValue:this._rootValue,contextValue:n,variableValues:s.variables,operationName:s.operationName,fieldResolver:o.fieldResolver,typeResolver:this._resolveType});r.push({result:l,emissions:n.emissions.slice(t)}),E(l)&&(i=e)}else r.push({result:b(i),emissions:[]});return r};_prepareAndCommit=async e=>{let t,i,o,a=this._context.domainContextSelectors.getStoreSystem(),n=await this.prepare(a.stateSlices.committed.value.state,e),s=n.map(({result:e})=>e),l=n.flatMap(e=>e.emissions);return s.some(E)||0===l.length?{results:s,outcome:"none"}:{results:s,outcome:a.commitPrepared((t=r(l[0]),i=r(l[l.length-1]),o=l.some(e=>void 0!==e.transformationLog),{kind:"committed",previousState:t.previousState,state:i.state,updates:l.flatMap(e=>e.updates),validity:i.validity,transformationLog:o?l.flatMap(e=>e.transformationLog??[]):void 0}))}};execute=async e=>{if(!this._context.domainContextSelectors.getStoreSystem().isInitialized)return{results:e.map(()=>u),committed:!1};let t=await this._prepareAndCommit(e),{results:i,outcome:o}="conflict"===t.outcome?await this._prepareAndCommit(e):t;return"committed"===o?{results:i,committed:!0}:"held"===o?{results:i,committed:!1,message:"The changes were not committed yet: the application held them, usually to ask the user for approval. They may still be applied once the user approves, and the next turn shows whether they were. Do not send the operations again."}:"conflict"===o?{results:i,committed:!1,message:"The changes were not committed, because the configuration changed while they were being applied. The results describe a state that was discarded. Query the current configuration and send the operations again if they still make sense."}:{results:i,committed:!1}}}
@@ -1,5 +1,5 @@
1
1
  {
2
- "generatedAt": "2026-10-07T15:22:23.840Z",
2
+ "generatedAt": "2026-10-07T17:54:56.392Z",
3
3
  "categories": [
4
4
  {
5
5
  "name": "Phoenix",
@@ -149,13 +149,17 @@ Host must pass the nonce into the web component:
149
149
  <salsita-configurator nonce="YOUR_REQUEST_NONCE"></salsita-configurator>
150
150
  ```
151
151
 
152
+ ### Starting Policy from Studio
153
+
154
+ The **CSP** tab of an environment in Studio generates a starting `<meta http-equiv="Content-Security-Policy">` tag with that environment's configurator, server and S3 bucket origins filled in. Its `script-src` and `style-src` carry the `'nonce-YOUR_REQUEST_NONCE'` placeholder: the host still has to replace it with a cryptographically random nonce generated for every request and pass the same value to `<salsita-configurator nonce="…">`. Extend the policy with any origins the host page itself needs.
155
+
152
156
  ## What Phoenix Does Not Configure
153
157
 
154
158
  Phoenix options only change SDK runtime internals. They **do not**:
155
159
 
156
160
  - set CSP headers for your hosting platform
157
- - define `script-src`, `style-src`, `connect-src`, etc.
158
- - choose your nonce strategy globally
161
+ - enforce `script-src`, `style-src`, `connect-src`, etc. (the Studio CSP tab only suggests a starting policy)
162
+ - generate nonces or choose your nonce strategy
159
163
 
160
164
  CSP policy itself is owned by the host page / hosting infra.
161
165
 
@@ -283,19 +283,20 @@ The Phoenix CLI auto-generates config files that read these variables:
283
283
 
284
284
  Starts the full development environment: Vite dev server, development webhook tunnel, domain-cli watcher, and editor WebSocket server.
285
285
 
286
- | Flag | Env Variable | Default | Description |
287
- | ------------------- | ------------------ | -------------------- | -------------------------------------------------------------------- |
288
- | `--workspace` | — | from `.phoenix.json` | Override workspace mode |
289
- | `--editor` | `ENABLE_EDITOR` | `true` | Enable editor file generation |
290
- | `--editorWsPort` | `EDITOR_WS_PORT` | `3020` | Editor WebSocket port |
291
- | `--debug` | `DEBUG` | `false` | Verbose logging |
292
- | `--projectSlug` | `PROJECT_SLUG` | `local` | Project slug |
293
- | `--environmentSlug` | `ENVIRONMENT_SLUG` | package.json name | Environment slug |
294
- | `--withLingui` | `WITH_LINGUI` | `false` | Enable i18n extraction/compilation and watch i18n sources during dev |
295
- | `--persistence` | `PERSISTENCE_MODE` | `server` | Persistence mode |
296
- | `--force` / `-f` | `FORCE_REBUILD` | `false` | Force full rebuild, skip cache |
297
- | `--serverUrl` | `SERVER_URL` | the region's server | Phoenix server URL |
298
- | `--region` | `PHOENIX_REGION` | `eu` | Region of the signed-in workspace, used when no server URL is set |
286
+ | Flag | Env Variable | Default | Description |
287
+ | ---------------------- | ------------------ | -------------------- | ------------------------------------------------------------------------------- |
288
+ | `--workspace` | — | from `.phoenix.json` | Override workspace mode |
289
+ | `--editor` | `ENABLE_EDITOR` | `true` | Enable editor file generation |
290
+ | `--editorWsPort` | `EDITOR_WS_PORT` | `3020` | Editor WebSocket port |
291
+ | `--debug` | `DEBUG` | `false` | Verbose logging |
292
+ | `--projectSlug` | `PROJECT_SLUG` | `local` | Project slug |
293
+ | `--environmentSlug` | `ENVIRONMENT_SLUG` | package.json name | Environment slug |
294
+ | `--withLingui` | `WITH_LINGUI` | `false` | Enable i18n extraction/compilation and watch i18n sources during dev |
295
+ | `--persistence` | `PERSISTENCE_MODE` | `server` | Persistence mode |
296
+ | `--force` / `-f` | `FORCE_REBUILD` | `false` | Force full rebuild, skip cache |
297
+ | `--serverUrl` | `SERVER_URL` | the region's server | Phoenix server URL |
298
+ | `--region` | `PHOENIX_REGION` | `eu` | Region of the signed-in workspace, used when no server URL is set |
299
+ | `--skipUpload` / `-su` | `SKIP_UPLOAD` | `false` | Skip the S3 asset upload when the development deployment is prepared at startup |
299
300
 
300
301
  In `server` persistence mode the project comes from `--projectSlug`, `PROJECT_SLUG` or `project` in the spec, and the credential from `DEVELOPMENT_KEY` or the `phoenix login` sign-in; see [Starting a New Project](#starting-a-new-project). When signed in, the environment is always your own development environment and `--environmentSlug` is ignored.
301
302
 
@@ -90,7 +90,8 @@ export interface AssistantRecipeGroup {
90
90
  * The options edge of one writable field the assistant manifest links to its component. `field` is
91
91
  * the delta field of `modify<Type>` the choices are for, `edgeName` the field of `<Type>Meta` that
92
92
  * lists them, `componentType` and `instanceName` the component instance they are read from, and
93
- * `validate` whether `modify<Type>` rejects a value that is not among them.
93
+ * `validate` whether `modify<Type>` rejects a value that is not among them, and `dryRuns` whether
94
+ * the choices can be dry-run.
94
95
  */
95
96
  export interface AssistantFieldOptions {
96
97
  readonly field: string;
@@ -98,6 +99,7 @@ export interface AssistantFieldOptions {
98
99
  readonly componentType: 'materialSwatch' | 'attributeSelection' | 'distanceDimensionSelect';
99
100
  readonly instanceName: string;
100
101
  readonly validate: boolean;
102
+ readonly dryRuns: boolean;
101
103
  }
102
104
  /**
103
105
  * Experimental assistant manifest generated from the application spec `assistant` section. `sdl` is
@@ -1,6 +1,6 @@
1
1
  import { type StateUpdate } from '../components/updates.js';
2
2
  import type { Domain } from '../core/domain.js';
3
- import type { $DomainEntity, DomainEntity } from '../core/model.js';
3
+ import { type $DomainEntity, type DomainEntity } from '../core/model.js';
4
4
  import type { DomainState } from '../core/state.js';
5
5
  import type { AssistantManifest } from './application-config.js';
6
6
  import { type AssistantRecipeContext } from './assistant-recipe-groups.js';
@@ -1 +1 @@
1
- import{systemUpdateFactory as e}from"../components/updates.js";import{findAssistantFieldOptions as t,readAssistantFieldOptions as i}from"./assistant-field-options.js";import{assistantAddedEntityIds as r,findAssistantRecipeGroups as n,prepareAssistantRecipeUpdates as a,readAssistantRecipeGroup as o}from"./assistant-recipe-groups.js";export const deleteEntityUpdateTag="deleteEntity";export const modifyEntityUpdateTag="modifyEntity";let s=(e,t,i)=>{let r=e.id;if("string"!=typeof r)throw Error(`The "id" argument is missing. Pass the id of the entity to ${t}, e.g. ${i}.`);return r},d="modify",l=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],p=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),h=e=>Array.isArray(e)?e.map(h):p(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,h(t)])):e,f=(e,t,i)=>{let r=e[t];if("string"!=typeof r)throw Error(`The "${t}" argument is missing. Pass all three arguments, e.g. ${i}.`);return r},u=e=>e.map(e=>`"${e}"`).join(", "),y=[{name:"deleteEntity",implementation:(t,i,{manifest:r})=>{let n=s(t,"delete",'deleteEntity(id: "Root-1")'),a=i.entities.find(e=>e.id===n);if(!a)throw Error(`Entity "${n}" does not exist, so it cannot be deleted. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);let o=r.deletableTypes??[];if(!o.includes(a.type))throw Error(`Entity "${n}" is a ${a.type}, which is not deletable. ${o.length>0?`Only entities of these types can be deleted: ${o.join(", ")}.`:"No entity type is deletable."} Delete an entity of a deletable type instead.`);return{updates:[e.EntityDeletion({entityId:a.id,updateTag:"deleteEntity"})],readResult:({previousState:e,state:t})=>{var i;let r;return[a.id,...(i=a.id,r=new Set(t.entities.map(e=>e.id)),e.entities.map(e=>e.id).filter(e=>e!==i&&!r.has(e)))]}}}},{name:"addChild",implementation:(e,t,i)=>{let s='addChild(parentId: "Root-1", recipeGroupId: "cabinets", recipeKey: "Base cabinet")',d=f(e,"parentId",s),l=f(e,"recipeGroupId",s),p=f(e,"recipeKey",s),h=t.entities.find(e=>e.id===d);if(!h)throw Error(`Entity "${d}" does not exist, so nothing can be added to it. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);let y=n(i.manifest,"child",h.type),c=y.find(e=>e.groupId===l);if(!c)throw Error(`Entity "${d}" is a ${h.type}, which has no recipe group "${l}". ${y.length>0?`Its recipe groups are: ${u(y.map(({groupId:e})=>e))}.`:`Nothing can be added to a ${h.type}.`} Query "meta { childRecipes { groupId } }" on the entity you want to add to and use a groupId it returns.`);let g=o("child",c,h.id,t,i);if(!g)throw Error(`The recipe group "${l}" is not available on "${d}" right now, so nothing can be added from it. The configurator offers a group only in some states of the configuration. Query "meta { childRecipes { groupId } }" on "${d}" to see the groups it offers now.`);let m=g.recipes.find(e=>e.key===p);if(!m)throw Error(`The recipe group "${l}" on "${d}" has no recipe with the key "${p}". Recipes and their keys change with the configuration and with the language. List the recipes of the group again and use a key it returns.`);let $=a(m,g,h.id,t,i);return{updates:$,readResult:e=>r($,h.id,e).map(t=>i.domain.get$Entity(t,e.state))}}},{name:"replaceEntity",implementation:(e,t,i)=>{let s='replaceEntity(entityId: "Cabinet-1", recipeGroupId: "otherCabinets", recipeKey: "Tall cabinet")',d=f(e,"entityId",s),l=f(e,"recipeGroupId",s),p=f(e,"recipeKey",s),h=t.entities.find(e=>e.id===d);if(!h)throw Error(`Entity "${d}" does not exist, so it cannot be replaced. It may have been deleted or replaced by an earlier operation or field; a replaced entity gets a new id. Query the current entities and use an id they return.`);let y=n(i.manifest,"replace",h.type),c=y.find(e=>e.groupId===l);if(!c)throw Error(`Entity "${d}" is a ${h.type}, which has no replace recipe group "${l}". ${y.length>0?`Its replace recipe groups are: ${u(y.map(({groupId:e})=>e))}.`:`A ${h.type} cannot be replaced.`} Query "meta { replaceRecipes { groupId } }" on the entity you want to replace and use a groupId it returns.`);let g=o("replace",c,h.id,t,i);if(!g)throw Error(`The recipe group "${l}" is not available on "${d}" right now, so it cannot be replaced from it. The configurator offers a group only in some states of the configuration. Query "meta { replaceRecipes { groupId } }" on "${d}" to see the groups it offers now.`);let m=g.recipes.find(e=>e.key===p);if(!m)throw Error(`The recipe group "${l}" on "${d}" has no recipe with the key "${p}". Recipes and their keys change with the configuration and with the language. List the recipes of the group again and use a key it returns.`);let $=a(m,g,h.id,t,i);return{updates:$,readResult:e=>r($,h.id,e).map(t=>i.domain.get$Entity(t,e.state))}}}];export const findAssistantMutation=(r,n)=>{let a,o,f=y.find(e=>e.name===r);if(f||!r.startsWith(d))return f;let u=r.slice(d.length),c=l(n.writableFields??{},u);return c&&(a=`${d}${u}`,o=Object.keys(c).join(", "),{name:a,implementation:(r,n,f)=>{let{manifest:y,domain:g}=f,m=s(r,"modify",`${a}(id: "${u}-1", delta: { ... })`),$=n.entities.find(e=>e.id===m);if(!$)throw Error(`Entity "${m}" does not exist, so it cannot be modified. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);if($.type!==u)throw Error(`Entity "${m}" is a ${$.type}, but ${a} modifies only ${u} entities. ${l(y.writableFields??{},$.type)?`Use ${d}${$.type} for it instead.`:`${$.type} has no writable fields, so it cannot be modified; pass the id of a ${u}.`}`);let E=r.delta,w=Object.entries(p(E)?E:{}).flatMap(([e,t])=>{let i=l(c,e);return void 0===i?[]:[{field:e,property:i,value:h(t)}]}),b=Object.fromEntries(w.map(({property:e,value:t})=>[e,t]));if(0===Object.keys(b).length)throw Error(`The delta of ${a} is empty, so there is nothing to change on "${m}". Set at least one of its fields: ${o}.`);let I=g.validateEntity({...$,...b});if(!I.success){let e=w.filter(({field:e,property:t})=>e!==t).map(({field:e,property:t})=>`${e} is stored as ${t}`);throw Error(`The delta would make "${m}" an invalid ${u}: ${I.errors.join("; ")}. ${e.length>0?`The messages name stored properties: ${e.join(", ")}. `:""}Nothing was changed. Send values that fit the types and the allowed values the schema describes for these fields.`)}let v=t(y,u);for(let{field:e,value:t}of w){let r=v.find(t=>t.field===e);if(!r?.validate||null===t)continue;let a=i(r,$.id,n,f);if(a&&!a.some(e=>e.value===t))throw Error(`${JSON.stringify(t)} is not a value "${e}" of "${m}" can take right now. ${a.length>0?`The configurator offers these values: ${a.map(e=>JSON.stringify(e.value)).join(", ")}.`:"The configurator offers no value for it in this state."} Nothing was changed. Send one of the offered values; "meta { ${r.edgeName} }" on the entity lists them with their names. When the values depend on another field of this delta, change that field in an earlier mutation field of the same operation.`)}return{updates:[e.DomainEntityModification({entityId:$.id,stateDelta:b,updateTag:"modifyEntity"})],readResult:({state:e})=>g.getEntity($.id,e)?g.get$Entity($.id,e):null}}})};
1
+ import{z as e}from"zod";import{systemUpdateFactory as t}from"../components/updates.js";import{DomainEntityIdSchema as i}from"../core/model.js";import{findAssistantFieldOptions as r,readAssistantFieldOptions as n}from"./assistant-field-options.js";import{assistantAddedEntityIds as o,findAssistantRecipeGroups as a,prepareAssistantRecipeUpdates as s,readAssistantRecipeGroup as d}from"./assistant-recipe-groups.js";export const deleteEntityUpdateTag="deleteEntity";export const modifyEntityUpdateTag="modifyEntity";let l=e.string().regex(new RegExp(i.pattern),'An entity id is the type name, a dash and a number, e.g. "Root-1". Query the current entities and use an id they return.'),p=e.object({id:l}),h=e.object({id:l,delta:e.record(e.unknown())}),u="modify",f=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],y=e=>Array.isArray(e)?e.map(y):"object"!=typeof e||null===e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,y(t)])),c=e.object({parentId:l,recipeGroupId:e.string(),recipeKey:e.string()}),g=e.object({entityId:l,recipeGroupId:e.string(),recipeKey:e.string()}),m=e=>e.map(e=>`"${e}"`).join(", "),$=[{name:"deleteEntity",implementation:(e,i,{manifest:r})=>{let{id:n}=p.parse(e),o=i.entities.find(e=>e.id===n);if(!o)throw Error(`Entity "${n}" does not exist, so it cannot be deleted. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);let a=r.deletableTypes??[];if(!a.includes(o.type))throw Error(`Entity "${n}" is a ${o.type}, which is not deletable. ${a.length>0?`Only entities of these types can be deleted: ${a.join(", ")}.`:"No entity type is deletable."} Delete an entity of a deletable type instead.`);return{updates:[t.EntityDeletion({entityId:o.id,updateTag:"deleteEntity"})],readResult:({previousState:e,state:t})=>{var i;let r;return[o.id,...(i=o.id,r=new Set(t.entities.map(e=>e.id)),e.entities.map(e=>e.id).filter(e=>e!==i&&!r.has(e)))]}}}},{name:"addChild",implementation:(e,t,i)=>{let{parentId:r,recipeGroupId:n,recipeKey:l}=c.parse(e),p=t.entities.find(e=>e.id===r);if(!p)throw Error(`Entity "${r}" does not exist, so nothing can be added to it. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);let h=a(i.manifest,"child",p.type),u=h.find(e=>e.groupId===n);if(!u)throw Error(`Entity "${r}" is a ${p.type}, which has no recipe group "${n}". ${h.length>0?`Its recipe groups are: ${m(h.map(({groupId:e})=>e))}.`:`Nothing can be added to a ${p.type}.`} Query "meta { childRecipes { groupId } }" on the entity you want to add to and use a groupId it returns.`);let f=d("child",u,p.id,t,i);if(!f)throw Error(`The recipe group "${n}" is not available on "${r}" right now, so nothing can be added from it. The configurator offers a group only in some states of the configuration. Query "meta { childRecipes { groupId } }" on "${r}" to see the groups it offers now.`);let y=f.recipes.find(e=>e.key===l);if(!y)throw Error(`The recipe group "${n}" on "${r}" has no recipe with the key "${l}". Recipes and their keys change with the configuration and with the language. List the recipes of the group again and use a key it returns.`);let g=s(y,f,p.id,t,i);return{updates:g,readResult:e=>o(g,p.id,e).map(t=>i.domain.get$Entity(t,e.state))}}},{name:"replaceEntity",implementation:(e,t,i)=>{let{entityId:r,recipeGroupId:n,recipeKey:l}=g.parse(e),p=t.entities.find(e=>e.id===r);if(!p)throw Error(`Entity "${r}" does not exist, so it cannot be replaced. It may have been deleted or replaced by an earlier operation or field; a replaced entity gets a new id. Query the current entities and use an id they return.`);let h=a(i.manifest,"replace",p.type),u=h.find(e=>e.groupId===n);if(!u)throw Error(`Entity "${r}" is a ${p.type}, which has no replace recipe group "${n}". ${h.length>0?`Its replace recipe groups are: ${m(h.map(({groupId:e})=>e))}.`:`A ${p.type} cannot be replaced.`} Query "meta { replaceRecipes { groupId } }" on the entity you want to replace and use a groupId it returns.`);let f=d("replace",u,p.id,t,i);if(!f)throw Error(`The recipe group "${n}" is not available on "${r}" right now, so it cannot be replaced from it. The configurator offers a group only in some states of the configuration. Query "meta { replaceRecipes { groupId } }" on "${r}" to see the groups it offers now.`);let y=f.recipes.find(e=>e.key===l);if(!y)throw Error(`The recipe group "${n}" on "${r}" has no recipe with the key "${l}". Recipes and their keys change with the configuration and with the language. List the recipes of the group again and use a key it returns.`);let c=s(y,f,p.id,t,i);return{updates:c,readResult:e=>o(c,p.id,e).map(t=>i.domain.get$Entity(t,e.state))}}}];export const findAssistantMutation=(e,i)=>{let o,a,s=$.find(t=>t.name===e);if(s||!e.startsWith(u))return s;let d=e.slice(u.length),l=f(i.writableFields??{},d);return l&&(o=`${u}${d}`,a=Object.keys(l).join(", "),{name:o,implementation:(e,i,s)=>{let{manifest:p,domain:c}=s,{id:g,delta:m}=h.parse(e),$=i.entities.find(e=>e.id===g);if(!$)throw Error(`Entity "${g}" does not exist, so it cannot be modified. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);if($.type!==d)throw Error(`Entity "${g}" is a ${$.type}, but ${o} modifies only ${d} entities. ${f(p.writableFields??{},$.type)?`Use ${u}${$.type} for it instead.`:`${$.type} has no writable fields, so it cannot be modified; pass the id of a ${d}.`}`);let w=Object.entries(m).flatMap(([e,t])=>{let i=f(l,e);return void 0===i?[]:[{field:e,property:i,value:y(t)}]}),b=Object.fromEntries(w.map(({property:e,value:t})=>[e,t]));if(0===Object.keys(b).length)throw Error(`The delta of ${o} is empty, so there is nothing to change on "${g}". Set at least one of its fields: ${a}.`);let E=c.validateEntity({...$,...b});if(!E.success){let e=w.filter(({field:e,property:t})=>e!==t).map(({field:e,property:t})=>`${e} is stored as ${t}`);throw Error(`The delta would make "${g}" an invalid ${d}: ${E.errors.join("; ")}. ${e.length>0?`The messages name stored properties: ${e.join(", ")}. `:""}Nothing was changed. Send values that fit the types and the allowed values the schema describes for these fields.`)}let j=r(p,d);for(let{field:e,value:t}of w){let r=j.find(t=>t.field===e);if(!r?.validate||null===t)continue;let o=n(r,$.id,i,s);if(o&&!o.some(e=>e.value===t))throw Error(`${JSON.stringify(t)} is not a value "${e}" of "${g}" can take right now. ${o.length>0?`The configurator offers these values: ${o.map(e=>JSON.stringify(e.value)).join(", ")}.`:"The configurator offers no value for it in this state."} Nothing was changed. Send one of the offered values; "meta { ${r.edgeName} }" on the entity lists them with their names. When the values depend on another field of this delta, change that field in an earlier mutation field of the same operation.`)}return{updates:[t.DomainEntityModification({entityId:$.id,stateDelta:b,updateTag:"modifyEntity"})],readResult:({state:e})=>c.getEntity($.id,e)?c.get$Entity($.id,e):null}}})};
@@ -1,3 +1,3 @@
1
- export declare const cacheVersion = 756;
1
+ export declare const cacheVersion = 757;
2
2
  export declare const needsRebuild: (fileContents: string[], outputDirectory: string) => Promise<boolean>;
3
3
  export declare const writeCacheInfo: (fileContents: string[], outputDirectory: string) => Promise<void>;
@@ -1 +1 @@
1
- import{createHash as e}from"crypto";import{existsSync as r}from"fs";import{readFile as t}from"fs/promises";import{isEqualArray as o}from"@salsita-ai/common/utils";import{writeFormatted as i}from"../gen/write-formatted.js";export const cacheVersion=756;let s=r=>({version:756,files:r.map(r=>e("md5").update(r).digest("base64")).sort()});export const needsRebuild=async(e,i)=>{let a=`${i}/cache.json`;if(!r(a))return!0;try{let r=JSON.parse(await t(a,"utf-8")),i=s(e);return 756!==r.version||!o(r.files,i.files)}catch(e){return console.error("Failed to read cache file, forcing rebuild",e),!0}};export const writeCacheInfo=async(e,r)=>{let t=`${r}/cache.json`,o=s(e);await i(t,JSON.stringify(o,null,2))};
1
+ import{createHash as e}from"crypto";import{existsSync as r}from"fs";import{readFile as t}from"fs/promises";import{isEqualArray as o}from"@salsita-ai/common/utils";import{writeFormatted as i}from"../gen/write-formatted.js";export const cacheVersion=757;let s=r=>({version:757,files:r.map(r=>e("md5").update(r).digest("base64")).sort()});export const needsRebuild=async(e,i)=>{let a=`${i}/cache.json`;if(!r(a))return!0;try{let r=JSON.parse(await t(a,"utf-8")),i=s(e);return 757!==r.version||!o(r.files,i.files)}catch(e){return console.error("Failed to read cache file, forcing rebuild",e),!0}};export const writeCacheInfo=async(e,r)=>{let t=`${r}/cache.json`,o=s(e);await i(t,JSON.stringify(o,null,2))};
@@ -13,5 +13,7 @@ export interface DevCommandProps {
13
13
  readonly tui?: boolean;
14
14
  readonly serverUrl?: string;
15
15
  readonly developmentKey?: string;
16
+ /** Skips the asset upload of the start-up prepare; the re-prepare after a rebuild never uploads. */
17
+ readonly skipUpload: boolean;
16
18
  }
17
19
  export declare const runDevCommand: (props: DevCommandProps, context: CommandContext) => Promise<void>;
@@ -1,5 +1,5 @@
1
- import{format as e}from"node:util";import{createServer as t}from"vite";import{runBuildCommand as r,setLambdaLocalLogger as o,webhookLogContext as s}from"../../webhook-cli/index.js";import{startEditorServer as n}from"../editor-server/index.js";import{DomainSpecProjectWatcher as i,LinguiWatcher as a,LogBus as l,MockTemplateWatcher as c,PhoenixPubSub as p,WebhookTunnelMonitor as d,createBusLogger as u,getViteDevConfig as m,patchConsole as g,setViteLogSink as w}from"../services/index.js";import{prepareDevelopmentEnvironment as v}from"../services/prepare-development-environment.js";import{createWebhookTunnelTransport as h,readOrCreateTunnelSessionId as f,startWebhookService as E}from"../services/webhook-service/index.js";import{startTui as b}from"../tui/index.js";import{FileLogger as S,createLogger as I,exists as k}from"../utils/index.js";import{generateProjectFilesAndInstallDependencies as T}from"./generate-project-files.js";import{readGeneratedEnvMarkers as x}from"./generated-env-markers.js";export const runDevCommand=async(N,$)=>{let{logger:j}=$,{sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,editorWsPort:O,debug:L=!1,withLingui:V=!1,persistenceMode:M,force:U=!1,tui:W=!1,serverUrl:C,developmentKey:Y}=N,G=null,B=null,H=null,X=null,q=null,F=null,J=new S,K=new p,Q=new l,z=W&&!!process.stdout.isTTY&&!!process.stdin.isTTY,A=!z,Z=null;W&&!z&&j.warn("TUI requested but stdin/stdout is not an interactive terminal — falling back to plain log output. Run phoenix dev --tui directly in a terminal to use the TUI.");let ee=null,et=j,er=null,eo=()=>{Z&&(Z(),Z=null),ee&&(ee.unmount(),ee=null,et=I({debug:L,fileLogger:J}))},es=(e=0)=>er||(er=(async()=>{process.off("SIGINT",en),process.off("SIGTERM",en),process.off("uncaughtException",ei),eo(),et.debug("Shutting down...");let t=[];for(let e of[{name:"lingui watcher",close:()=>X?.close()},{name:"project watcher",close:()=>F?.close()},{name:"mock template watcher",close:()=>q?.close()},{name:"editor server",close:()=>H?.close()},{name:"vite server",close:()=>G?.close()},{name:"webhook tunnel",close:()=>B?.stop()}])try{et.debug(`Shutting down ${e.name}`),await e.close()}catch(r){t.push(`${e.name}: ${r instanceof Error?r.message:String(r)}`)}t.length>0&&et.warn(`Cleanup warnings:
2
- ${t.join("\n ")}`),et.debug("Shutdown complete"),await J.close(),process.exit(e)})()),en=()=>{es(0)},ei=e=>{eo(),et.error(`Uncaught exception: ${e.message}`),es(1)};process.once("SIGINT",en),process.once("SIGTERM",en),process.once("uncaughtException",ei);try{await J.init(".phoenix"),et=u({bus:Q,stream:"spec",debug:L,fileLogger:J,echo:!0}),w((e,t)=>Q.push("vite",e,t),{echo:A}),o({transports:[],log:(t,...r)=>{Q.push("webhook","warn"===t||"error"===t?t:"info",e(...r)),A&&process.stdout.write(`${e(t,...r)}
3
- `)}}),K.browserConsole$.subscribe(e=>{Q.push("browser",e.level,e.source?`[${e.source}] ${e.message}`:e.message);let t=`[${e.source?`browser:${e.source}`:"browser"}] ${e.message}`;J.write("warn",t),A&&process.stderr.write(`⚠️ ${t}
4
- `)}),A&&(Z=g(Q,{echo:!0})),process.env.NODE_ENV="development",M&&(process.env.PERSISTENCE_MODE=M);let l=!M||"server"===M,p=l&&C?new d(C):void 0;if(et.step("Starting development mode"),!await k("spec")){et.error('Spec folder not found. Run "phoenix init" first.'),await es(1);return}if(l){if(!C||!Y)throw Error("Server persistence needs SERVER_URL and DEVELOPMENT_KEY. Create a development environment in Studio and paste its .env block into .env.");let e=await x(".env.generated");e?.PHOENIX_PROJECT_SLUG!==D||e.PHOENIX_ENVIRONMENT_SLUG!==P||e.PHOENIX_SERVER_URL!==C?(et.step("Preparing development deployment"),await v({serverUrl:C,projectSlug:D,environmentSlug:P,developmentKey:Y,outFile:".env.generated",skipUpload:!1,overrideSchema:!0,debug:L,projectVersion:R},{logger:et})):et.debug(".env.generated matches the current development environment, skipping prepare")}et.step("Building project files");let{templateFiles:S}=await T({sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,withLingui:V,force:U},{logger:et});if(et.success("Project files built successfully"),z&&(et=u({bus:Q,stream:"spec",debug:L,fileLogger:J}),Z=g(Q),ee=b(Q,{onQuit:()=>void es(0)})),V?(X=new a({logger:et})).start():et.warn("Lingui is disabled: i18n messages are not extracted or compiled during dev. Pass --withLingui or set WITH_LINGUI=true to enable."),l&&(et.step("Building webhooks"),await s.run("webhook",async()=>{await r({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:void 0})})),l&&C&&Y){let e=await x(".env.generated");if(!e?.DEPLOYMENT_ID)throw Error("Webhook tunnel cannot start because .env.generated has no DEPLOYMENT_ID. Rerun phoenix dev to prepare the development deployment.");let t=await f();B=await E({experimental:!0,transport:h({serverUrl:C,developmentKey:Y,projectSlug:D,environmentSlug:P}),projectSlug:D,environmentSlug:P,deploymentId:e.DEPLOYMENT_ID,sessionId:t,onStatus:(r,o)=>{p?.setStatus(r,{deploymentId:e.DEPLOYMENT_ID,sessionId:t,message:o??null})},onRequest:e=>p?.record(e)}),p?.setStatus("waiting",{deploymentId:e.DEPLOYMENT_ID,sessionId:t}),B.stopped.catch(e=>{eo(),et.error(`Webhook tunnel failed: ${e instanceof Error?e.message:String(e)}`),es(1)}),et.success("Webhook tunnel started")}if(y&&O){et.step("Starting editor WebSocket server");let e=parseInt(O,10);H=n({port:e,projectRoot:process.cwd(),pubsub:K,logger:et,logBus:Q,tunnelMonitor:p,debug:L,prepareDeployment:l&&C&&Y?()=>v({serverUrl:C,projectSlug:D,environmentSlug:P,developmentKey:Y,outFile:".env.generated",skipUpload:!0,overrideSchema:!0,debug:!1,projectVersion:R},{logger:et}):void 0}),await H.ready,et.debug(`Editor WebSocket server started on port ${e}`),(q=new c({projectRoot:process.cwd(),pubsub:K,logger:et})).start()}let I=await m({templateFiles:S});if(G=await t(I),await G.listen(),et.step("Starting Vite dev server"),(F=new i({viteServer:G,sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,useServer:l,logger:et,onRebuilt:()=>X?.trigger(),onViteServerChange:e=>{G=e}})).start(),z)et.success("Vite dev server started — watching for changes"),y&&O&&et.info(`Editor WebSocket: ws://localhost:${O}`);else if(L)et.success("Vite dev server started");else{let e=e=>{Q.push("spec","info",e),process.stdout.write(`${e}
5
- `)};e("\n\uD83D\uDE80 Phoenix Dev Server\n"),y&&O&&e(`Editor WebSocket: ws://localhost:${O}`),e("\n\uD83D\uDC40 Watching for changes...\n")}}catch(e){eo(),et.error(`Dev mode failed: ${e instanceof Error?e.message:String(e)}`,e),await es(1)}};
1
+ import{format as e}from"node:util";import{createServer as t}from"vite";import{runBuildCommand as r,setLambdaLocalLogger as o,webhookLogContext as s}from"../../webhook-cli/index.js";import{startEditorServer as n}from"../editor-server/index.js";import{DomainSpecProjectWatcher as i,LinguiWatcher as a,LogBus as l,MockTemplateWatcher as c,PhoenixPubSub as p,WebhookTunnelMonitor as d,createBusLogger as u,getViteDevConfig as m,patchConsole as g,setViteLogSink as w}from"../services/index.js";import{prepareDevelopmentEnvironment as v}from"../services/prepare-development-environment.js";import{createWebhookTunnelTransport as h,readOrCreateTunnelSessionId as f,startWebhookService as E}from"../services/webhook-service/index.js";import{startTui as b}from"../tui/index.js";import{FileLogger as S,createLogger as I,exists as k}from"../utils/index.js";import{generateProjectFilesAndInstallDependencies as T}from"./generate-project-files.js";import{readGeneratedEnvMarkers as x}from"./generated-env-markers.js";export const runDevCommand=async(N,$)=>{let{logger:j}=$,{sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,editorWsPort:O,debug:L=!1,withLingui:V=!1,persistenceMode:M,force:U=!1,tui:W=!1,serverUrl:C,developmentKey:Y,skipUpload:G}=N,B=null,H=null,X=null,q=null,F=null,J=null,K=new S,Q=new p,z=new l,A=W&&!!process.stdout.isTTY&&!!process.stdin.isTTY,Z=!A,ee=null;W&&!A&&j.warn("TUI requested but stdin/stdout is not an interactive terminal — falling back to plain log output. Run phoenix dev --tui directly in a terminal to use the TUI.");let et=null,er=j,eo=null,es=()=>{ee&&(ee(),ee=null),et&&(et.unmount(),et=null,er=I({debug:L,fileLogger:K}))},en=(e=0)=>eo||(eo=(async()=>{process.off("SIGINT",ei),process.off("SIGTERM",ei),process.off("uncaughtException",ea),es(),er.debug("Shutting down...");let t=[];for(let e of[{name:"lingui watcher",close:()=>q?.close()},{name:"project watcher",close:()=>J?.close()},{name:"mock template watcher",close:()=>F?.close()},{name:"editor server",close:()=>X?.close()},{name:"vite server",close:()=>B?.close()},{name:"webhook tunnel",close:()=>H?.stop()}])try{er.debug(`Shutting down ${e.name}`),await e.close()}catch(r){t.push(`${e.name}: ${r instanceof Error?r.message:String(r)}`)}t.length>0&&er.warn(`Cleanup warnings:
2
+ ${t.join("\n ")}`),er.debug("Shutdown complete"),await K.close(),process.exit(e)})()),ei=()=>{en(0)},ea=e=>{es(),er.error(`Uncaught exception: ${e.message}`),en(1)};process.once("SIGINT",ei),process.once("SIGTERM",ei),process.once("uncaughtException",ea);try{await K.init(".phoenix"),er=u({bus:z,stream:"spec",debug:L,fileLogger:K,echo:!0}),w((e,t)=>z.push("vite",e,t),{echo:Z}),o({transports:[],log:(t,...r)=>{z.push("webhook","warn"===t||"error"===t?t:"info",e(...r)),Z&&process.stdout.write(`${e(t,...r)}
3
+ `)}}),Q.browserConsole$.subscribe(e=>{z.push("browser",e.level,e.source?`[${e.source}] ${e.message}`:e.message);let t=`[${e.source?`browser:${e.source}`:"browser"}] ${e.message}`;K.write("warn",t),Z&&process.stderr.write(`⚠️ ${t}
4
+ `)}),Z&&(ee=g(z,{echo:!0})),process.env.NODE_ENV="development",M&&(process.env.PERSISTENCE_MODE=M);let l=!M||"server"===M,p=l&&C?new d(C):void 0;if(er.step("Starting development mode"),!await k("spec")){er.error('Spec folder not found. Run "phoenix init" first.'),await en(1);return}if(l){if(!C||!Y)throw Error("Server persistence needs SERVER_URL and DEVELOPMENT_KEY. Create a development environment in Studio and paste its .env block into .env.");let e=await x(".env.generated");e?.PHOENIX_PROJECT_SLUG!==D||e.PHOENIX_ENVIRONMENT_SLUG!==P||e.PHOENIX_SERVER_URL!==C?(er.step("Preparing development deployment"),await v({serverUrl:C,projectSlug:D,environmentSlug:P,developmentKey:Y,outFile:".env.generated",skipUpload:G,overrideSchema:!0,debug:L,projectVersion:R},{logger:er})):er.debug(".env.generated matches the current development environment, skipping prepare")}er.step("Building project files");let{templateFiles:S}=await T({sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,withLingui:V,force:U},{logger:er});if(er.success("Project files built successfully"),A&&(er=u({bus:z,stream:"spec",debug:L,fileLogger:K}),ee=g(z),et=b(z,{onQuit:()=>void en(0)})),V?(q=new a({logger:er})).start():er.warn("Lingui is disabled: i18n messages are not extracted or compiled during dev. Pass --withLingui or set WITH_LINGUI=true to enable."),l&&(er.step("Building webhooks"),await s.run("webhook",async()=>{await r({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:void 0})})),l&&C&&Y){let e=await x(".env.generated");if(!e?.DEPLOYMENT_ID)throw Error("Webhook tunnel cannot start because .env.generated has no DEPLOYMENT_ID. Rerun phoenix dev to prepare the development deployment.");let t=await f();H=await E({experimental:!0,transport:h({serverUrl:C,developmentKey:Y,projectSlug:D,environmentSlug:P}),projectSlug:D,environmentSlug:P,deploymentId:e.DEPLOYMENT_ID,sessionId:t,onStatus:(r,o)=>{p?.setStatus(r,{deploymentId:e.DEPLOYMENT_ID,sessionId:t,message:o??null})},onRequest:e=>p?.record(e)}),p?.setStatus("waiting",{deploymentId:e.DEPLOYMENT_ID,sessionId:t}),H.stopped.catch(e=>{es(),er.error(`Webhook tunnel failed: ${e instanceof Error?e.message:String(e)}`),en(1)}),er.success("Webhook tunnel started")}if(y&&O){er.step("Starting editor WebSocket server");let e=parseInt(O,10);X=n({port:e,projectRoot:process.cwd(),pubsub:Q,logger:er,logBus:z,tunnelMonitor:p,debug:L,prepareDeployment:l&&C&&Y?()=>v({serverUrl:C,projectSlug:D,environmentSlug:P,developmentKey:Y,outFile:".env.generated",skipUpload:!0,overrideSchema:!0,debug:!1,projectVersion:R},{logger:er}):void 0}),await X.ready,er.debug(`Editor WebSocket server started on port ${e}`),(F=new c({projectRoot:process.cwd(),pubsub:Q,logger:er})).start()}let I=await m({templateFiles:S});if(B=await t(I),await B.listen(),er.step("Starting Vite dev server"),(J=new i({viteServer:B,sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,useServer:l,logger:er,onRebuilt:()=>q?.trigger(),onViteServerChange:e=>{B=e}})).start(),A)er.success("Vite dev server started — watching for changes"),y&&O&&er.info(`Editor WebSocket: ws://localhost:${O}`);else if(L)er.success("Vite dev server started");else{let e=e=>{z.push("spec","info",e),process.stdout.write(`${e}
5
+ `)};e("\n\uD83D\uDE80 Phoenix Dev Server\n"),y&&O&&e(`Editor WebSocket: ws://localhost:${O}`),e("\n\uD83D\uDC40 Watching for changes...\n")}}catch(e){es(),er.error(`Dev mode failed: ${e instanceof Error?e.message:String(e)}`,e),await en(1)}};
@@ -1 +1 @@
1
- export declare const envExampleFile = "# This file documents developer-supplied Phoenix variables. Copy the values you\n# need into an untracked .env; never commit .env.\n# phoenix dev, deployment:prepare-dev, and deployment:prepare-local write\n# server-generated values to .env.generated; do not maintain them here.\n\n# ============================================================================\n# Development environment (phoenix dev and deployment:prepare-dev)\n# ============================================================================\n# Create a development environment in PHX Studio and paste its block here.\n#\n# SERVER_URL=http://localhost:3000\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<development-environment-slug>\n# DEVELOPMENT_KEY=<development-key>\n\n# ============================================================================\n# Shared-server access (deployment:prepare-local and CI commands only)\n# ============================================================================\n# Ask DevOps for these values when using the legacy prepare-local or CI flows.\n# SERVER_URL=https://phoenix.example.com\n# ENVIRONMENT_API_KEY=<shared-server-api-key>\n# PROJECT_KEY=<shared-server-project-key>\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<environment-slug>\n# LAMBDA_URL=http://localhost:8080\n\n# ============================================================================\n# Dev Configuration (phoenix dev)\n# ============================================================================\n# Override these to run multiple projects simultaneously.\n# Ports auto-increment if occupied, but setting explicit values avoids surprises.\n#\n# EDITOR_WS_PORT=3020\n# ENABLE_EDITOR=true\n# Enable Lingui extraction and compilation during dev. Phoenix warns when this is disabled.\n# WITH_LINGUI=false\n# DEBUG=false\n# FORCE_REBUILD=false\n# USE_APPLICATION_SPEC=false\n# IS_DEV=true\n#\n# Persistence mode controls how configurator state is stored.\n# Options: 'server' (default), 'local-storage', 'memory'\n# PERSISTENCE_MODE=server\n\n# deployment:prepare-dev and deployment:prepare-local output and behavior overrides:\n# OUT_FILE=.env.generated\n# SKIP_UPLOAD=false\n# OVERRIDE_SCHEMA=true\n\n# ============================================================================\n# Project-Specific Environment Variables\n# ============================================================================\n# Additional environment variables can be defined in spec/application.yaml\n# under the 'env.frontend' and 'env.webhook' sections.\n#\n# These are useful for project-specific needs such as:\n# - Third-party API keys (e.g., salesforce)\n# - External service URLs\n# - Feature flags\n# - Custom configuration values\n#\n# Example in spec/application.yaml:\n# env:\n# frontend:\n# SALESFORCE_CLIENT_ID:\n# type: str\n# devDefault: pk_test_xxx\n# webhook:\n# SALESFORCE_CLIENT_SECRET:\n# type: str\n# SALESFORCE_REDIRECT_URI:\n# type: str\n#\n# These will be automatically validated and available in your code via\n# the generated frontend.config.ts and webhooks.config.ts files.\n#\n# IMPORTANT: If you add required custom environment variables (without defaults),\n# remember to also add them to .env.ci with mock values so CI builds can succeed.\n\n# ============================================================================\n# Generated environment\n# ============================================================================\n# Deployment variables (DEPLOYMENT_ID, RESOURCES_URL, and related values)\n# are auto-generated by the PHX server and written to .env.generated when you run\n# phoenix dev, deployment:prepare-dev, or deployment:prepare-local. Development\n# environment settings can be managed via PHX Studio.\n";
1
+ export declare const envExampleFile = "# This file documents developer-supplied Phoenix variables. Copy the values you\n# need into an untracked .env; never commit .env.\n# phoenix dev, deployment:prepare-dev, and deployment:prepare-local write\n# server-generated values to .env.generated; do not maintain them here.\n\n# ============================================================================\n# Development environment (phoenix dev and deployment:prepare-dev)\n# ============================================================================\n# Create a development environment in PHX Studio and paste its block here.\n#\n# SERVER_URL=http://localhost:3000\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<development-environment-slug>\n# DEVELOPMENT_KEY=<development-key>\n\n# ============================================================================\n# Shared-server access (deployment:prepare-local and CI commands only)\n# ============================================================================\n# Ask DevOps for these values when using the legacy prepare-local or CI flows.\n# SERVER_URL=https://phoenix.example.com\n# ENVIRONMENT_API_KEY=<shared-server-api-key>\n# PROJECT_KEY=<shared-server-project-key>\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<environment-slug>\n# LAMBDA_URL=http://localhost:8080\n\n# ============================================================================\n# Dev Configuration (phoenix dev)\n# ============================================================================\n# Override these to run multiple projects simultaneously.\n# Ports auto-increment if occupied, but setting explicit values avoids surprises.\n#\n# EDITOR_WS_PORT=3020\n# ENABLE_EDITOR=true\n# Enable Lingui extraction and compilation during dev. Phoenix warns when this is disabled.\n# WITH_LINGUI=false\n# DEBUG=false\n# FORCE_REBUILD=false\n# USE_APPLICATION_SPEC=false\n# IS_DEV=true\n#\n# Persistence mode controls how configurator state is stored.\n# Options: 'server' (default), 'local-storage', 'memory'\n# PERSISTENCE_MODE=server\n\n# deployment:prepare-dev and deployment:prepare-local output and behavior overrides:\n# OUT_FILE=.env.generated\n# SKIP_UPLOAD also applies to the deployment phoenix dev prepares at startup.\n# SKIP_UPLOAD=false\n# OVERRIDE_SCHEMA=true\n\n# ============================================================================\n# Project-Specific Environment Variables\n# ============================================================================\n# Additional environment variables can be defined in spec/application.yaml\n# under the 'env.frontend' and 'env.webhook' sections.\n#\n# These are useful for project-specific needs such as:\n# - Third-party API keys (e.g., salesforce)\n# - External service URLs\n# - Feature flags\n# - Custom configuration values\n#\n# Example in spec/application.yaml:\n# env:\n# frontend:\n# SALESFORCE_CLIENT_ID:\n# type: str\n# devDefault: pk_test_xxx\n# webhook:\n# SALESFORCE_CLIENT_SECRET:\n# type: str\n# SALESFORCE_REDIRECT_URI:\n# type: str\n#\n# These will be automatically validated and available in your code via\n# the generated frontend.config.ts and webhooks.config.ts files.\n#\n# IMPORTANT: If you add required custom environment variables (without defaults),\n# remember to also add them to .env.ci with mock values so CI builds can succeed.\n\n# ============================================================================\n# Generated environment\n# ============================================================================\n# Deployment variables (DEPLOYMENT_ID, RESOURCES_URL, and related values)\n# are auto-generated by the PHX server and written to .env.generated when you run\n# phoenix dev, deployment:prepare-dev, or deployment:prepare-local. Development\n# environment settings can be managed via PHX Studio.\n";
@@ -45,6 +45,7 @@ export const envExampleFile=`# This file documents developer-supplied Phoenix va
45
45
 
46
46
  # deployment:prepare-dev and deployment:prepare-local output and behavior overrides:
47
47
  # OUT_FILE=.env.generated
48
+ # SKIP_UPLOAD also applies to the deployment phoenix dev prepares at startup.
48
49
  # SKIP_UPLOAD=false
49
50
  # OVERRIDE_SCHEMA=true
50
51
 
@@ -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."],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. 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 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.","- 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. 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)?[a]:[],.../^\s+replaceEntity\(/m.test(h.sdl)?[n]:[],.../^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."],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,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 R}from"./application-spec/read-spec-project.js";import{prepareDevelopmentEnvironment as h,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 X,runStoryCommand as $,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}}};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(),h=el(t.applicationSpec,m.applicationFlow,{logger:n}),S=t.local??i.PHOENIX_LOCAL,_=t.projectSlug??i.PROJECT_SLUG,U=E&&h&&!S&&!_?.length?await R(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)},()=>h,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,"")},()=>h,()=>{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};if(h){let e=P?{developmentKey:P}:b?{apiToken:b}:void 0;await k({...N,credential:e,skipUpload:t.skipUpload??i.SKIP_UPLOAD},{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=>$(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 X({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;await B({customer:e.customer,serverUrl:e.serverUrl??et(i),studioUrl:e.studioUrl??ei(i,e.customer),open:e.open},{logger:ea()})}).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;await T({serverUrl:e.serverUrl??et(i),sdkVersion:ed.version,wait:e.wait,projectDir:process.cwd(),pollIntervalMs:3e3},{logger:ea()})}).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;await F({serverUrl:e.serverUrl??et(i)},{logger:ea()})}).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 R(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.")});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})}).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 h({...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 R}from"./application-spec/read-spec-project.js";import{prepareDevelopmentEnvironment as h,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 X,runStoryCommand as $,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}}};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(),h=el(t.applicationSpec,m.applicationFlow,{logger:n}),S=t.local??i.PHOENIX_LOCAL,_=t.projectSlug??i.PROJECT_SLUG,U=E&&h&&!S&&!_?.length?await R(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)},()=>h,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,"")},()=>h,()=>{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(h){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=>$(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 X({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;await B({customer:e.customer,serverUrl:e.serverUrl??et(i),studioUrl:e.studioUrl??ei(i,e.customer),open:e.open},{logger:ea()})}).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;await T({serverUrl:e.serverUrl??et(i),sdkVersion:ed.version,wait:e.wait,projectDir:process.cwd(),pollIntervalMs:3e3},{logger:ea()})}).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;await F({serverUrl:e.serverUrl??et(i)},{logger:ea()})}).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 R(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.")});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})}).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 h({...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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salsita-ai/sdk",
3
- "version": "0.49.0-develop.f5fc5cfc25",
3
+ "version": "0.49.0-develop.fc391028c9",
4
4
  "description": "TypeScript SDK and CLI for building, running, and deploying Phoenix configurator applications.",
5
5
  "keywords": [
6
6
  "salsita",
@@ -295,8 +295,8 @@
295
295
  "yaml": "2.9.0",
296
296
  "yargs": "17.7.2",
297
297
  "zod": "3.25.76",
298
- "@salsita-ai/common": "0.49.0-develop.f5fc5cfc25",
299
- "@salsita-ai/contracts": "0.49.0-develop.f5fc5cfc25"
298
+ "@salsita-ai/common": "0.49.0-develop.fc391028c9",
299
+ "@salsita-ai/contracts": "0.49.0-develop.fc391028c9"
300
300
  },
301
301
  "devDependencies": {
302
302
  "@clerk/clerk-react": "5.61.8",