@salsita-ai/sdk 0.49.0-develop.d4bea2382c → 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 (38) hide show
  1. package/dist/application-spec/generate-application/code/templates/env-example.js +1 -0
  2. package/dist/application-spec/generate-application/code/templates/phoenix-skill.js +1 -1
  3. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.d.ts +6 -3
  4. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.js +1 -1
  5. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.js +1 -1
  6. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
  7. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +32 -32
  8. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
  9. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
  10. package/dist/docs/index.json +1 -1
  11. package/dist/docs/phoenix/csp.mdx +6 -2
  12. package/dist/docs/phoenix/phoenix-cli.mdx +19 -17
  13. package/dist/docs/phoenix/sdk-builder-workflow.mdx +9 -5
  14. package/dist/domain/application/application-config.d.ts +3 -1
  15. package/dist/domain/application/assistant-mutations.d.ts +1 -1
  16. package/dist/domain/application/assistant-mutations.js +1 -1
  17. package/dist/legacy/domain-cli/utils/cache.d.ts +1 -1
  18. package/dist/legacy/domain-cli/utils/cache.js +1 -1
  19. package/dist/legacy/phoenix-cli/commands/dev.d.ts +2 -0
  20. package/dist/legacy/phoenix-cli/commands/dev.js +5 -5
  21. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/env-example.d.ts +1 -1
  22. package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/env-example.js +1 -0
  23. package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
  24. package/dist/phoenix/application-spec/project-files.js +1 -1
  25. package/dist/phoenix/cli.js +1 -1
  26. package/dist/phoenix/commands/deploy.js +2 -2
  27. package/dist/phoenix/commands/dev.js +4 -4
  28. package/dist/phoenix/commands/init.d.ts +2 -1
  29. package/dist/phoenix/commands/init.js +1 -1
  30. package/dist/phoenix/commands/login.js +2 -2
  31. package/dist/phoenix/commands/sync.js +1 -1
  32. package/dist/phoenix/services/cli-credentials.d.ts +3 -0
  33. package/dist/phoenix/services/cli-credentials.js +1 -1
  34. package/dist/phoenix/utils/index.d.ts +1 -1
  35. package/dist/phoenix/utils/index.js +1 -1
  36. package/dist/phoenix/utils/package-info.d.ts +9 -0
  37. package/dist/phoenix/utils/package-info.js +1 -1
  38. package/package.json +3 -3
@@ -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 +1 @@
1
- import{globby as s}from"globby";import e from"picomatch";export const SPEC_FILE_PATTERN="spec/**/*.yaml";export const PARSED_TEXT_FILE_PATTERNS=["spec/**/*.yaml","src/**/*.{ts,tsx}","mocks/**/*.{yaml,yml}",".gitignore",".cursor/rules/phoenix.mdc","CLAUDE.md","package.json","assets/chat/embeddings.csv","assets/chat/chat.yaml"];export const PARSED_ASSET_FILE_PATTERNS=["assets/private/**","assets/public/**"];let o=[...PARSED_TEXT_FILE_PATTERNS,...PARSED_ASSET_FILE_PATTERNS,"src/**","mocks/**","assets/**","public/**","templates/**","pnpm-lock.yaml"],t=["**/node_modules/**","**/.phoenix/**","**/__generated/**","**/.DS_Store","**/._*","**/.env","**/.env.*"],c=e(o,{dot:!0,ignore:t});export const isProjectFile=s=>c(s);export const listProjectEntries=async e=>(await s(o,{cwd:e,dot:!0,ignore:t,onlyFiles:!1,followSymbolicLinks:!1})).sort();
1
+ import{globby as s}from"globby";import e from"picomatch";export const SPEC_FILE_PATTERN="spec/**/*.yaml";export const PARSED_TEXT_FILE_PATTERNS=["spec/**/*.yaml","src/**/*.{ts,tsx}","mocks/**/*.{yaml,yml}",".gitignore",".cursor/rules/phoenix.mdc","CLAUDE.md","package.json","assets/chat/embeddings.csv","assets/chat/chat.yaml"];export const PARSED_ASSET_FILE_PATTERNS=["assets/private/**","assets/public/**"];let o=[...PARSED_TEXT_FILE_PATTERNS,...PARSED_ASSET_FILE_PATTERNS,"src/**","mocks/**","assets/**","public/**","templates/**","pnpm-lock.yaml","pnpm-workspace.yaml"],t=["**/node_modules/**","**/.phoenix/**","**/__generated/**","**/.DS_Store","**/._*","**/.env","**/.env.*"],c=e(o,{dot:!0,ignore:t});export const isProjectFile=s=>c(s);export const listProjectEntries=async e=>(await s(o,{cwd:e,dot:!0,ignore:t,onlyFiles:!1,followSymbolicLinks:!1})).sort();
@@ -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, and a starter spec. 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();
@@ -1,4 +1,4 @@
1
- import{openAsBlob as e}from"node:fs";import{createApiBaseClient as t}from"#package/client";import{resolveApplicationSpecDeploymentData as i}from"../application-spec/index.js";import{createSourceArchive as r,getServerCredentials as a}from"../services/index.js";let o={queued:"Waiting for a build runner",preparing:"Preparing the deployment",building:"Building the project",deploying:"Deploying the frontend, webhooks and assets",live:"Live",failed:"Failed",cancelled:"Cancelled"},s=e=>new Promise(t=>setTimeout(t,e)),l=async(t,i)=>{let r=new FormData;for(let[e,i]of Object.entries(t.fields))r.append(e,i);r.append("file",await e(i,{type:"application/gzip"}),"sources.tgz");let a=await fetch(t.url,{method:"POST",body:r});if(!a.ok)throw Error(`Uploading the sources failed with HTTP ${a.status}: ${await a.text()}`)};export const runDeployCommand=async(e,{logger:n})=>{let d=await a(e.serverUrl),{pollIntervalMs:p}=e;if(!d)throw Error(`You are not signed in to ${e.serverUrl}. Run \`phoenix login <workspace>\` first.`);let u=t(e.serverUrl),c={authorization:`Bearer ${d.token}`};n.step("Validating the application spec");let f=await i({skipUpload:!0,logger:n});n.success(`The spec is valid (application version ${f.applicationVersion})`),n.step(`Packing the project for ${d.customerName}`);let h=await r(e.projectDir);try{let t;n.info(` ${h.fileCount} files, ${(t=h.size)<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}`);let i=await u.POST("/deployments/builds",{body:{sdkVersion:e.sdkVersion,sizeBytes:h.size},headers:c});if(i.error||!i.data)throw Error(`The server did not create a build: ${i.error?.message??"no response"}`);let{buildId:r,upload:a}=i.data;n.step("Uploading the sources"),await l(a,h.path);let d=await u.POST("/deployments/builds/{buildId}/start",{params:{path:{buildId:r}},headers:{...c,"content-type":null}});if(d.error)throw Error(`The server did not start the build: ${d.error.message}`);if(d.data?.status==="failed")throw Error(`Build ${r} could not be started: ${d.data.error??"the server gave no reason"}`);if(n.success(`Build ${r} started`),!e.wait)return;let f=null,m=0;for(;;){let{data:e,error:t}=await u.GET("/deployments/builds/{buildId}",{params:{path:{buildId:r}},headers:c}).catch(e=>({data:void 0,error:{message:String(e)}}));if(t||!e){if((m+=1)>=5)throw Error(`Following build ${r} failed: ${t?.message??"no response"}. The build may still finish; check Deployments in Studio.`);await s(p);continue}if(m=0,e.status!==f&&(f=e.status,n.step(o[e.status])),"live"===e.status)return void n.success(`Your configurator is live at ${e.configuratorUrl}`);if("failed"===e.status||"cancelled"===e.status||e.timedOut){let t=await u.GET("/deployments/builds/{buildId}/log",{params:{path:{buildId:r}},headers:c}).catch(()=>({data:void 0})),i=(t.data?.log??"").trim().split("\n").slice(-40).join("\n");i&&n.info(`
1
+ import{openAsBlob as e}from"node:fs";import{createApiBaseClient as t}from"#package/client";import{resolveApplicationSpecDeploymentData as i}from"../application-spec/index.js";import{createSourceArchive as r,getServerCredentials as o}from"../services/index.js";import{ensureWorkspaceInstallSettings as a}from"../utils/index.js";let s={queued:"Waiting for a build runner",preparing:"Preparing the deployment",building:"Building the project",deploying:"Deploying the frontend, webhooks and assets",live:"Live",failed:"Failed",cancelled:"Cancelled"},l=e=>new Promise(t=>setTimeout(t,e)),n=async(t,i)=>{let r=new FormData;for(let[e,i]of Object.entries(t.fields))r.append(e,i);r.append("file",await e(i,{type:"application/gzip"}),"sources.tgz");let o=await fetch(t.url,{method:"POST",body:r});if(!o.ok)throw Error(`Uploading the sources failed with HTTP ${o.status}: ${await o.text()}`)};export const runDeployCommand=async(e,{logger:d})=>{let u=await o(e.serverUrl),{pollIntervalMs:p}=e;if(!u)throw Error(`You are not signed in to ${e.serverUrl}. Run \`phoenix login <workspace>\` first.`);let c=t(e.serverUrl),f={authorization:`Bearer ${u.token}`};d.step("Validating the application spec");let h=await i({skipUpload:!0,logger:d});d.success(`The spec is valid (application version ${h.applicationVersion})`),d.step(`Packing the project for ${u.customerName}`),a(e.projectDir);let m=await r(e.projectDir);try{let t;d.info(` ${m.fileCount} files, ${(t=m.size)<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}`);let i=await c.POST("/deployments/builds",{body:{sdkVersion:e.sdkVersion,sizeBytes:m.size},headers:f});if(i.error||!i.data)throw Error(`The server did not create a build: ${i.error?.message??"no response"}`);let{buildId:r,upload:o}=i.data;d.step("Uploading the sources"),await n(o,m.path);let a=await c.POST("/deployments/builds/{buildId}/start",{params:{path:{buildId:r}},headers:{...f,"content-type":null}});if(a.error)throw Error(`The server did not start the build: ${a.error.message}`);if(a.data?.status==="failed")throw Error(`Build ${r} could not be started: ${a.data.error??"the server gave no reason"}`);if(d.success(`Build ${r} started`),u.studioUrl){let e=new URL(`/builder/deployments/${r}`,u.studioUrl);e.searchParams.set("customer",u.customerSlug),d.info(`Follow the build in Studio: ${e.toString()}`)}if(!e.wait)return;let h=null,g=0;for(;;){let{data:e,error:t}=await c.GET("/deployments/builds/{buildId}",{params:{path:{buildId:r}},headers:f}).catch(e=>({data:void 0,error:{message:String(e)}}));if(t||!e){if((g+=1)>=5)throw Error(`Following build ${r} failed: ${t?.message??"no response"}. The build may still finish; check Deployments in Studio.`);await l(p);continue}if(g=0,e.status!==h&&(h=e.status,d.step(s[e.status])),"live"===e.status)return void d.success(`Your configurator is live at ${e.configuratorUrl}`);if("failed"===e.status||"cancelled"===e.status||e.timedOut){let t=await c.GET("/deployments/builds/{buildId}/log",{params:{path:{buildId:r}},headers:f}).catch(()=>({data:void 0})),i=(t.data?.log??"").trim().split("\n").slice(-40).join("\n");i&&d.info(`
2
2
  Last lines of the build log:
3
3
  ${i}
4
- `);let a=e.timedOut?"it took too long":e.error??"see the build log";throw Error(`Build ${r} did not go live: ${a}`)}await s(p)}}finally{await h.cleanup()}};
4
+ `);let o=e.timedOut?"it took too long":e.error??"see the build log";throw Error(`Build ${r} did not go live: ${o}`)}await l(p)}}finally{await m.cleanup()}};
@@ -1,5 +1,5 @@
1
- import{format as e}from"node:util";import{createServer as t}from"vite";import{startEditorServer as r}from"../editor-server/index.js";import{getDevelopmentCredentialHint as o}from"../services/development-credential.js";import{ApplicationSpecProjectWatcher as n,LinguiWatcher as s,LogBus as i,MockTemplateWatcher as a,PhoenixPubSub as l,WebhookTunnelMonitor as c,createBusLogger as p,getViteDevConfig as d,patchConsole as u,setViteLogSink as m}from"../services/index.js";import{prepareDevelopmentEnvironment as g}from"../services/prepare-development-environment.js";import{createWebhookTunnelTransport as w,readOrCreateTunnelSessionId as v,startWebhookService as h}from"../services/webhook-service/index.js";import{startTui as f}from"../tui/index.js";import{FileLogger as E,createLogger as b,exists as S}from"../utils/index.js";import{buildWebhooks as I,setLogger as k,webhookLogContext as x}from"../webhooks/index.js";import{generateProjectFilesAndInstallDependencies as j}from"./generate-project-files.js";import{readGeneratedEnvMarkers as T}from"./generated-env-markers.js";export const runDevCommand=async($,N)=>{let{logger:D}=N,{sdkVersion:R,projectSlug:y,environmentSlug:P,cliUseWorkspace:_,enableEditor:O,editorWsPort:L,debug:M=!1,withLingui:V=!1,persistenceMode:W,force:U=!1,tui:G=!1,serverUrl:Y,credential:C,skipUpload:H}=$,B=null,X=null,q=null,F=null,J=null,Q=null,z=new E,A=new l,K=new i,Z=G&&!!process.stdout.isTTY&&!!process.stdin.isTTY,ee=!Z,et=null;G&&!Z&&D.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 er=null,eo=D,en=null,es=()=>{et&&(et(),et=null),er&&(er.unmount(),er=null,eo=b({debug:M,fileLogger:z}))},ei=(e=0)=>en||(en=(async()=>{process.off("SIGINT",ea),process.off("SIGTERM",ea),process.off("uncaughtException",el),es(),eo.debug("Shutting down...");let t=[];for(let e of[{name:"lingui watcher",close:()=>F?.close()},{name:"project watcher",close:()=>Q?.close()},{name:"mock template watcher",close:()=>J?.close()},{name:"editor server",close:()=>q?.close()},{name:"vite server",close:()=>B?.close()},{name:"webhook tunnel",close:()=>X?.stop()}])try{eo.debug(`Shutting down ${e.name}`),await e.close()}catch(r){t.push(`${e.name}: ${r instanceof Error?r.message:String(r)}`)}t.length>0&&eo.warn(`Cleanup warnings:
2
- ${t.join("\n ")}`),eo.debug("Shutdown complete"),await z.close(),process.exit(e)})()),ea=()=>{ei(0)},el=e=>{es(),eo.error(`Uncaught exception: ${e.message}`),ei(1)};process.once("SIGINT",ea),process.once("SIGTERM",ea),process.once("uncaughtException",el);try{await z.init(".phoenix"),eo=p({bus:K,stream:"spec",debug:M,fileLogger:z,echo:!0}),m((e,t)=>K.push("vite",e,t),{echo:ee}),k({transports:[],log:(t,...r)=>{K.push("webhook","warn"===t||"error"===t?t:"info",e(...r)),ee&&process.stdout.write(`${e(t,...r)}
1
+ import{format as e}from"node:util";import{createServer as t}from"vite";import{startEditorServer as r}from"../editor-server/index.js";import{getDevelopmentCredentialHint as o}from"../services/development-credential.js";import{ApplicationSpecProjectWatcher as n,LinguiWatcher as s,LogBus as i,MockTemplateWatcher as a,PhoenixPubSub as l,WebhookTunnelMonitor as c,createBusLogger as p,getViteDevConfig as d,patchConsole as u,setViteLogSink as m}from"../services/index.js";import{prepareDevelopmentEnvironment as g}from"../services/prepare-development-environment.js";import{createWebhookTunnelTransport as w,readOrCreateTunnelSessionId as v,startWebhookService as h}from"../services/webhook-service/index.js";import{startTui as f}from"../tui/index.js";import{FileLogger as E,createLogger as b,exists as S}from"../utils/index.js";import{buildWebhooks as I,setLogger as k,webhookLogContext as $}from"../webhooks/index.js";import{generateProjectFilesAndInstallDependencies as x}from"./generate-project-files.js";import{readGeneratedEnvMarkers as j}from"./generated-env-markers.js";export const runDevCommand=async(T,P)=>{let{logger:R}=P,{sdkVersion:N,projectSlug:D,environmentSlug:y,cliUseWorkspace:_,enableEditor:O,editorWsPort:L,debug:U=!1,withLingui:V=!1,persistenceMode:M,force:W=!1,tui:G=!1,serverUrl:Y,credential:C,skipUpload:H}=T,B=null,X=null,q=null,F=null,J=null,Q=null,z=new E,A=new l,K=new i,Z=G&&!!process.stdout.isTTY&&!!process.stdin.isTTY,ee=!Z,et=null;G&&!Z&&R.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 er=null,eo=R,en=null,es=()=>{et&&(et(),et=null),er&&(er.unmount(),er=null,eo=b({debug:U,fileLogger:z}))},ei=(e=0)=>en||(en=(async()=>{process.off("SIGINT",ea),process.off("SIGTERM",ea),process.off("uncaughtException",el),es(),eo.debug("Shutting down...");let t=[];for(let e of[{name:"lingui watcher",close:()=>F?.close()},{name:"project watcher",close:()=>Q?.close()},{name:"mock template watcher",close:()=>J?.close()},{name:"editor server",close:()=>q?.close()},{name:"vite server",close:()=>B?.close()},{name:"webhook tunnel",close:()=>X?.stop()}])try{eo.debug(`Shutting down ${e.name}`),await e.close()}catch(r){t.push(`${e.name}: ${r instanceof Error?r.message:String(r)}`)}t.length>0&&eo.warn(`Cleanup warnings:
2
+ ${t.join("\n ")}`),eo.debug("Shutdown complete"),await z.close(),process.exit(e)})()),ea=()=>{ei(0)},el=e=>{es(),eo.error(`Uncaught exception: ${e.message}`),ei(1)};process.once("SIGINT",ea),process.once("SIGTERM",ea),process.once("uncaughtException",el);try{await z.init(".phoenix"),eo=p({bus:K,stream:"spec",debug:U,fileLogger:z,echo:!0}),m((e,t)=>K.push("vite",e,t),{echo:ee}),k({transports:[],log:(t,...r)=>{K.push("webhook","warn"===t||"error"===t?t:"info",e(...r)),ee&&process.stdout.write(`${e(t,...r)}
3
3
  `)}}),A.browserConsole$.subscribe(e=>{K.push("browser",e.level,e.source?`[${e.source}] ${e.message}`:e.message);let t=`[${e.source?`browser:${e.source}`:"browser"}] ${e.message}`;z.write("warn",t),ee&&process.stderr.write(`⚠️ ${t}
4
- `)}),ee&&(et=u(K,{echo:!0})),process.env.NODE_ENV="development",W&&(process.env.PERSISTENCE_MODE=W);let i=!W||"server"===W,l=i&&Y?new c(Y):void 0;if(eo.step("Starting development mode"),!await S("spec")){eo.error('Spec folder not found. Run "phoenix init" first.'),await ei(1);return}if(i){if(!Y||!C)throw Error("Server persistence needs a server and a credential. Run `phoenix login <workspace>`, or create a development environment in Studio and paste its .env block into .env.");let e=await T(".env.generated");e?.PHOENIX_PROJECT_SLUG!==y||e.PHOENIX_ENVIRONMENT_SLUG!==P||e.PHOENIX_SERVER_URL!==Y?(eo.step("Preparing development deployment"),await g({serverUrl:Y,projectSlug:y,environmentSlug:P,credential:C,outFile:".env.generated",skipUpload:H,overrideSchema:!0,debug:M,projectVersion:R},{logger:eo})):eo.debug(".env.generated matches the current development environment, skipping prepare")}eo.step("Building project files");let{templateFiles:E}=await j({sdkVersion:R,projectSlug:y,environmentSlug:P,cliUseWorkspace:_,enableEditor:O,withLingui:V,force:U},{logger:eo});if(eo.success("Project files built successfully"),Z&&(eo=p({bus:K,stream:"spec",debug:M,fileLogger:z}),et=u(K),er=f(K,{onQuit:()=>void ei(0)})),V?(F=new s({logger:eo})).start():eo.warn("Lingui is disabled: i18n messages are not extracted or compiled during dev. Pass --withLingui or set WITH_LINGUI=true to enable."),i&&(eo.step("Building webhooks"),await x.run("webhook",async()=>{await I({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:"./.phoenix/.swc/.phoenix/webhook.js"})})),i&&Y&&C){let e=await T(".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 v();X=await h({experimental:!0,transport:w({serverUrl:Y,credential:C,projectSlug:y,environmentSlug:P}),rejectionHint:o(C,y),environmentSlug:P,deploymentId:e.DEPLOYMENT_ID,sessionId:t,onStatus:(r,o)=>{l?.setStatus(r,{deploymentId:e.DEPLOYMENT_ID,sessionId:t,message:o??null})},onRequest:e=>l?.record(e)}),l?.setStatus("waiting",{deploymentId:e.DEPLOYMENT_ID,sessionId:t}),X.stopped.catch(e=>{es(),eo.error(`Webhook tunnel failed: ${e instanceof Error?e.message:String(e)}`),ei(1)}),eo.success("Webhook tunnel started")}if(O&&L){eo.step("Starting editor WebSocket server");let e=parseInt(L,10);q=r({port:e,projectRoot:process.cwd(),pubsub:A,logger:eo,logBus:K,tunnelMonitor:l,debug:M,prepareDeployment:i&&Y&&C?()=>g({serverUrl:Y,projectSlug:y,environmentSlug:P,credential:C,outFile:".env.generated",skipUpload:!0,overrideSchema:!0,debug:!1,projectVersion:R},{logger:eo}):void 0}),await q.ready,eo.debug(`Editor WebSocket server started on port ${e}`),(J=new a({projectRoot:process.cwd(),pubsub:A,logger:eo})).start()}let b=await d({templateFiles:E});if(B=await t(b),await B.listen(),eo.step("Starting Vite dev server"),(Q=new n({viteServer:B,pubsub:A,logger:eo,onRebuilt:()=>F?.trigger(),onViteServerChange:e=>{B=e},sdkVersion:R,projectSlug:y,environmentSlug:P,cliUseWorkspace:_,enableEditor:O??!0,inlineTemplates:!1,useServer:i})).start(),Z)eo.success("Vite dev server started — watching for changes"),O&&L&&eo.info(`Editor WebSocket: ws://localhost:${L}`);else if(M)eo.success("Vite dev server started");else{let e=e=>{K.push("spec","info",e),process.stdout.write(`${e}
5
- `)};e("\n\uD83D\uDE80 Phoenix Dev Server\n"),O&&L&&e(`Editor WebSocket: ws://localhost:${L}`),e("\n\uD83D\uDC40 Watching for changes...\n")}}catch(e){es(),eo.error(`Dev mode failed: ${e instanceof Error?e.message:String(e)}`,e),await ei(1)}};
4
+ `)}),ee&&(et=u(K,{echo:!0})),process.env.NODE_ENV="development",M&&(process.env.PERSISTENCE_MODE=M);let i=!M||"server"===M;i&&Y&&(process.env.SERVER_URL=Y);let l=i&&Y?new c(Y):void 0;if(eo.step("Starting development mode"),!await S("spec")){eo.error('Spec folder not found. Run "phoenix init" first.'),await ei(1);return}if(i){if(!Y||!C)throw Error("Server persistence needs a server and a credential. Run `phoenix login <workspace>`, or create a development environment in Studio and paste its .env block into .env.");let e=await j(".env.generated");e?.PHOENIX_PROJECT_SLUG!==D||e.PHOENIX_ENVIRONMENT_SLUG!==y||e.PHOENIX_SERVER_URL!==Y?(eo.step("Preparing development deployment"),await g({serverUrl:Y,projectSlug:D,environmentSlug:y,credential:C,outFile:".env.generated",skipUpload:H,overrideSchema:!0,debug:U,projectVersion:N},{logger:eo})):eo.debug(".env.generated matches the current development environment, skipping prepare")}eo.step("Building project files");let{templateFiles:E}=await x({sdkVersion:N,projectSlug:D,environmentSlug:y,cliUseWorkspace:_,enableEditor:O,withLingui:V,force:W},{logger:eo});if(eo.success("Project files built successfully"),Z&&(eo=p({bus:K,stream:"spec",debug:U,fileLogger:z}),et=u(K),er=f(K,{onQuit:()=>void ei(0)})),V?(F=new s({logger:eo})).start():eo.warn("Lingui is disabled: i18n messages are not extracted or compiled during dev. Pass --withLingui or set WITH_LINGUI=true to enable."),i&&(eo.step("Building webhooks"),await $.run("webhook",async()=>{await I({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:"./.phoenix/.swc/.phoenix/webhook.js"})})),i&&Y&&C){let e=await j(".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 v();X=await h({experimental:!0,transport:w({serverUrl:Y,credential:C,projectSlug:D,environmentSlug:y}),rejectionHint:o(C,D),environmentSlug:y,deploymentId:e.DEPLOYMENT_ID,sessionId:t,onStatus:(r,o)=>{l?.setStatus(r,{deploymentId:e.DEPLOYMENT_ID,sessionId:t,message:o??null})},onRequest:e=>l?.record(e)}),l?.setStatus("waiting",{deploymentId:e.DEPLOYMENT_ID,sessionId:t}),X.stopped.catch(e=>{es(),eo.error(`Webhook tunnel failed: ${e instanceof Error?e.message:String(e)}`),ei(1)}),eo.success("Webhook tunnel started")}if(O&&L){eo.step("Starting editor WebSocket server");let e=parseInt(L,10);q=r({port:e,projectRoot:process.cwd(),pubsub:A,logger:eo,logBus:K,tunnelMonitor:l,debug:U,prepareDeployment:i&&Y&&C?()=>g({serverUrl:Y,projectSlug:D,environmentSlug:y,credential:C,outFile:".env.generated",skipUpload:!0,overrideSchema:!0,debug:!1,projectVersion:N},{logger:eo}):void 0}),await q.ready,eo.debug(`Editor WebSocket server started on port ${e}`),(J=new a({projectRoot:process.cwd(),pubsub:A,logger:eo})).start()}let b=await d({templateFiles:E});B=await t(b),await B.listen(),eo.step("Starting Vite dev server"),(Q=new n({viteServer:B,pubsub:A,logger:eo,onRebuilt:()=>F?.trigger(),onViteServerChange:e=>{B=e},sdkVersion:N,projectSlug:D,environmentSlug:y,cliUseWorkspace:_,enableEditor:O??!0,inlineTemplates:!1,useServer:i})).start();let T=B.resolvedUrls?.local[0];if(Z)eo.success("Vite dev server started — watching for changes"),T&&eo.info(`Preview: ${T}`),O&&L&&eo.info(`Editor WebSocket: ws://localhost:${L}`);else if(U)eo.success("Vite dev server started"),T&&eo.info(`Preview: ${T}`);else{let e=e=>{K.push("spec","info",e),process.stdout.write(`${e}
5
+ `)};e("\n\uD83D\uDE80 Phoenix Dev Server\n"),T&&(e(`Preview: ${T}`),z.write("info",`Preview: ${T}`)),O&&L&&e(`Editor WebSocket: ws://localhost:${L}`),e("\n\uD83D\uDC40 Watching for changes...\n")}}catch(e){es(),eo.error(`Dev mode failed: ${e instanceof Error?e.message:String(e)}`,e),await ei(1)}};
@@ -6,7 +6,8 @@ export interface InitCommandProps {
6
6
  }
7
7
  /**
8
8
  * Starts a Phoenix project: writes a `package.json` that depends on this CLI's SDK version when the folder has none,
9
- * and the starter spec, and switches the project to the application-spec pipeline. It touches no server and asks
9
+ * the starter spec and the pnpm settings the first install needs, and switches the project to the application-spec
10
+ * pipeline. It touches no server and asks
10
11
  * nothing: the starter spec names the default project of whichever workspace the developer signs in to, and
11
12
  * everything else is generated by sync or the build.
12
13
  *
@@ -1 +1 @@
1
- import{existsSync as e}from"fs";import{mkdir as n,readFile as t,writeFile as i}from"fs/promises";import{basename as o,dirname as r,join as p}from"path";import{starterSpecFiles as a}from"./init-starter-spec.js";let s="@salsita-ai/sdk",c=async e=>{let n=`Install the SDK first (\`pnpm add ${s}\`), then rerun \`pnpm phoenix init\`.`,i=JSON.parse(await t(e,"utf-8"));if("object"!=typeof i||null===i||Array.isArray(i))throw Error(`phoenix init could not read package.json because it is not a JSON object. ${n}`);if(!["dependencies","devDependencies"].some(e=>{let n=Reflect.get(i,e);return"object"==typeof n&&null!==n&&s in n}))throw Error(`phoenix init found no ${s} dependency in package.json. ${n}`);return{...i}},l=async e=>{for(let t of a){let o=p(e,t.path);await n(r(o),{recursive:!0}),await i(o,t.content)}},d=async(e,n)=>{let t=n.phoenix;await i(e,JSON.stringify({...n,phoenix:{..."object"==typeof t&&null!==t?t:{},applicationFlow:!0}},null,2)+"\n")};export const runInitCommand=async(t,{logger:i})=>{var r,a;let f,h=t.projectRoot??process.cwd(),m=p(h,"package.json");if(e(p(h,"spec")))throw Error("phoenix init found an existing spec/ folder. init only starts new projects, and writing a starter spec would overwrite or mix with the existing one. To update an existing project, run `pnpm phoenix sync`; to start over, run init in an empty project folder.");let u=e(m)?await c(m):(r=h,a=t.sdkVersion,{name:(f=o(r).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[-]+$/g,"")).length>0?f:"phoenix-configurator",private:!0,type:"module",dependencies:{[s]:a},devDependencies:{"@lingui/cli":"5.9.5","@lingui/swc-plugin":"5.11.0"}});i.step(`Writing the starter project to ${h}`),await n(h,{recursive:!0}),await l(h),await d(m,u),i.success(`Phoenix project created in ${h}.`),i.info("\nNext steps, in the project folder:\n pnpm install\n pnpm phoenix sync\n pnpm phoenix login <workspace>\n pnpm phoenix dev\n pnpm phoenix deploy\n\nDeveloping against a Studio development environment instead? Paste its .env block into .env before phoenix dev.")};
1
+ import{existsSync as e}from"fs";import{mkdir as n,readFile as t,writeFile as i}from"fs/promises";import{basename as o,dirname as r,join as p}from"path";import{ensureWorkspaceInstallSettings as a}from"../utils/index.js";import{starterSpecFiles as s}from"./init-starter-spec.js";let c="@salsita-ai/sdk",l=async e=>{let n=`Install the SDK first (\`pnpm add ${c}\`), then rerun \`pnpm phoenix init\`.`,i=JSON.parse(await t(e,"utf-8"));if("object"!=typeof i||null===i||Array.isArray(i))throw Error(`phoenix init could not read package.json because it is not a JSON object. ${n}`);if(!["dependencies","devDependencies"].some(e=>{let n=Reflect.get(i,e);return"object"==typeof n&&null!==n&&c in n}))throw Error(`phoenix init found no ${c} dependency in package.json. ${n}`);return{...i}},d=async e=>{for(let t of s){let o=p(e,t.path);await n(r(o),{recursive:!0}),await i(o,t.content)}},m=async(e,n)=>{let t=n.phoenix;await i(e,JSON.stringify({...n,phoenix:{..."object"==typeof t&&null!==t?t:{},applicationFlow:!0}},null,2)+"\n")};export const runInitCommand=async(t,{logger:i})=>{var r,s;let f,u=t.projectRoot??process.cwd(),h=p(u,"package.json");if(e(p(u,"spec")))throw Error("phoenix init found an existing spec/ folder. init only starts new projects, and writing a starter spec would overwrite or mix with the existing one. To update an existing project, run `pnpm phoenix sync`; to start over, run init in an empty project folder.");let w=e(h)?await l(h):(r=u,s=t.sdkVersion,{name:(f=o(r).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[-]+$/g,"")).length>0?f:"phoenix-configurator",private:!0,type:"module",dependencies:{[c]:s},devDependencies:{"@lingui/cli":"5.9.5","@lingui/swc-plugin":"5.11.0"}});i.step(`Writing the starter project to ${u}`),await n(u,{recursive:!0}),await d(u),await m(h,w),a(u),i.success(`Phoenix project created in ${u}.`),i.info("\nNext steps, in the project folder:\n pnpm install\n pnpm phoenix sync\n pnpm phoenix login <workspace>\n pnpm phoenix dev\n pnpm phoenix deploy\n\nDeveloping against a Studio development environment instead? Paste its .env block into .env before phoenix dev.")};