@salsita-ai/sdk 0.50.0-develop.a926ccd94f → 0.50.0-develop.aff4f8dd6d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/application-spec/generate-application/code/project-scaffolding.js +2 -2
- package/dist/application-spec/generate-application/code/templates/index.d.ts +1 -0
- package/dist/application-spec/generate-application/code/templates/index.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/agents-md.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-cli-skill.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-create-configurator-skill.js +41 -13
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-review-skill.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-skill.js +1 -1
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.d.ts +1 -0
- package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.js +6 -0
- package/dist/application-spec/generate-application/code/templates/skills/sdk-content.d.ts +28 -2
- package/dist/application-spec/generate-application/code/templates/skills/sdk-content.js +19 -4
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
- package/dist/configurator/application-runtime/extensions/selectors.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +158 -13
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.d.ts +85 -0
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.js +1 -0
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.d.ts +8 -3
- package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +4 -0
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.d.ts +16 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.d.ts +9 -0
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.js +1 -0
- package/dist/configurator/application-runtime/extensions/systems/index.d.ts +1 -1
- package/dist/configurator/index.d.ts +0 -1
- package/dist/configurator/index.js +1 -1
- package/dist/configurator/pages/LoadedConfiguratorDetailPage.js +1 -1
- package/dist/configurator/ui/assistant/AssistantChips.js +1 -1
- package/dist/configurator/ui/assistant/AssistantComposer.d.ts +1 -6
- package/dist/configurator/ui/assistant/AssistantComposer.js +1 -1
- package/dist/configurator/ui/assistant/AssistantPanel.js +1 -1
- package/dist/configurator/ui/assistant/AssistantThread.d.ts +1 -6
- package/dist/configurator/ui/assistant/AssistantThread.js +1 -1
- package/dist/configurator/ui/assistant/index.d.ts +1 -1
- package/dist/configurator/ui/assistant/index.js +1 -1
- package/dist/configurator/ui/assistant/thread-items.d.ts +1 -1
- package/dist/configurator/ui/assistant/tool-chip.d.ts +8 -1
- package/dist/configurator/ui/assistant/tool-chip.js +1 -1
- package/dist/configurator/ui/assistant/use-is-assistant-panel-open.d.ts +5 -0
- package/dist/configurator/ui/assistant/use-is-assistant-panel-open.js +1 -0
- package/dist/configurator/ui/configurator-layout/universal/DesktopLayout.js +2 -2
- package/dist/configurator/ui/configurator-layout/universal/Layout.js +1 -1
- package/dist/configurator/ui/configurator-layout/universal/MobileLayout.js +4 -4
- package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.d.ts +2 -2
- package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.js +1 -1
- package/dist/docs/index.json +1 -1
- package/dist/docs/layouts/toolbar.mdx +3 -1
- package/dist/docs/other-features/side-effects.mdx +26 -0
- package/dist/docs/phoenix/phoenix-cli.mdx +80 -1
- package/dist/docs/phoenix/project-structure.mdx +3 -2
- package/dist/docs/phoenix/sdk-builder-workflow.mdx +4 -3
- package/dist/domain/components/updates.d.ts +16 -0
- package/dist/domain/domain-context/store-system/store-system.js +1 -1
- package/dist/editor/Editor.js +1 -1
- package/dist/editor/graphql/GraphQLPanel.js +1 -1
- package/dist/editor/variants/VariantAnswerFooter.d.ts +17 -0
- package/dist/editor/variants/VariantAnswerFooter.js +1 -0
- package/dist/editor/variants/VariantPreviewHandler.d.ts +6 -0
- package/dist/editor/variants/VariantPreviewHandler.js +1 -0
- package/dist/editor/variants/variant-preview-styles.d.ts +49 -0
- package/dist/editor/variants/variant-preview-styles.js +1 -0
- package/dist/i18n/locales/cs/messages.js +1 -1
- package/dist/i18n/locales/da/messages.js +1 -1
- package/dist/i18n/locales/de/messages.js +1 -1
- package/dist/i18n/locales/de-AT/messages.js +1 -1
- package/dist/i18n/locales/en/messages.js +1 -1
- package/dist/i18n/locales/en-AU/messages.js +1 -1
- package/dist/i18n/locales/en-GB/messages.js +1 -1
- package/dist/i18n/locales/es/messages.js +1 -1
- package/dist/i18n/locales/fr/messages.js +1 -1
- package/dist/i18n/locales/hu/messages.js +1 -1
- package/dist/i18n/locales/it/messages.js +1 -1
- package/dist/i18n/locales/nl/messages.js +1 -1
- package/dist/i18n/locales/pl/messages.js +1 -1
- package/dist/i18n/locales/pt/messages.js +1 -1
- package/dist/i18n/locales/ro/messages.js +1 -1
- package/dist/i18n/locales/sk/messages.js +1 -1
- package/dist/i18n/locales/tr/messages.js +1 -1
- package/dist/phoenix/application-spec/application-spec-builder.js +1 -1
- package/dist/phoenix/application-spec/generate-assistant-prompt.d.ts +3 -2
- package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
- package/dist/phoenix/cli.js +1 -1
- package/dist/phoenix/commands/dev.js +5 -5
- package/dist/phoenix/commands/index.d.ts +1 -0
- package/dist/phoenix/commands/index.js +1 -1
- package/dist/phoenix/commands/story-dev.js +2 -2
- package/dist/phoenix/commands/variants.d.ts +35 -0
- package/dist/phoenix/commands/variants.js +1 -0
- package/dist/phoenix/editor-server/commands-router.d.ts +68 -1
- package/dist/phoenix/editor-server/commands-router.js +1 -1
- package/dist/phoenix/editor-server/editor-router.d.ts +65 -0
- package/dist/phoenix/editor-server/editor-server.d.ts +3 -3
- package/dist/phoenix/editor-server/editor-server.js +1 -1
- package/dist/phoenix/editor-server/protocol.d.ts +1 -0
- package/dist/phoenix/editor-server/spec-router.js +1 -1
- package/dist/phoenix/editor-server/trpc.d.ts +3 -0
- package/dist/phoenix/services/application-spec-project-watcher.d.ts +13 -2
- package/dist/phoenix/services/application-spec-project-watcher.js +3 -3
- package/dist/phoenix/services/index.d.ts +4 -0
- package/dist/phoenix/services/index.js +1 -1
- package/dist/phoenix/services/phoenix-application.d.ts +21 -0
- package/dist/phoenix/services/phoenix-application.js +1 -0
- package/dist/phoenix/services/phoenix-store.d.ts +48 -0
- package/dist/phoenix/services/phoenix-store.js +1 -0
- package/dist/phoenix/services/phx-variant-previews-plugin.d.ts +9 -0
- package/dist/phoenix/services/phx-variant-previews-plugin.js +1 -0
- package/dist/phoenix/services/variant-file-session.d.ts +36 -0
- package/dist/phoenix/services/variant-file-session.js +1 -0
- package/dist/phoenix/services/variant-preview-service.d.ts +80 -0
- package/dist/phoenix/services/variant-preview-service.js +1 -0
- package/dist/phoenix/services/vite-config.js +1 -1
- package/dist/ui-sdk/common/use-viewport-size.d.ts +4 -1
- package/dist/ui-sdk/common/use-viewport-size.js +1 -1
- package/package.json +4 -4
- package/dist/configurator/assistant/index.d.ts +0 -1
- package/dist/configurator/assistant/index.js +0 -1
- package/dist/configurator/assistant/use-assistant-chat.d.ts +0 -30
- package/dist/configurator/assistant/use-assistant-chat.js +0 -1
- package/dist/configurator/ui/assistant/AssistantPanelProvider.d.ts +0 -42
- package/dist/configurator/ui/assistant/AssistantPanelProvider.js +0 -1
|
@@ -165,6 +165,71 @@ export declare const appRouter: import("@trpc/server").TRPCBuiltRouter<{
|
|
|
165
165
|
output: void;
|
|
166
166
|
meta: object;
|
|
167
167
|
}>;
|
|
168
|
+
previewVariants: import("@trpc/server").TRPCMutationProcedure<{
|
|
169
|
+
input: {
|
|
170
|
+
title: string;
|
|
171
|
+
description: string;
|
|
172
|
+
variants: {
|
|
173
|
+
id: string;
|
|
174
|
+
kind: "page" | "script";
|
|
175
|
+
label: string;
|
|
176
|
+
description: string;
|
|
177
|
+
url: string;
|
|
178
|
+
}[];
|
|
179
|
+
timeoutMs: number;
|
|
180
|
+
};
|
|
181
|
+
output: import("../services/variant-preview-service.js").VariantPreviewOutcome;
|
|
182
|
+
meta: object;
|
|
183
|
+
}>;
|
|
184
|
+
onVariantPreview: import("@trpc/server/unstable-core-do-not-import").LegacyObservableSubscriptionProcedure<{
|
|
185
|
+
input: void;
|
|
186
|
+
output: import("./protocol.js").VariantPreviewRequest | null;
|
|
187
|
+
meta: object;
|
|
188
|
+
}>;
|
|
189
|
+
getVariantBaseline: import("@trpc/server").TRPCQueryProcedure<{
|
|
190
|
+
input: {
|
|
191
|
+
requestId: string;
|
|
192
|
+
};
|
|
193
|
+
output: {
|
|
194
|
+
readonly files: readonly import("../services/variant-file-session.js").VariantFileEdit[];
|
|
195
|
+
readonly choice: string | null;
|
|
196
|
+
};
|
|
197
|
+
meta: object;
|
|
198
|
+
}>;
|
|
199
|
+
applyVariantFiles: import("@trpc/server").TRPCMutationProcedure<{
|
|
200
|
+
input: {
|
|
201
|
+
requestId: string;
|
|
202
|
+
choice: string | null;
|
|
203
|
+
files: {
|
|
204
|
+
fileName: string;
|
|
205
|
+
content: string | null;
|
|
206
|
+
}[];
|
|
207
|
+
};
|
|
208
|
+
output: void;
|
|
209
|
+
meta: object;
|
|
210
|
+
}>;
|
|
211
|
+
submitVariantChoice: import("@trpc/server").TRPCMutationProcedure<{
|
|
212
|
+
input: {
|
|
213
|
+
requestId: string;
|
|
214
|
+
choice: string | null;
|
|
215
|
+
};
|
|
216
|
+
output: void;
|
|
217
|
+
meta: object;
|
|
218
|
+
}>;
|
|
219
|
+
closeVariantPreview: import("@trpc/server").TRPCMutationProcedure<{
|
|
220
|
+
input: void;
|
|
221
|
+
output: {
|
|
222
|
+
readonly closed: boolean;
|
|
223
|
+
};
|
|
224
|
+
meta: object;
|
|
225
|
+
}>;
|
|
226
|
+
claimVariantChoice: import("@trpc/server").TRPCMutationProcedure<{
|
|
227
|
+
input: {
|
|
228
|
+
requestId: string;
|
|
229
|
+
};
|
|
230
|
+
output: void;
|
|
231
|
+
meta: object;
|
|
232
|
+
}>;
|
|
168
233
|
}> & import("@trpc/server").TRPCDecorateCreateRouterOptions<{
|
|
169
234
|
saveMock: import("@trpc/server").TRPCMutationProcedure<{
|
|
170
235
|
input: {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { LogBus } from '../services/log-bus.js';
|
|
2
|
-
import type {
|
|
2
|
+
import type { PhoenixApplication } from '../services/phoenix-application.js';
|
|
3
3
|
import type { WebhookTunnelMonitor } from '../services/webhook-tunnel-monitor.js';
|
|
4
4
|
import type { Logger } from '../utils/index.js';
|
|
5
5
|
export interface EditorServerOptions {
|
|
6
6
|
readonly port: number;
|
|
7
7
|
readonly projectRoot: string;
|
|
8
|
-
readonly
|
|
8
|
+
readonly application: PhoenixApplication;
|
|
9
9
|
readonly logger: Logger;
|
|
10
10
|
readonly debug?: boolean;
|
|
11
11
|
/** Bound to this dev session; absent for offline and story sessions. */
|
|
@@ -14,7 +14,7 @@ export interface EditorServerOptions {
|
|
|
14
14
|
readonly logBus?: LogBus;
|
|
15
15
|
readonly tunnelMonitor?: WebhookTunnelMonitor;
|
|
16
16
|
}
|
|
17
|
-
export declare const startEditorServer: ({ port, projectRoot,
|
|
17
|
+
export declare const startEditorServer: ({ port, projectRoot, application, logger, prepareDeployment, storyMode, logBus, tunnelMonitor, }: EditorServerOptions) => {
|
|
18
18
|
ready: Promise<void>;
|
|
19
19
|
close: () => Promise<void>;
|
|
20
20
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyWSSHandler as e}from"@trpc/server/adapters/ws";import{WebSocketServer as
|
|
1
|
+
import{applyWSSHandler as e}from"@trpc/server/adapters/ws";import{WebSocketServer as r}from"ws";import{appRouter as o}from"./editor-router.js";export const startEditorServer=({port:n,projectRoot:t,application:i,logger:s,prepareDeployment:c,storyMode:l,logBus:a,tunnelMonitor:f})=>{let m=new r({port:n}),u=e({wss:m,router:o,createContext:()=>({projectRoot:t,pubsub:i.pubsub,variantPreviews:i.variantPreviews,logger:s,prepareDeployment:c,storyMode:l,logBus:a,tunnelMonitor:f})});m.on("connection",(e,r)=>{let o=r.headers.origin??"unknown";s.info(`WS connected (clients: ${m.clients.size}, origin: ${o})`),e.on("error",e=>{s.warn(`WS error: ${e.message}`)}),e.once("close",(e,r)=>{s.info(`WS disconnected (clients: ${m.clients.size}, code: ${e}, reason: ${r.toString()||"none"})`)})}),m.on("error",e=>{s.error(`WebSocket server error: ${e.message}`)});let w=new Promise((e,r)=>{let o=()=>{m.off("error",t),s.info(`WebSocket Server listening on ws://localhost:${n}`),e()},t=e=>{m.off("listening",o),r(e)};m.once("listening",o),m.once("error",t)}),d=null;return{ready:w,close:()=>d||(s.info("Shutting down WebSocket server"),u.broadcastReconnectNotification(),d=new Promise((e,r)=>{let o=setTimeout(()=>{for(let e of m.clients)e.terminate()},3e3);m.close(n=>{clearTimeout(o),n?r(n):e()})}))}};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
/** Internal browser/editor protocol. This entry has no runtime package mapping. */
|
|
2
2
|
export type { AppRouter } from './editor-router.js';
|
|
3
3
|
export type { DataRequest, EditorContextData, SceneRequest, EditorLifecycleStatus, StateRequest, ScreenshotRequest, } from '../services/phoenix-pubsub.js';
|
|
4
|
+
export type { VariantPreviewOption, VariantPreviewRequest } from '../services/phoenix-store.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TRPCError as e}from"@trpc/server";import{observable as o}from"@trpc/server/observable";import{writeFile as t}from"fs/promises";import{join as r}from"path";import{z as i}from"zod";import{readApplicationFiles as
|
|
1
|
+
import{TRPCError as e}from"@trpc/server";import{observable as o}from"@trpc/server/observable";import{writeFile as t}from"fs/promises";import{join as r}from"path";import{z as i}from"zod";import{readApplicationFiles as s}from"../application-spec/index.js";import{exists as p}from"../utils/index.js";import{publicProcedure as a,router as n}from"./trpc.js";export const specRouter=n({getEditorConfig:a.query(()=>({specSync:!0})),prepareDeployment:a.mutation(async({ctx:o})=>{if(o.variantPreviews?.isOpen)throw new e({code:"BAD_REQUEST",message:"Deployment preparation is disabled during variant previews. Close the preview first."});if(o.storyMode)throw new e({code:"BAD_REQUEST",message:"Deployment preparation is disabled in Storybook story mode."});if(!o.prepareDeployment)throw new e({code:"BAD_REQUEST",message:"Deployment preparation requires a deployment configuration outside story mode."});await o.prepareDeployment()}),requestSpecFiles:a.mutation(async({ctx:e})=>{let o=e.storyMode?await s({projectRoot:e.projectRoot,envs:{}}):await s();e.pubsub.specFile$.next({rawProjectFiles:o,projectRoot:e.projectRoot})}),save:a.input(i.array(i.object({fileName:i.string(),content:i.string()}))).mutation(async({ctx:o,input:i})=>{if(o.variantPreviews?.isOpen)throw new e({code:"BAD_REQUEST",message:"Close the variant preview before editing source files."});for(let e of i){let i=r(o.projectRoot,e.fileName),s=r(o.projectRoot,e.fileName.split("/").slice(0,-1).join("/"));await p(s)&&await t(i,e.content)}}),onSpecChange:a.subscription(({ctx:e})=>o(o=>{let t=e.pubsub.specFile$.subscribe(e=>{o.next(e)});return()=>{t.unsubscribe()}}))});
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import type { LogBus } from '../services/log-bus.js';
|
|
2
2
|
import type { PhoenixPubSub } from '../services/phoenix-pubsub.js';
|
|
3
|
+
import type { VariantPreviewService } from '../services/variant-preview-service.js';
|
|
3
4
|
import type { WebhookTunnelMonitor } from '../services/webhook-tunnel-monitor.js';
|
|
4
5
|
import type { Logger } from '../utils/index.js';
|
|
5
6
|
export type Context = {
|
|
6
7
|
readonly projectRoot: string;
|
|
7
8
|
readonly pubsub: PhoenixPubSub;
|
|
8
9
|
readonly logger: Logger;
|
|
10
|
+
/** The session's variant comparison; absent where project files cannot be rewritten, such as story-dev. */
|
|
11
|
+
readonly variantPreviews: VariantPreviewService | undefined;
|
|
9
12
|
/** Bound to this dev session; absent for offline and story sessions. */
|
|
10
13
|
readonly prepareDeployment?: () => Promise<void>;
|
|
11
14
|
readonly storyMode?: boolean;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { type ViteDevServer } from 'vite';
|
|
2
2
|
import type { Logger } from '../utils/index.js';
|
|
3
3
|
import type { PhoenixPubSub } from './phoenix-pubsub.js';
|
|
4
|
+
import type { VariantFileEdit } from './variant-file-session.js';
|
|
4
5
|
/** Configuration for {@link ApplicationSpecProjectWatcher}. */
|
|
5
6
|
export interface ApplicationSpecProjectWatcherConfig {
|
|
6
|
-
readonly viteServer: ViteDevServer;
|
|
7
7
|
readonly pubsub: PhoenixPubSub;
|
|
8
8
|
readonly logger: Logger;
|
|
9
9
|
readonly onRebuilt?: () => void;
|
|
@@ -42,8 +42,19 @@ export declare class ApplicationSpecProjectWatcher {
|
|
|
42
42
|
private readonly builder;
|
|
43
43
|
private readonly useServer;
|
|
44
44
|
private isShuttingDown;
|
|
45
|
+
private suspended;
|
|
46
|
+
private readonly heldChanges;
|
|
45
47
|
constructor(config: ApplicationSpecProjectWatcherConfig);
|
|
46
|
-
start(): void;
|
|
48
|
+
start(viteServer: ViteDevServer): void;
|
|
49
|
+
/** Rebuilds a batch a variant comparison wrote, at once and without the server work of a source change. */
|
|
50
|
+
applyVariantFiles(files: readonly VariantFileEdit[]): void;
|
|
51
|
+
/**
|
|
52
|
+
* Holds source changes back until `resume`: a variant comparison rewrites files and rebuilds them itself,
|
|
53
|
+
* and a rebuild from the watcher would repeat that with the server work on top.
|
|
54
|
+
*/
|
|
55
|
+
suspend(): void;
|
|
56
|
+
/** Rebuilds once for everything that changed while suspended, so no edit made meanwhile is lost. */
|
|
57
|
+
resume(): void;
|
|
47
58
|
close(): Promise<void>;
|
|
48
59
|
private setupFileWatcher;
|
|
49
60
|
private setupRebuildSubscription;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{resolve as e}from"path";import t from"promise-queue";import{Subject as i,buffer as s,debounceTime as r}from"rxjs";import{createServer as o,normalizePath as n}from"vite";import{watch as l}from"#package/watch";import{ApplicationSpecBuilder as
|
|
2
|
-
📝 Detected ${e}: ${t}`),this.changeSubject$.next(t)
|
|
1
|
+
import{resolve as e}from"path";import t from"promise-queue";import{Subject as i,buffer as s,debounceTime as r}from"rxjs";import{createServer as o,normalizePath as n}from"vite";import{watch as l}from"#package/watch";import{ApplicationSpecBuilder as h}from"../application-spec/application-spec-builder.js";import{logDiagnostics as a}from"../application-spec/metrics/index.js";import{syncTemplateFiles as c}from"../application-spec/template-files.js";import{buildWebhooks as u}from"../webhooks/index.js";import{getViteDevConfig as p}from"./vite-config.js";let g=["spec/**/*.{yaml,yml}","src/**/*.{ts,tsx,yaml,yml,json,html,css}","templates/*.html",".env",".env.generated"],d=["src/locales/**/*.{ts,tsx}",".phoenix/**"];export class ApplicationSpecProjectWatcher{watcher=null;subscription=null;rebuildQueue=new t(1,1/0);changeSubject$=new i;viteServer=null;pubsub;logger;onRebuilt;onViteServerChange;builder;useServer;isShuttingDown=!1;suspended=!1;heldChanges=new Set;constructor(e){this.pubsub=e.pubsub,this.logger=e.logger,this.onRebuilt=e.onRebuilt,this.onViteServerChange=e.onViteServerChange,this.builder=new h({logger:e.logger,sdkVersion:e.sdkVersion,projectSlug:e.projectSlug,environmentSlug:e.environmentSlug,cliUseWorkspace:e.cliUseWorkspace,name:e.name,description:e.description,enableEditor:e.enableEditor,inlineTemplates:e.inlineTemplates}),this.useServer=e.useServer}start(e){this.viteServer=e,this.setupFileWatcher(),this.setupRebuildSubscription()}applyVariantFiles(e){this.rebuildQueue.add(async()=>{this.isShuttingDown||await this.rebuild(new Set(e.map(e=>e.fileName)),!1,!0)})}suspend(){this.suspended=!0}resume(){for(let e of(this.suspended=!1,this.heldChanges))this.changeSubject$.next(e);this.heldChanges.clear()}async close(){this.isShuttingDown=!0,this.watcher&&(await this.watcher.close(),this.watcher=null),this.subscription?.unsubscribe(),this.changeSubject$.complete()}setupFileWatcher(){this.watcher=l(g,{ignored:d,cwd:process.cwd(),persistent:!0,ignoreInitial:!1}),this.watcher.on("all",(e,t)=>{if("change"===e||"add"===e||"unlink"===e){if(this.suspended)return void this.heldChanges.add(t);this.logger.info(`
|
|
2
|
+
📝 Detected ${e}: ${t}`),this.changeSubject$.next(t)}})}setupRebuildSubscription(){let e=this.changeSubject$.pipe(r(10));this.subscription=this.changeSubject$.pipe(s(e)).subscribe(e=>{let t=new Set(e),i=t.has(".env");this.rebuildQueue.add(async()=>{this.isShuttingDown||(this.logger.info(`
|
|
3
3
|
🔨 Rebuilding spec files...
|
|
4
|
-
`),await this.rebuild(t,i))})})}async rebuild(t,i){try{let
|
|
4
|
+
`),await this.rebuild(t,i,!1))})})}async rebuild(t,i,s){try{let r=this.viteServer;if(!r)throw Error("Cannot rebuild the project: the watcher has no Vite server yet, because it was not started. Start the watcher before applying files");let l=await c();if(this.isShuttingDown)return;let h=await this.builder.build({compile:!s});if(this.isShuttingDown)return;if(a(h.diagnostics,this.logger),!h.ok){for(let e of h.errors)this.logger.error(`[${e.code}] ${e.message}${e.file?` (${e.file})`:""}`);this.pubsub.specFile$.next({rawProjectFiles:h.rawProjectFiles,projectRoot:process.cwd()});return}this.onRebuilt?.();let{application:g,changedFiles:d}=h,w=r.moduleGraph,b=Date.now(),f=new Set,m=process.cwd(),S=e=>{let t=w.getModulesByFile(n(e));if(t)for(let e of t)w.invalidateModule(e,f,b,!0)};for(let i of t)S(e(m,i));for(let t of d)S(e(m,`.phoenix/${t.path}`));if(this.pubsub.specFile$.next({rawProjectFiles:g.rawProjectFiles,projectRoot:process.cwd(),configurationSchemaHash:g.applicationSpec.configurator.configurationSchema.hash}),this.isShuttingDown)return;if(i){if(await r.close(),this.isShuttingDown)return;let e=await p({templateFiles:l});if(this.isShuttingDown)return;let t=await o(e);if(this.isShuttingDown||(await t.listen(),this.isShuttingDown))return void await t.close();this.viteServer=t,this.onViteServerChange?.(t),this.logger.success("Vite server restarted (env changed)")}if(this.useServer&&!s){if(this.logger.step("Building webhooks"),await u({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:"./.phoenix/.swc/.phoenix/webhook.js",preserveExistingOutput:!0}),this.isShuttingDown)return;this.logger.success("Webhooks rebuilt successfully")}this.logger.success("Project files rebuilt successfully")}catch(e){this.logger.error(`Build failed: ${e instanceof Error?e.message:String(e)}`,e)}}}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
export type { BrowserConsoleEvent, DataRequest, DataResult, EditorContextData, EditorLifecycleStatus, EditorStateData, MockTemplateUpdateEvent, SceneRequest, SceneResult, ScreenshotRequest, ScreenshotResult, SpecUpdateEvent, StateRequest, StateResult, StateSection, } from './phoenix-pubsub.js';
|
|
2
2
|
export { PhoenixPubSub } from './phoenix-pubsub.js';
|
|
3
|
+
export { PhoenixStore } from './phoenix-store.js';
|
|
4
|
+
export { PhoenixApplication } from './phoenix-application.js';
|
|
5
|
+
export { VariantFileSession } from './variant-file-session.js';
|
|
6
|
+
export { VariantPreviewService } from './variant-preview-service.js';
|
|
3
7
|
export { MockTemplateWatcher, type MockTemplateWatcherConfig } from './mock-template-watcher.js';
|
|
4
8
|
export { ApplicationSpecProjectWatcher, type ApplicationSpecProjectWatcherConfig, } from './application-spec-project-watcher.js';
|
|
5
9
|
export { ApplicationSpecStoryWatcher, type ApplicationSpecStoryWatcherConfig, } from './application-spec-story-watcher.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{PhoenixPubSub}from"./phoenix-pubsub.js";export{MockTemplateWatcher}from"./mock-template-watcher.js";export{ApplicationSpecProjectWatcher}from"./application-spec-project-watcher.js";export{ApplicationSpecStoryWatcher}from"./application-spec-story-watcher.js";export{LinguiWatcher}from"./lingui-watcher.js";export{loadMockTemplates,parseMockTemplateYaml}from"./spec-files.js";export{LOG_STREAMS,LogBus}from"./log-bus.js";export{createBusLogger}from"./bus-logger.js";export{patchConsole}from"./console-capture.js";export{WebhookTunnelMonitor}from"./webhook-tunnel-monitor.js";export{compileWithSwc,watchWithSwc}from"./swc.js";export{STORY_DEV_MARKER_PATH,readActiveStoryDevMarker}from"./story-dev-marker.js";export{composeDefaultBanner}from"./phx-banner-plugin.js";export{getViteBuildConfigs,getViteDevConfig,setViteLogSink}from"./vite-config.js";export{getServerCredentials,removeServerCredentials,saveServerCredentials}from"./cli-credentials.js";export{createSourceArchive,extractSourceArchive}from"./source-archive.js";export{resolveSignedInDevelopmentEnvironment}from"./signed-in-development-environment.js";export{DEFAULT_PHOENIX_REGION,PHOENIX_REGIONS,PUBLIC_PHOENIX_REGIONS,getRegionServerUrl,getRegionStudioUrl}from"./phoenix-regions.js";
|
|
1
|
+
export{PhoenixPubSub}from"./phoenix-pubsub.js";export{PhoenixStore}from"./phoenix-store.js";export{PhoenixApplication}from"./phoenix-application.js";export{VariantFileSession}from"./variant-file-session.js";export{VariantPreviewService}from"./variant-preview-service.js";export{MockTemplateWatcher}from"./mock-template-watcher.js";export{ApplicationSpecProjectWatcher}from"./application-spec-project-watcher.js";export{ApplicationSpecStoryWatcher}from"./application-spec-story-watcher.js";export{LinguiWatcher}from"./lingui-watcher.js";export{loadMockTemplates,parseMockTemplateYaml}from"./spec-files.js";export{LOG_STREAMS,LogBus}from"./log-bus.js";export{createBusLogger}from"./bus-logger.js";export{patchConsole}from"./console-capture.js";export{WebhookTunnelMonitor}from"./webhook-tunnel-monitor.js";export{compileWithSwc,watchWithSwc}from"./swc.js";export{STORY_DEV_MARKER_PATH,readActiveStoryDevMarker}from"./story-dev-marker.js";export{composeDefaultBanner}from"./phx-banner-plugin.js";export{getViteBuildConfigs,getViteDevConfig,setViteLogSink}from"./vite-config.js";export{getServerCredentials,removeServerCredentials,saveServerCredentials}from"./cli-credentials.js";export{createSourceArchive,extractSourceArchive}from"./source-archive.js";export{resolveSignedInDevelopmentEnvironment}from"./signed-in-development-environment.js";export{DEFAULT_PHOENIX_REGION,PHOENIX_REGIONS,PUBLIC_PHOENIX_REGIONS,getRegionServerUrl,getRegionStudioUrl}from"./phoenix-regions.js";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { PhoenixPubSub } from './phoenix-pubsub.js';
|
|
2
|
+
import type { PhoenixStore } from './phoenix-store.js';
|
|
3
|
+
import type { VariantPreviewService } from './variant-preview-service.js';
|
|
4
|
+
export interface PhoenixApplicationProps {
|
|
5
|
+
readonly store: PhoenixStore;
|
|
6
|
+
readonly pubsub: PhoenixPubSub;
|
|
7
|
+
/** Absent in a session that cannot rewrite project files, such as story-dev. */
|
|
8
|
+
readonly variantPreviews: VariantPreviewService | undefined;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* One running dev session: its state, its event bus and the services built on them. The command that
|
|
12
|
+
* starts the session composes it once and hands it to the transports, so the editor server's routers get
|
|
13
|
+
* their services from here instead of from callbacks threaded through the command.
|
|
14
|
+
*/
|
|
15
|
+
export declare class PhoenixApplication {
|
|
16
|
+
readonly store: PhoenixStore;
|
|
17
|
+
readonly pubsub: PhoenixPubSub;
|
|
18
|
+
readonly variantPreviews: VariantPreviewService | undefined;
|
|
19
|
+
constructor(props: PhoenixApplicationProps);
|
|
20
|
+
close(): Promise<void>;
|
|
21
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export class PhoenixApplication{store;pubsub;variantPreviews;constructor(s){this.store=s.store,this.pubsub=s.pubsub,this.variantPreviews=s.variantPreviews}async close(){await this.variantPreviews?.dispose()}}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { BehaviorSubject } from 'rxjs';
|
|
2
|
+
/**
|
|
3
|
+
* A frontend file script or standalone HTML proposal served from `.phoenix/variants/`.
|
|
4
|
+
*/
|
|
5
|
+
export interface VariantPreviewOption {
|
|
6
|
+
/** File name without its suffix; the answer names the picked option by it. */
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly kind: 'script' | 'page';
|
|
9
|
+
readonly label: string;
|
|
10
|
+
/** What sets this option apart from the others; may be empty. */
|
|
11
|
+
readonly description: string;
|
|
12
|
+
/** Address of the option's file on the dev server, with a version query that changes when the file does. */
|
|
13
|
+
readonly url: string;
|
|
14
|
+
}
|
|
15
|
+
/** CLI → browser request to show the options over the configurator and collect the builder's answer. */
|
|
16
|
+
export interface VariantPreviewRequest {
|
|
17
|
+
readonly requestId: string;
|
|
18
|
+
readonly title: string;
|
|
19
|
+
/** A line under the title saying what differs between the options; may be empty. */
|
|
20
|
+
readonly description: string;
|
|
21
|
+
readonly variants: readonly VariantPreviewOption[];
|
|
22
|
+
}
|
|
23
|
+
/** Browser → CLI answer; `choice` is the picked option id, or `null` for Original. */
|
|
24
|
+
export interface VariantPreviewResult {
|
|
25
|
+
readonly requestId: string;
|
|
26
|
+
readonly choice: string | null;
|
|
27
|
+
}
|
|
28
|
+
/** An answer no command was waiting for, kept with the request it answers until a command claims it. */
|
|
29
|
+
export interface UnclaimedVariantPreviewResult {
|
|
30
|
+
readonly request: VariantPreviewRequest;
|
|
31
|
+
readonly result: VariantPreviewResult;
|
|
32
|
+
}
|
|
33
|
+
/** Where the variant comparison of a dev session stands. Written by VariantPreviewService only. */
|
|
34
|
+
export interface VariantPreviewState {
|
|
35
|
+
/** The comparison the editor shows, or `null` when none is open. */
|
|
36
|
+
readonly open: VariantPreviewRequest | null;
|
|
37
|
+
/** The option whose edits are in the source files right now; `null` is the baseline. */
|
|
38
|
+
readonly activeChoice: string | null;
|
|
39
|
+
/** An answer given after the command that asked had stopped waiting. */
|
|
40
|
+
readonly unclaimed: UnclaimedVariantPreviewResult | null;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The state of one dev session. It holds values and no logic: services read and write it, and the
|
|
44
|
+
* editor server reaches it only through them. Events that carry no state stay on PhoenixPubSub.
|
|
45
|
+
*/
|
|
46
|
+
export declare class PhoenixStore {
|
|
47
|
+
readonly variantPreview$: BehaviorSubject<VariantPreviewState>;
|
|
48
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BehaviorSubject as e}from"rxjs";export class PhoenixStore{variantPreview$=new e({open:null,activeChoice:null,unclaimed:null})}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
export declare const isVariantPreviewFile: (root: string, file: string) => boolean;
|
|
3
|
+
/**
|
|
4
|
+
* Option files live under Vite's root and have no HMR boundary, so a change to one would reload the
|
|
5
|
+
* configurator behind the comparison. Listing the folder in `server.watch.ignored` would stop that too, but
|
|
6
|
+
* Vite would then never drop its cached transform, and a rewritten option or helper would be served stale.
|
|
7
|
+
* Answering the hot update with no modules keeps the invalidation and skips only the reload.
|
|
8
|
+
*/
|
|
9
|
+
export declare const phxVariantPreviewsPlugin: () => Plugin;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toPosixPath as i}from"../utils/path.js";export const isVariantPreviewFile=(t,e)=>i(e).startsWith(`${i(t).replace(/\/+$/,"")}/variants/`);export const phxVariantPreviewsPlugin=()=>({name:"phx:variant-previews",hotUpdate({file:i}){return isVariantPreviewFile(this.environment.config.root,i)?[]:void 0}});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Logger } from '../utils/index.js';
|
|
2
|
+
/** A baseline-relative edit collected by an option script; null removes the file. */
|
|
3
|
+
export interface VariantFileEdit {
|
|
4
|
+
readonly fileName: string;
|
|
5
|
+
readonly content: string | null;
|
|
6
|
+
}
|
|
7
|
+
/** Owns the baseline, file transactions and recovery for one live comparison. */
|
|
8
|
+
export declare class VariantFileSession {
|
|
9
|
+
private readonly props;
|
|
10
|
+
private readonly queue;
|
|
11
|
+
private readonly applied;
|
|
12
|
+
private readonly baseline;
|
|
13
|
+
private readonly contract;
|
|
14
|
+
private settled;
|
|
15
|
+
private constructor();
|
|
16
|
+
static create(props: {
|
|
17
|
+
readonly projectRoot: string;
|
|
18
|
+
readonly logger: Logger;
|
|
19
|
+
readonly onFilesChanged: (files: readonly VariantFileEdit[]) => void;
|
|
20
|
+
}): Promise<VariantFileSession>;
|
|
21
|
+
/**
|
|
22
|
+
* Restores the baseline a comparison left behind when its dev session ended without closing it. A file
|
|
23
|
+
* edited since then is left as it is, so the edit survives and the next dev session can still start.
|
|
24
|
+
*/
|
|
25
|
+
static recover(projectRoot: string, logger: Logger): Promise<void>;
|
|
26
|
+
private static resolveFile;
|
|
27
|
+
getFiles(): readonly VariantFileEdit[];
|
|
28
|
+
apply(edits: readonly VariantFileEdit[]): Promise<void>;
|
|
29
|
+
finish(keep: boolean): Promise<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Moves the files from what is applied now to `target`. A file edited outside the comparison is never
|
|
32
|
+
* overwritten: a switch is refused, so the builder sees why, while the end of the comparison keeps that
|
|
33
|
+
* file as it is and restores the others, so the comparison can always be closed.
|
|
34
|
+
*/
|
|
35
|
+
private writeTarget;
|
|
36
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mkdir as e,readFile as t,realpath as i,rename as a,rm as r,writeFile as s}from"node:fs/promises";import{dirname as o,join as n,relative as l,resolve as p,sep as c}from"node:path";import h from"promise-queue";import{z as d}from"zod";import{RawProjectFiles as f,RuntimeReferenceStore as m,TextFile as w,buildPhoenixDefinitions as u,isTextFile as g,parseApplicationFiles as v}from"#package/application-spec";import{getAllPhxDefinitions as y}from"#package/domain";import{readApplicationFiles as b}from"../application-spec/application-spec-file-reader.js";import{generateAssistantPrompt as S}from"../application-spec/generate-assistant-prompt.js";import{swcEvalExpressionParser as F,swcModuleAnalyzer as N}from"../application-spec/swc-module-analyzer.js";let j=".phoenix/variant-recovery.json",k=d.array(d.object({fileName:d.string(),original:d.string().nullable(),applied:d.string().nullable(),previous:d.string().nullable().optional()})),E=e=>!e.includes("\\")&&!e.split("/").some(e=>".."===e||"."===e||""===e)&&(/^spec\/(?!admin\/).+\.yaml$/.test(e)||/^src\/(?:components|transformers|handlers|elements|_[^/]+)\/.+\.tsx?$/.test(e)),M=e=>`Left ${e} as it is: it was edited outside the variant comparison, so restoring the baseline would overwrite that edit. Review the file and remove what the option added to it`,$=async e=>{try{return await t(e,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return null;throw e}},C=async(t,i)=>{if(null===i)return void await r(t,{force:!0});await e(o(t),{recursive:!0});let n=`${t}.variant-${crypto.randomUUID()}`;try{await s(n,i),await a(n,t)}finally{await r(n,{force:!0})}},R=(e,t)=>{let i=v({rawProjectFiles:e,phxDefinitions:u(y())},{analyzer:N,evalExpressionParser:F,referenceStore:new m,logger:t});if(!i.ok)throw Error(`Cannot apply variant: ${i.errors.map(e=>`[${e.code}] ${e.message}`).join("\n")}`);let{configurator:a,admin:r,appMetadata:s,infra:o,dataSpec:n}=i.value.applicationSpec,l=i.value.categorizedFiles,p=new Set([...l.webhooks,...l.expressions,...l.actions,...l.invariants,...l.migrations,...l.adminMigrations,...l.adminExpressions,...l.adminInvariants,...l.handlers.filter(e=>"pinned"===e.webhookMembership||"named-handler"===e.webhookMembership),...l.components.filter(e=>"pinned"===e.webhookMembership),...l.adminComponents.filter(e=>"pinned"===e.webhookMembership)].flatMap(e=>[e.file.name,...e.deps]));return JSON.stringify({webhookFiles:e.files.filter(g).filter(e=>p.has(e.name)).sort((e,t)=>e.name.localeCompare(t.name)),appMetadata:s,infra:o,dataSpec:n,model:a.latestModel,schema:a.configurationSchema,dataSchemas:a.dataSchemas,adminModel:r.latestModel,adminSchema:r.configurationSchema,assistant:a.assistant?.sdl,assistantSettings:a.assistantServerSettings,assistantPrompt:a.assistant?S(a.assistant):null},(e,t)=>t instanceof Map?[...t.entries()]:t)};export class VariantFileSession{props;queue=new h(1,1/0);applied=new Map;baseline=new Map;contract;settled=!1;constructor(e){for(let t of(this.props=e,e.rawFiles.files))g(t)&&E(t.name)&&this.baseline.set(t.name,t.content);this.contract=R(e.rawFiles,e.logger)}static async create(e){await VariantFileSession.recover(e.projectRoot,e.logger);let t=await b({projectRoot:e.projectRoot,envs:{}});return new VariantFileSession({...e,rawFiles:t})}static async recover(e,t){let i=await $(n(e,j));if(null!==i){for(let a of k.parse(JSON.parse(i))){let i=await VariantFileSession.resolveFile(e,a.fileName),r=await $(i);if(r!==a.applied&&r!==a.original&&r!==a.previous){t.warn(M(a.fileName));continue}await C(i,a.original)}await r(n(e,j),{force:!0})}}static async resolveFile(e,t){if(!E(t))throw Error(`Cannot override ${t}: variants support frontend spec and TypeScript files only. Keep server code, dependencies, environment files and assets unchanged`);let a=await i(e),r=p(a,t),s=r;for(;;)try{let e=await i(s),r=l(a,e);if(".."===r||r.startsWith(`..${c}`))throw Error(`Cannot override ${t}: its symbolic link leaves the project`);if(e!==s)throw Error(`Cannot override ${t}: it uses a symbolic link. Variant edits require regular files so restoration preserves the original file`);break}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e;s=o(s)}return r}getFiles(){return[...this.baseline].map(([e,t])=>({fileName:e,content:t}))}apply(e){return this.queue.add(async()=>{if(this.settled)throw Error("This variant comparison has already ended");let t=new Map;for(let i of e){if(await VariantFileSession.resolveFile(this.props.projectRoot,i.fileName),t.has(i.fileName))throw Error(`Cannot apply variant: ${i.fileName} is specified twice`);t.set(i.fileName,i.content)}if(t.size>0){let e=this.props.rawFiles.files.filter(e=>!t.has(e.name));for(let[i,a]of t)null!==a&&e.push(w(i,a));if(R(f(e),this.props.logger)!==this.contract)throw Error("Cannot apply variant: it changes the model, schemas, data or deployment settings. Variants must need no server preparation")}await this.writeTarget(t,"refuse")})}finish(e){return this.queue.add(async()=>{this.settled||(e||await this.writeTarget(new Map,"keep"),await r(n(this.props.projectRoot,j),{force:!0}),this.settled=!0)})}async writeTarget(t,i){let a=new Set([...this.applied.keys(),...t.keys()]);if(0===a.size)return;let r=new Map;for(let e of a){let t=await VariantFileSession.resolveFile(this.props.projectRoot,e),a=this.applied.has(e)?this.applied.get(e):this.baseline.get(e)??null;if(await $(t)===a){r.set(e,t);continue}if("refuse"===i)throw Error(`Cannot switch variant: ${e} was edited outside the preview, and switching would overwrite that edit. Choose the option that is shown, or close the comparison with \`phoenix variants --close\`, which keeps the edit`);this.props.logger.warn(M(e))}let s=[...r.keys()].map(e=>({fileName:e,original:this.baseline.get(e)??null,previous:this.applied.has(e)?this.applied.get(e)??null:this.baseline.get(e)??null,applied:t.has(e)?t.get(e)??null:this.baseline.get(e)??null}));await e(n(this.props.projectRoot,".phoenix"),{recursive:!0}),await C(n(this.props.projectRoot,j),JSON.stringify(s));let o=new Map(this.applied);try{for(let e of s){let t=r.get(e.fileName);void 0!==t&&await C(t,e.applied)}}catch(e){for(let[e,t]of r)await C(t,o.has(e)?o.get(e)??null:this.baseline.get(e)??null);throw await C(n(this.props.projectRoot,j),JSON.stringify([...o].map(([e,t])=>({fileName:e,original:this.baseline.get(e)??null,applied:t})))),e}for(let[e,i]of(this.applied.clear(),t))this.applied.set(e,i);this.props.onFilesChanged(s.map(e=>({fileName:e.fileName,content:e.applied})))}}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { Observable } from 'rxjs';
|
|
2
|
+
import type { Logger } from '../utils/index.js';
|
|
3
|
+
import type { ApplicationSpecProjectWatcher } from './application-spec-project-watcher.js';
|
|
4
|
+
import type { PhoenixStore, VariantPreviewOption, VariantPreviewRequest, VariantPreviewResult } from './phoenix-store.js';
|
|
5
|
+
import { type VariantFileEdit } from './variant-file-session.js';
|
|
6
|
+
/** What a command asks the editor to show, and how long it waits for the answer. */
|
|
7
|
+
export interface VariantPreviewInput {
|
|
8
|
+
readonly title: string;
|
|
9
|
+
readonly description: string;
|
|
10
|
+
readonly variants: readonly VariantPreviewOption[];
|
|
11
|
+
readonly timeoutMs: number;
|
|
12
|
+
}
|
|
13
|
+
/** How a wait for the builder's answer ended. `waiting` leaves the comparison open. */
|
|
14
|
+
export type VariantPreviewOutcome = ({
|
|
15
|
+
readonly status: 'settled';
|
|
16
|
+
} & VariantPreviewResult) | {
|
|
17
|
+
readonly status: 'closed';
|
|
18
|
+
} | {
|
|
19
|
+
readonly status: 'waiting';
|
|
20
|
+
};
|
|
21
|
+
/** The files of one option, as the editor collected them from its script. */
|
|
22
|
+
export interface VariantFilesInput {
|
|
23
|
+
readonly requestId: string;
|
|
24
|
+
readonly choice: string | null;
|
|
25
|
+
readonly files: readonly VariantFileEdit[];
|
|
26
|
+
}
|
|
27
|
+
export interface VariantPreviewServiceProps {
|
|
28
|
+
readonly projectRoot: string;
|
|
29
|
+
}
|
|
30
|
+
export interface VariantPreviewServiceContext {
|
|
31
|
+
readonly store: PhoenixStore;
|
|
32
|
+
readonly logger: Logger;
|
|
33
|
+
readonly projectWatcher: Pick<ApplicationSpecProjectWatcher, 'suspend' | 'resume' | 'applyVariantFiles'>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Owns the variant comparison of a dev session: which one is open, the file session that rewrites and
|
|
37
|
+
* restores the source files for it, and the answer. Its state lives in the store; every operation that
|
|
38
|
+
* changes it runs one at a time.
|
|
39
|
+
*/
|
|
40
|
+
export declare class VariantPreviewService {
|
|
41
|
+
private readonly props;
|
|
42
|
+
private readonly context;
|
|
43
|
+
private readonly queue;
|
|
44
|
+
private readonly result$;
|
|
45
|
+
private readonly closed$;
|
|
46
|
+
private session;
|
|
47
|
+
private editors;
|
|
48
|
+
/**
|
|
49
|
+
* The comparison an editor has to show, or `null`. A subscriber counts as a connected editor, and gets
|
|
50
|
+
* the open comparison at once, so a reloaded browser tab shows it again.
|
|
51
|
+
*/
|
|
52
|
+
readonly request$: Observable<VariantPreviewRequest | null>;
|
|
53
|
+
constructor(props: VariantPreviewServiceProps, context: VariantPreviewServiceContext);
|
|
54
|
+
/** True while option edits may be in the source files, so nothing else should write or deploy them. */
|
|
55
|
+
get isOpen(): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Opens the comparison in the editor and waits for the builder's answer. A wait that times out leaves
|
|
58
|
+
* it open, and a later call with the same options attaches to it again.
|
|
59
|
+
*/
|
|
60
|
+
open(input: VariantPreviewInput): Promise<VariantPreviewOutcome>;
|
|
61
|
+
getBaseline(requestId: string): {
|
|
62
|
+
readonly files: readonly VariantFileEdit[];
|
|
63
|
+
readonly choice: string | null;
|
|
64
|
+
};
|
|
65
|
+
applyFiles(input: VariantFilesInput): Promise<void>;
|
|
66
|
+
submit(result: VariantPreviewResult): Promise<void>;
|
|
67
|
+
/** Closes whichever comparison is open without an answer, for a command that gives up on it. */
|
|
68
|
+
close(): Promise<{
|
|
69
|
+
readonly closed: boolean;
|
|
70
|
+
}>;
|
|
71
|
+
claim(requestId: string): void;
|
|
72
|
+
/** Restores the baseline when the dev session ends with a comparison still open. */
|
|
73
|
+
dispose(): Promise<void>;
|
|
74
|
+
private get state();
|
|
75
|
+
private setState;
|
|
76
|
+
/** Takes a comparison off the screen without an answer and ends the wait of the command that opened it. */
|
|
77
|
+
private forget;
|
|
78
|
+
private startSession;
|
|
79
|
+
private endSession;
|
|
80
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"promise-queue";import{Observable as t,Subject as s,distinctUntilChanged as i,filter as r,firstValueFrom as o,map as n,merge as a,of as h,timeout as l}from"rxjs";import{VariantFileSession as c}from"./variant-file-session.js";export class VariantPreviewService{props;context;queue=new e(1,1/0);result$=new s;closed$=new s;session=null;editors=0;request$=new t(e=>{this.editors+=1;let t=this.context.store.variantPreview$.pipe(n(e=>e.open),i()).subscribe(e);return()=>{this.editors-=1,t.unsubscribe()}});constructor(e,t){this.props=e,this.context=t}get isOpen(){return null!==this.session}async open(e){return(await this.queue.add(async()=>{let t=t=>JSON.stringify(t.variants)===JSON.stringify(e.variants),{open:s,unclaimed:i}=this.state;if(i&&t(i.request))return{outcome:Promise.resolve({status:"settled",...i.result})};if(0===this.editors)throw Error("No editor connected. Open the configurator in a browser");let c=s&&t(s)?s:{requestId:crypto.randomUUID(),title:e.title,description:e.description,variants:e.variants};if(c!==s)try{await this.endSession(!1),await this.startSession()}catch(e){throw this.forget(s),e}let u=o(a(this.result$.pipe(r(e=>e.requestId===c.requestId),n(e=>({status:"settled",...e}))),this.closed$.pipe(r(e=>e===c.requestId),n(()=>({status:"closed"})))).pipe(l({first:e.timeoutMs,with:()=>h({status:"waiting"})})));return c!==s&&(this.setState({open:c,activeChoice:null,unclaimed:null}),s&&this.closed$.next(s.requestId)),{outcome:u}})).outcome}getBaseline(e){if(this.state.open?.requestId!==e||!this.session)throw Error("This variant preview is no longer open");return{files:this.session.getFiles(),choice:this.state.activeChoice}}applyFiles(e){return this.queue.add(async()=>{let{open:t}=this.state;if(t?.requestId!==e.requestId||!this.session)throw Error("This variant preview is no longer open");let s=t.variants.find(t=>t.id===e.choice);if(null!==e.choice&&!s)throw Error("This option does not belong to the open variant preview");if(null===e.choice&&e.files.length>0)throw Error("The baseline cannot contain variant edits");if(s?.kind==="page"&&e.files.length>0)throw Error("HTML previews cannot override project files");await this.session.apply(e.files),this.setState({activeChoice:e.choice})})}submit(e){return this.queue.add(async()=>{let{open:t,activeChoice:s}=this.state;if(t?.requestId!==e.requestId)throw Error("This preview is no longer open. The agent closed it or replaced it with another one");if(!this.session||s!==e.choice||null!==e.choice&&!t.variants.some(t=>t.id===e.choice))throw Error("Apply this option before choosing it");await this.endSession(!0),this.setState({open:null,activeChoice:null,unclaimed:{request:t,result:e}}),this.result$.next(e)})}close(){return this.queue.add(async()=>{let{open:e}=this.state;try{await this.endSession(!1)}finally{this.forget(e)}return{closed:null!==e}})}claim(e){this.state.unclaimed?.result.requestId===e&&this.setState({unclaimed:null})}dispose(){return this.queue.add(()=>this.endSession(!1))}get state(){return this.context.store.variantPreview$.value}setState(e){this.context.store.variantPreview$.next({...this.state,...e})}forget(e){this.setState({open:null,activeChoice:null,unclaimed:null}),e&&this.closed$.next(e.requestId)}async startSession(){let{projectWatcher:e,logger:t}=this.context;e.suspend();try{this.session=await c.create({projectRoot:this.props.projectRoot,logger:t,onFilesChanged:t=>e.applyVariantFiles(t)})}catch(t){throw e.resume(),t}}async endSession(e){if(this.session)try{await this.session.finish(e)}finally{this.session=null,this.context.projectWatcher.resume()}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{lingui as e}from"@lingui/vite-plugin";import i from"@vitejs/plugin-react";import{mkdir as t,readFile as n,writeFile as r}from"fs/promises";import o from"lodash-es/camelCase.js";import{createRequire as a}from"node:module";import{dirname as s,resolve as m}from"path";import{createLogger as l}from"vite";import
|
|
1
|
+
import{lingui as e}from"@lingui/vite-plugin";import i from"@vitejs/plugin-react";import{mkdir as t,readFile as n,writeFile as r}from"fs/promises";import o from"lodash-es/camelCase.js";import{createRequire as a}from"node:module";import{dirname as s,resolve as m}from"path";import{createLogger as l}from"vite";import p from"vite-plugin-css-injected-by-js";import{isUsingLocalSdk as d}from"../utils/package-info.js";import{loadFrontendConfigModule as f}from"./frontend-config.js";import{phxBannerPlugin as c}from"./phx-banner-plugin.js";import{phxCspNoncePlugin as g}from"./phx-csp-nonce-plugin.js";import{phxGlobalIsolationPlugin as u}from"./phx-global-isolation-plugin.js";import{phxLicensesPlugin as h}from"./phx-licenses-plugin.js";import{phxVariantPreviewsPlugin as S}from"./phx-variant-previews-plugin.js";let b=null;export const setViteLogSink=(e,i={})=>{b={sink:e,echo:i.echo??!1}};let y=["react","react-dom","three","@react-three/fiber","@react-three/drei","@react-three/postprocessing","its-fine","@emotion/react","@emotion/styled","@mui/material","@mui/system","@tanstack/react-query","rxjs"],O=e=>{let i=e.DEPLOYMENT_ID;if("string"!=typeof i)throw Error("DEPLOYMENT_ID is required in runtime config");return i};export const getViteDevConfig=async t=>{var n,r;let o,p,c=d(),g=f(),h=g.readRuntimeConfig(),x=g.frontendBuildConfig,D=Object.fromEntries((t?.templateFiles??[]).map(e=>[e,`.phoenix/${e}`]));return{...b&&{customLogger:(n=b.sink,r=b.echo,o=l(),{get hasWarned(){return o.hasWarned},info:(e,i)=>{n("info",e),r&&o.info(e,i)},warn:(e,i)=>{n("warn",e),r&&o.warn(e,i)},warnOnce:(e,i)=>{n("warn",e),r&&o.warnOnce(e,i)},error:(e,i)=>{n("error",e),r&&o.error(e,i)},clearScreen:e=>{r&&o.clearScreen(e)},hasErrorLogged:e=>o.hasErrorLogged(e)}),...b.echo?{}:{clearScreen:!1}},mode:"development",optimizeDeps:{exclude:["@swc/wasm-web"],...c&&{entries:["index.html","admin.html",...t?.templateFiles??[]],force:!0}},...c&&{resolve:{alias:(p=a(m(process.cwd(),"package.json")),y.flatMap(e=>{try{let i=s(p.resolve(`${e}/package.json`));return[{find:RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(/|$)`),replacement:`${i}$1`}]}catch{return[]}}))}},plugins:[i({babel:{plugins:["macros"]}}),e(),{name:"vite:runtime-config",apply:(e,i)=>"build"===i.command||"development"===i.mode,config:e=>{let i=g.readRuntimeConfig(),t=g.frontendBuildConfig;return{...e,define:{...e.define,"phx.frontendEnv":JSON.stringify(i),"globalThis.PHX_SCHEMA_VALIDATOR":JSON.stringify(t.jsonSchemaValidator),"globalThis.PHX_GLTF_DECODER":JSON.stringify(t.gltfDecoder)}}}},u({getDeploymentId:()=>O(g.readRuntimeConfig())}),S()],define:{"process.env":{},"import.meta.env.DEV":!0,"import.meta.env.PROD":!1,"phx.frontendEnv":JSON.stringify(h),"globalThis.PHX_SCHEMA_VALIDATOR":JSON.stringify(x.jsonSchemaValidator),"globalThis.PHX_GLTF_DECODER":JSON.stringify(x.gltfDecoder)},build:{rollupOptions:{input:{index:".phoenix/index.html",admin:".phoenix/admin.html",...D}}},root:m(process.cwd(),"./.phoenix"),server:{watch:{ignored:["./**/*.{ts,tsx}","./.swc/**","../spec/**","../src/**"]}}}};export const getViteBuildConfigs=async a=>{let l=f(),d=l.readRuntimeConfig(),S=l.frontendBuildConfig,b=h(),y=c({sdkVersion:a.sdkVersion,banner:a.banner}),x=[{name:"salsita-configurator",entryFile:"./configurator.ts",mainScriptPath:"./configurator.ts",htmlFiles:["./index.html",...{templateFiles:a.templateFiles}.templateFiles],main:!0,format:"iife"},{name:"salsita-admin",entryFile:"./admin.ts",mainScriptPath:"./admin.ts",htmlFiles:["./admin.html"],main:!1,format:"iife"},{name:"salsita-embedded-admin",entryFile:"./embedded-admin.ts",mainScriptPath:"./embedded-admin.ts",htmlFiles:[],main:!1,format:"es"},{name:"salsita-embedded-configurator",entryFile:"./embedded-configurator.ts",mainScriptPath:"./embedded-configurator.ts",htmlFiles:[],main:!1,format:"es"}].map(f=>({plugins:[i({babel:{plugins:["macros"]}}),e(),p({useStrictCSP:!0}),g(),u({getDeploymentId:()=>O(l.readRuntimeConfig())}),{name:"vite:lib-index",writeBundle:async()=>{if(!f.htmlFiles.length)return;let e="iife"===f.format?`${f.name}.iife.js`:`${f.name}.js`;for(let i of f.htmlFiles){if(f.main&&a.enableEditor&&"./index.html"===i)continue;let o=m("./.phoenix",i),l=m("./.phoenix/dist/frontend",i);await t(s(l),{recursive:!0});let p=(await n(o,"utf-8")).replace(f.mainScriptPath,e);await r(l,p,"utf-8")}}},b,y],build:{outDir:"./dist/frontend",chunkSizeWarningLimit:4e3,lib:{entry:f.entryFile,name:o(f.name),formats:[f.format],fileName:()=>"iife"===f.format?`${f.name}.iife.js`:`${f.name}.js`},rollupOptions:{external:[],output:{assetFileNames:`${f.name}.[ext]`}},minify:!0,emptyOutDir:!1},root:m(process.cwd(),"./.phoenix"),define:{"process.env":{},"process.env.NODE_ENV":JSON.stringify("production"),"phx.frontendEnv":JSON.stringify(d),"globalThis.PHX_SCHEMA_VALIDATOR":JSON.stringify(S.jsonSchemaValidator),"globalThis.PHX_GLTF_DECODER":JSON.stringify(S.gltfDecoder)}}));return a.enableEditor?[...x,{plugins:[i({babel:{plugins:["macros"]}}),e(),p({useStrictCSP:!0}),g(),b,y],build:{outDir:"./dist/frontend",chunkSizeWarningLimit:4e3,rollupOptions:{external:[]},minify:!0,emptyOutDir:!1},root:m(process.cwd(),"./.phoenix"),define:{"process.env":{},"process.env.NODE_ENV":JSON.stringify("production"),"phx.frontendEnv":JSON.stringify(d),"globalThis.PHX_SCHEMA_VALIDATOR":JSON.stringify(S.jsonSchemaValidator),"globalThis.PHX_GLTF_DECODER":JSON.stringify(S.gltfDecoder)}}]:x};
|
|
@@ -13,8 +13,11 @@ export declare const getViewportSize: () => Size;
|
|
|
13
13
|
* Returns the viewport size. This can also be used as a dependency in a
|
|
14
14
|
* useEffect to trigger an update when the browser resizes.
|
|
15
15
|
*
|
|
16
|
+
* @param subscriptionActive if `false`, the viewport is neither measured nor followed, and the size
|
|
17
|
+
* returned is the last one measured, if any (useful for optimization)
|
|
18
|
+
*
|
|
16
19
|
* @see https://martijnhols.nl/gists/how-to-get-document-height-ios-safari-osk
|
|
17
20
|
* @todo: investigate if this can use `viewport$`
|
|
18
21
|
*/
|
|
19
|
-
export declare const useViewportSize: () => Size | undefined;
|
|
22
|
+
export declare const useViewportSize: (subscriptionActive?: boolean) => Size | undefined;
|
|
20
23
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as e,useEffect as i,useLayoutEffect as t,useState as n}from"react";let
|
|
1
|
+
import{useCallback as e,useEffect as i,useLayoutEffect as t,useState as n}from"react";let r="u">typeof window?t:()=>{};export const getViewportSize=()=>window.visualViewport?[window.visualViewport.width,window.visualViewport.height]:[window.innerWidth,window.innerHeight];export const useViewportSize=(t=!0)=>{let[o,w]=n(),d=e(()=>{let e=getViewportSize();w(i=>i&&i[0]===e[0]&&i[1]===e[1]?i:e)},[]);return r(()=>{t&&d()},[t,d]),i(()=>{if(!t)return;let e=()=>{d(),setTimeout(d,1e3)};return window.addEventListener("resize",e),window.addEventListener("orientationchange",e),window.visualViewport?.addEventListener("resize",e),()=>{window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e),window.visualViewport?.removeEventListener("resize",e)}},[t,d]),o};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@salsita-ai/sdk",
|
|
3
|
-
"version": "0.50.0-develop.
|
|
3
|
+
"version": "0.50.0-develop.aff4f8dd6d",
|
|
4
4
|
"description": "TypeScript SDK and CLI for building, running, and deploying Phoenix configurator applications.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"salsita",
|
|
@@ -221,7 +221,7 @@
|
|
|
221
221
|
"@swc/core": "1.15.40",
|
|
222
222
|
"@swc/wasm-web": "1.15.40",
|
|
223
223
|
"@tanstack/ai": "0.64.0",
|
|
224
|
-
"@tanstack/ai-
|
|
224
|
+
"@tanstack/ai-client": "0.36.1",
|
|
225
225
|
"@trpc/client": "11.17.0",
|
|
226
226
|
"@trpc/react-query": "11.17.0",
|
|
227
227
|
"@trpc/server": "11.17.0",
|
|
@@ -292,8 +292,8 @@
|
|
|
292
292
|
"yaml": "2.9.0",
|
|
293
293
|
"yargs": "17.7.2",
|
|
294
294
|
"zod": "3.25.76",
|
|
295
|
-
"@salsita-ai/common": "0.50.0-develop.
|
|
296
|
-
"@salsita-ai/contracts": "0.50.0-develop.
|
|
295
|
+
"@salsita-ai/common": "0.50.0-develop.aff4f8dd6d",
|
|
296
|
+
"@salsita-ai/contracts": "0.50.0-develop.aff4f8dd6d"
|
|
297
297
|
},
|
|
298
298
|
"devDependencies": {
|
|
299
299
|
"@clerk/clerk-react": "5.61.8",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { useAssistantChat, type AssistantChatState } from './use-assistant-chat.js';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{useAssistantChat}from"./use-assistant-chat.js";
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { type UIMessage } from '@tanstack/ai-react';
|
|
2
|
-
/** Assistant chat state and actions of the current configuration. */
|
|
3
|
-
export interface AssistantChatState {
|
|
4
|
-
/** The thread as painted: hydrated from the server, then streamed. */
|
|
5
|
-
readonly messages: ReadonlyArray<UIMessage>;
|
|
6
|
-
/** True while a reply streams or a browser tool runs. */
|
|
7
|
-
readonly isLoading: boolean;
|
|
8
|
-
readonly error: Error | undefined;
|
|
9
|
-
/**
|
|
10
|
-
* HTTP status of the latest request the server answered with a failure, for telling a refusal from
|
|
11
|
-
* a dropped connection when `error` is set. Nothing when the latest answered request succeeded or
|
|
12
|
-
* the server was never reached.
|
|
13
|
-
*/
|
|
14
|
-
readonly failedStatus: number | undefined;
|
|
15
|
-
/** False when the server said this session may read the thread but not add to it. */
|
|
16
|
-
readonly isContinuable: boolean;
|
|
17
|
-
/** False until the first request of the chat, the thread read, was answered or failed. */
|
|
18
|
-
readonly isLoaded: boolean;
|
|
19
|
-
/** Sends a user message stamped with its send time. */
|
|
20
|
-
readonly send: (content: string) => Promise<void>;
|
|
21
|
-
/** Stops the current reply in the browser and on the server. */
|
|
22
|
-
readonly stop: () => Promise<void>;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* The conversational assistant of the current configuration. The server owns the thread — the chat
|
|
26
|
-
* hydrates from it on mount and rejoins a reply still streaming — so the hook keeps nothing in
|
|
27
|
-
* browser storage. Each message carries its send time for the model. The model's `query` and
|
|
28
|
-
* `apply` calls run here, in the browser, against the configurator this hook is rendered in.
|
|
29
|
-
*/
|
|
30
|
-
export declare const useAssistantChat: () => AssistantChatState;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{fetchServerSentEvents as t,useChat as e}from"@tanstack/ai-react";import{useCallback as a,useMemo as n,useState as r}from"react";import{useApplicationRuntimeSelector as s,useAuthorizedClient as o,useConfigurationId as i,useLogger as c}from"#package/react-sdk";import{useConfigurator as l}from"../application-runtime/index.js";export const useAssistantChat=()=>{let u=i(),h=o(),d=c(),[p,m]=r(),[f,w]=r(!0),[y,g]=r(!1),C=a(()=>h.getAssistantChatConnection(u),[h,u]),k=n(()=>{let e=async(t,e)=>{let a=await fetch(t,e).finally(()=>g(!0)),n=a.headers.get("x-assistant-thread-continuable");return m(a.ok?void 0:a.status),null!=n&&w("false"!==n),a},a=async()=>({headers:await C().headers(),fetchClient:e}),n=t(()=>C().url,a),r=t(()=>`${C().url}/runs`,a);return{...n,joinRun:r.joinRun}},[C]),{assistantSystem:S}=l(),{messages:$,isLoading:j,error:x,sendMessage:A,stop:I,runId:R}=e({threadId:`assistant:${u}`,connection:k,persistence:!0,history:{pageSize:50},tools:s(S.getTools)}),v=a(async t=>{let e={sentAt:new Date().toISOString()};await A({content:t,metadata:e})},[A]),O=a(async()=>{if(I(),null!=R)try{let t=C();await fetch(`${t.url}/runs/${encodeURIComponent(R)}/cancel`,{method:"POST",headers:await t.headers()})}catch(t){d.warn("Could not cancel the assistant run on the server",{error:t})}},[C,d,R,I]);return n(()=>({messages:$,isLoading:j,error:x,failedStatus:p,isContinuable:f,isLoaded:y,send:v,stop:O}),[$,j,x,p,f,y,v,O])};
|