@jay-framework/stack-server-runtime 0.8.0 → 0.10.0

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 (3) hide show
  1. package/dist/index.d.ts +410 -6
  2. package/dist/index.js +800 -25
  3. package/package.json +11 -9
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { AnyJayStackComponentDefinition, PageProps, AnySlowlyRenderResult, UrlParams, JayStackComponentDefinition, AnyFastRenderResult, ServiceMarker } from '@jay-framework/fullstack-component';
1
+ import { AnyJayStackComponentDefinition, PageProps, AnySlowlyRenderResult, UrlParams, JayStackComponentDefinition, AnyFastRenderResult, HttpMethod, CacheOptions, JayAction, JayActionDefinition, ServiceMarker } from '@jay-framework/fullstack-component';
2
2
  import { JayComponentCore } from '@jay-framework/component';
3
3
  import { ViteDevServer } from 'vite';
4
4
  import { JayRoute } from '@jay-framework/stack-route-scanner';
5
5
  import { WithValidations } from '@jay-framework/compiler-shared';
6
6
  import { JayRollupConfig } from '@jay-framework/rollup-plugin';
7
+ import { TrackByMap } from '@jay-framework/view-state-merge';
7
8
 
8
9
  interface DevServerPagePart {
9
10
  compDefinition: AnyJayStackComponentDefinition;
@@ -11,7 +12,16 @@ interface DevServerPagePart {
11
12
  clientImport: string;
12
13
  clientPart: string;
13
14
  }
14
- declare function loadPageParts(vite: ViteDevServer, route: JayRoute, pagesBase: string, jayRollupConfig: JayRollupConfig): Promise<WithValidations<DevServerPagePart[]>>;
15
+ interface LoadedPageParts {
16
+ parts: DevServerPagePart[];
17
+ /** TrackBy map for server-side merge (slow → fast) */
18
+ serverTrackByMap?: Record<string, string>;
19
+ /** TrackBy map for client-side merge (fast → interactive) */
20
+ clientTrackByMap?: Record<string, string>;
21
+ /** NPM package names used on this page (for filtering plugin inits) */
22
+ usedPackages: Set<string>;
23
+ }
24
+ declare function loadPageParts(vite: ViteDevServer, route: JayRoute, pagesBase: string, projectBase: string, jayRollupConfig: JayRollupConfig): Promise<WithValidations<LoadedPageParts>>;
15
25
 
16
26
  interface SlowlyChangingPhase {
17
27
  runSlowlyForPage(pageParams: object, pageProps: PageProps, parts: Array<DevServerPagePart>): Promise<AnySlowlyRenderResult>;
@@ -21,12 +31,359 @@ declare class DevSlowlyChangingPhase implements SlowlyChangingPhase {
21
31
  constructor(dontCacheSlowly: boolean);
22
32
  runSlowlyForPage(pageParams: UrlParams, pageProps: PageProps, parts: Array<DevServerPagePart>): Promise<AnySlowlyRenderResult>;
23
33
  }
24
- declare function runLoadParams<StaticViewState extends object, ViewState extends object, Refs extends object, Services extends Array<any>, Contexts extends Array<any>, PropsT extends object, Params extends UrlParams, CompCore extends JayComponentCore<PropsT, ViewState>>(compDefinition: JayStackComponentDefinition<StaticViewState, ViewState, Refs, Services, Contexts, PropsT, Params, CompCore>, services: Services): Promise<void>;
25
- declare function runSlowlyChangingRender<StaticViewState extends object, ViewState extends object, Refs extends object, Services extends Array<any>, Contexts extends Array<any>, PropsT extends object, Params extends UrlParams, CompCore extends JayComponentCore<PropsT, ViewState>>(compDefinition: JayStackComponentDefinition<StaticViewState, ViewState, Refs, Services, Contexts, PropsT, Params, CompCore>): void;
34
+ declare function runLoadParams<Refs extends object, SlowVS extends object, FastVS extends object, InteractiveVS extends object, Services extends Array<any>, Contexts extends Array<any>, PropsT extends object, Params extends UrlParams, CompCore extends JayComponentCore<PropsT, InteractiveVS>>(compDefinition: JayStackComponentDefinition<Refs, SlowVS, FastVS, InteractiveVS, Services, Contexts, PropsT, Params, CompCore>, services: Services): Promise<void>;
35
+ declare function runSlowlyChangingRender<Refs extends object, SlowVS extends object, FastVS extends object, InteractiveVS extends object, Services extends Array<any>, Contexts extends Array<any>, PropsT extends object, Params extends UrlParams, CompCore extends JayComponentCore<PropsT, InteractiveVS>>(compDefinition: JayStackComponentDefinition<Refs, SlowVS, FastVS, InteractiveVS, Services, Contexts, PropsT, Params, CompCore>): void;
26
36
 
27
37
  declare function renderFastChangingData(pageParams: object, pageProps: PageProps, carryForward: object, parts: Array<DevServerPagePart>): Promise<AnyFastRenderResult>;
28
38
 
29
- declare function generateClientScript(defaultViewState: object, fastCarryForward: object, parts: DevServerPagePart[], jayHtmlPath: string): string;
39
+ /**
40
+ * Action registry for Jay Stack server-side action handling.
41
+ *
42
+ * Actions are registered at build/startup time and can be invoked via HTTP.
43
+ * The registry maps action names to their definitions (handler, services, method, etc.).
44
+ */
45
+
46
+ /**
47
+ * Registered action entry with resolved metadata.
48
+ */
49
+ interface RegisteredAction {
50
+ /** Unique action name */
51
+ actionName: string;
52
+ /** HTTP method */
53
+ method: HttpMethod;
54
+ /** Cache options (for GET requests) */
55
+ cacheOptions?: CacheOptions;
56
+ /** Service markers for dependency injection */
57
+ services: any[];
58
+ /** The handler function */
59
+ handler: (input: any, ...services: any[]) => Promise<any>;
60
+ }
61
+ /**
62
+ * Result of executing an action.
63
+ */
64
+ type ActionExecutionResult<T> = {
65
+ success: true;
66
+ data: T;
67
+ } | {
68
+ success: false;
69
+ error: ActionErrorResponse;
70
+ };
71
+ /**
72
+ * Error response structure for failed actions.
73
+ */
74
+ interface ActionErrorResponse {
75
+ code: string;
76
+ message: string;
77
+ isActionError: boolean;
78
+ }
79
+ /**
80
+ * Registry for Jay Stack server actions.
81
+ *
82
+ * Manages action registration, lookup, and execution.
83
+ * Create instances for testing or use the default export for production.
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * // For testing - create isolated instance
88
+ * const registry = new ActionRegistry();
89
+ * registry.register(myAction);
90
+ * const result = await registry.execute('my.action', input);
91
+ *
92
+ * // For production - use default instance
93
+ * import { actionRegistry } from '@jay-framework/stack-server-runtime';
94
+ * actionRegistry.register(myAction);
95
+ * ```
96
+ */
97
+ declare class ActionRegistry {
98
+ private readonly actions;
99
+ /**
100
+ * Registers an action with the registry.
101
+ *
102
+ * @param action - The JayAction to register (created via makeJayAction/makeJayQuery)
103
+ */
104
+ register<I, O, S extends any[]>(action: JayAction<I, O> & JayActionDefinition<I, O, S>): void;
105
+ /**
106
+ * Retrieves a registered action by name.
107
+ *
108
+ * @param actionName - The unique action name
109
+ * @returns The registered action or undefined
110
+ */
111
+ get(actionName: string): RegisteredAction | undefined;
112
+ /**
113
+ * Checks if an action is registered.
114
+ *
115
+ * @param actionName - The unique action name
116
+ * @returns true if the action is registered
117
+ */
118
+ has(actionName: string): boolean;
119
+ /**
120
+ * Gets all registered action names.
121
+ *
122
+ * @returns Array of registered action names
123
+ */
124
+ getNames(): string[];
125
+ /**
126
+ * Clears all registered actions.
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Executes a registered action with the given input.
131
+ * Resolves services and calls the handler.
132
+ *
133
+ * @param actionName - The action to execute
134
+ * @param input - The input data for the action
135
+ * @returns The action result or error
136
+ */
137
+ execute<T = any>(actionName: string, input: unknown): Promise<ActionExecutionResult<T>>;
138
+ /**
139
+ * Gets the cache headers for an action (if applicable).
140
+ *
141
+ * @param actionName - The action name
142
+ * @returns Cache-Control header value or undefined
143
+ */
144
+ getCacheHeaders(actionName: string): string | undefined;
145
+ }
146
+ /**
147
+ * Default action registry instance.
148
+ * Use this for production; create new instances for testing.
149
+ */
150
+ declare const actionRegistry: ActionRegistry;
151
+ /**
152
+ * Registers an action with the default registry.
153
+ * @deprecated Use actionRegistry.register() instead
154
+ */
155
+ declare function registerAction<I, O, S extends any[]>(action: JayAction<I, O> & JayActionDefinition<I, O, S>): void;
156
+ /**
157
+ * Retrieves a registered action by name from the default registry.
158
+ * @deprecated Use actionRegistry.get() instead
159
+ */
160
+ declare function getRegisteredAction(actionName: string): RegisteredAction | undefined;
161
+ /**
162
+ * Checks if an action is registered in the default registry.
163
+ * @deprecated Use actionRegistry.has() instead
164
+ */
165
+ declare function hasAction(actionName: string): boolean;
166
+ /**
167
+ * Gets all registered action names from the default registry.
168
+ * @deprecated Use actionRegistry.getNames() instead
169
+ */
170
+ declare function getRegisteredActionNames(): string[];
171
+ /**
172
+ * Clears all registered actions from the default registry.
173
+ * @deprecated Use actionRegistry.clear() instead
174
+ */
175
+ declare function clearActionRegistry(): void;
176
+ /**
177
+ * Executes an action from the default registry.
178
+ * @deprecated Use actionRegistry.execute() instead
179
+ */
180
+ declare function executeAction<T = any>(actionName: string, input: unknown): Promise<ActionExecutionResult<T>>;
181
+ /**
182
+ * Gets cache headers for an action from the default registry.
183
+ * @deprecated Use actionRegistry.getCacheHeaders() instead
184
+ */
185
+ declare function getActionCacheHeaders(actionName: string): string | undefined;
186
+
187
+ /**
188
+ * Action discovery and auto-registration for Jay Stack.
189
+ *
190
+ * Scans project and plugin directories to discover and register actions
191
+ * automatically on server startup.
192
+ */
193
+
194
+ /**
195
+ * Vite server interface for SSR module loading.
196
+ * Using a minimal interface to avoid direct Vite dependency.
197
+ */
198
+ interface ViteSSRLoader {
199
+ ssrLoadModule: (url: string) => Promise<Record<string, any>>;
200
+ }
201
+ /**
202
+ * Options for action discovery.
203
+ */
204
+ interface ActionDiscoveryOptions {
205
+ /** Project root directory */
206
+ projectRoot: string;
207
+ /** Custom actions directory (default: src/actions) */
208
+ actionsDir?: string;
209
+ /** Registry to register actions in (default: global actionRegistry) */
210
+ registry?: ActionRegistry;
211
+ /** Whether to log discovery progress */
212
+ verbose?: boolean;
213
+ /** Vite server for SSR module loading (required in dev for TypeScript files) */
214
+ viteServer?: ViteSSRLoader;
215
+ }
216
+ /**
217
+ * Result of action discovery.
218
+ */
219
+ interface ActionDiscoveryResult {
220
+ /** Number of actions discovered and registered */
221
+ actionCount: number;
222
+ /** Names of registered actions */
223
+ actionNames: string[];
224
+ /** Paths of scanned action files */
225
+ scannedFiles: string[];
226
+ }
227
+ /**
228
+ * Discovers and registers actions from the project's actions directory.
229
+ *
230
+ * Scans `src/actions/*.actions.ts` for exported actions and registers them.
231
+ *
232
+ * @param options - Discovery options
233
+ * @returns Result with discovered action information
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * // In dev-server startup
238
+ * const result = await discoverAndRegisterActions({
239
+ * projectRoot: process.cwd(),
240
+ * verbose: true,
241
+ * });
242
+ * console.log(`Registered ${result.actionCount} actions`);
243
+ * ```
244
+ */
245
+ declare function discoverAndRegisterActions(options: ActionDiscoveryOptions): Promise<ActionDiscoveryResult>;
246
+ /**
247
+ * Options for discovering plugin actions.
248
+ */
249
+ interface PluginActionDiscoveryOptions {
250
+ /** Project root directory */
251
+ projectRoot: string;
252
+ /** Registry to register actions in (default: global actionRegistry) */
253
+ registry?: ActionRegistry;
254
+ /** Whether to log discovery progress */
255
+ verbose?: boolean;
256
+ /** Vite server for SSR module loading (required in dev for TypeScript files) */
257
+ viteServer?: ViteSSRLoader;
258
+ }
259
+ /**
260
+ * Discovers and registers actions from all plugins in a project.
261
+ *
262
+ * Scans both local plugins (src/plugins/) and installed NPM plugins.
263
+ *
264
+ * @param options - Discovery options
265
+ * @returns Array of registered action names
266
+ */
267
+ declare function discoverAllPluginActions(options: PluginActionDiscoveryOptions): Promise<string[]>;
268
+ /**
269
+ * Discovers actions from a single plugin's plugin.yaml file.
270
+ *
271
+ * Reads plugin.yaml, finds the `actions` array, and imports those
272
+ * named exports from the plugin's module.
273
+ *
274
+ * @param pluginPath - Path to the plugin directory (containing plugin.yaml)
275
+ * @param projectRoot - Project root for resolving imports
276
+ * @param registry - Registry to register actions in
277
+ * @param verbose - Whether to log progress
278
+ * @returns Array of registered action names
279
+ */
280
+ declare function discoverPluginActions(pluginPath: string, projectRoot: string, registry?: ActionRegistry, verbose?: boolean, viteServer?: ViteSSRLoader): Promise<string[]>;
281
+
282
+ /**
283
+ * Plugin initialization discovery and execution for Jay Stack.
284
+ *
285
+ * Discovers plugins with init configurations (using makeJayInit pattern),
286
+ * sorts them by dependencies, and executes their init functions in order.
287
+ *
288
+ * Auto-discovers `lib/init.ts` files in plugins, or uses the path specified
289
+ * in `plugin.yaml` via the `init` property.
290
+ */
291
+
292
+ /**
293
+ * Information about a discovered plugin with init.
294
+ */
295
+ interface PluginWithInit {
296
+ /** Plugin name from plugin.yaml (used as default init key) */
297
+ name: string;
298
+ /** Plugin path (directory containing plugin.yaml) */
299
+ pluginPath: string;
300
+ /** Package name for NPM plugins, or path for local plugins */
301
+ packageName: string;
302
+ /** Whether this is a local plugin (src/plugins/) or NPM */
303
+ isLocal: boolean;
304
+ /**
305
+ * Init module path relative to plugin root.
306
+ * Default is 'lib/init' (auto-discovered).
307
+ * Can be overridden via `init` property in plugin.yaml.
308
+ */
309
+ initModule: string;
310
+ /**
311
+ * Export name for the init constant.
312
+ * Default is 'init'.
313
+ * Can be overridden via `init` property in plugin.yaml (for compiled packages).
314
+ */
315
+ initExport: string;
316
+ /** Dependencies from package.json (for ordering) */
317
+ dependencies: string[];
318
+ }
319
+ /**
320
+ * Options for plugin init discovery.
321
+ */
322
+ interface PluginInitDiscoveryOptions {
323
+ /** Project root directory */
324
+ projectRoot: string;
325
+ /** Whether to log discovery progress */
326
+ verbose?: boolean;
327
+ }
328
+ /**
329
+ * Discovers all plugins with init configurations.
330
+ *
331
+ * Auto-discovers `lib/init.ts` files in plugins, or uses the path specified
332
+ * in `plugin.yaml` via the `init` property.
333
+ *
334
+ * Scans both local plugins (src/plugins/) and NPM plugins (node_modules/).
335
+ */
336
+ declare function discoverPluginsWithInit(options: PluginInitDiscoveryOptions): Promise<PluginWithInit[]>;
337
+ /**
338
+ * Sorts plugins by their dependencies (topological sort).
339
+ * Plugins with no dependencies come first, then plugins that depend on them, etc.
340
+ */
341
+ declare function sortPluginsByDependencies(plugins: PluginWithInit[]): PluginWithInit[];
342
+ /**
343
+ * Executes server init for all plugins in order.
344
+ *
345
+ * Uses the `makeJayInit` pattern:
346
+ * - Loads the init module and finds the JayInit object
347
+ * - Calls `_serverInit()` if defined
348
+ * - Stores returned data via `setClientInitData(pluginName, data)`
349
+ *
350
+ * @param plugins - Sorted list of plugins with init
351
+ * @param viteServer - Vite server for SSR module loading (optional)
352
+ * @param verbose - Whether to log progress
353
+ */
354
+ declare function executePluginServerInits(plugins: PluginWithInit[], viteServer?: ViteSSRLoader, verbose?: boolean): Promise<void>;
355
+ /**
356
+ * Information needed to generate client init script for a plugin.
357
+ */
358
+ interface PluginClientInitInfo {
359
+ /** Plugin name (used for logging and as data key) */
360
+ name: string;
361
+ /** Import path for the init module */
362
+ importPath: string;
363
+ /** Export name for the JayInit constant */
364
+ initExport: string;
365
+ }
366
+ /**
367
+ * Prepares plugin information for client init script generation.
368
+ *
369
+ * For LOCAL plugins: Use the init file path directly
370
+ * For NPM plugins: Use the `/client` subpath (client bundle exports init)
371
+ *
372
+ * Filters to only plugins that have init modules and returns the
373
+ * information needed to generate client-side imports and execution.
374
+ */
375
+ declare function preparePluginClientInits(plugins: PluginWithInit[]): PluginClientInitInfo[];
376
+
377
+ /**
378
+ * Information needed to generate client init script for the project.
379
+ */
380
+ interface ProjectClientInitInfo {
381
+ /** Import path for the init module */
382
+ importPath: string;
383
+ /** Export name for the JayInit constant (default: 'init') */
384
+ initExport?: string;
385
+ }
386
+ declare function generateClientScript(defaultViewState: object, fastCarryForward: object, parts: DevServerPagePart[], jayHtmlPath: string, trackByMap?: TrackByMap, clientInitData?: Record<string, Record<string, any>>, projectInit?: ProjectClientInitInfo, pluginInits?: PluginClientInitInfo[]): string;
30
387
 
31
388
  /**
32
389
  * Service registry for Jay Stack server-side dependency injection.
@@ -144,5 +501,52 @@ declare function runShutdownCallbacks(): Promise<void>;
144
501
  * Internal API used by dev-server during hot reload.
145
502
  */
146
503
  declare function clearLifecycleCallbacks(): void;
504
+ /**
505
+ * Sets client init data for a specific namespace (plugin or project).
506
+ * Each namespace's data is kept separate and passed only to the matching
507
+ * client init callback.
508
+ *
509
+ * @param key - Namespace key (plugin name or 'project')
510
+ * @param data - Data object for this namespace
511
+ *
512
+ * @example
513
+ * ```typescript
514
+ * // In plugin server init
515
+ * onInit(async () => {
516
+ * setClientInitData('wix-stores', {
517
+ * currency: 'USD',
518
+ * apiEndpoint: process.env.STORES_API_URL,
519
+ * });
520
+ * });
521
+ *
522
+ * // In project jay.init.ts
523
+ * onInit(async () => {
524
+ * setClientInitData('project', {
525
+ * oauthClientId: process.env.OAUTH_CLIENT_ID,
526
+ * featureFlags: await loadFeatureFlags(),
527
+ * });
528
+ * });
529
+ * ```
530
+ */
531
+ declare function setClientInitData(key: string, data: Record<string, any>): void;
532
+ /**
533
+ * Gets all namespaced client init data.
534
+ * Internal API used by page rendering to embed data in HTML.
535
+ *
536
+ * @returns Object with namespace keys and their data
537
+ */
538
+ declare function getClientInitData(): Record<string, Record<string, any>>;
539
+ /**
540
+ * Gets client init data for a specific namespace.
541
+ *
542
+ * @param key - Namespace key
543
+ * @returns Data for that namespace, or empty object if not set
544
+ */
545
+ declare function getClientInitDataForKey(key: string): Record<string, any>;
546
+ /**
547
+ * Clears client init data.
548
+ * Internal API used by dev-server during hot reload.
549
+ */
550
+ declare function clearClientInitData(): void;
147
551
 
148
- export { DevSlowlyChangingPhase, type SlowlyChangingPhase, clearLifecycleCallbacks, clearServiceRegistry, generateClientScript, getService, hasService, loadPageParts, onInit, onShutdown, registerService, renderFastChangingData, resolveServices, runInitCallbacks, runLoadParams, runShutdownCallbacks, runSlowlyChangingRender };
552
+ export { type ActionDiscoveryOptions, type ActionDiscoveryResult, type ActionErrorResponse, type ActionExecutionResult, ActionRegistry, type DevServerPagePart, DevSlowlyChangingPhase, type LoadedPageParts, type PluginActionDiscoveryOptions, type PluginClientInitInfo, type PluginInitDiscoveryOptions, type PluginWithInit, type ProjectClientInitInfo, type RegisteredAction, type SlowlyChangingPhase, type ViteSSRLoader, actionRegistry, clearActionRegistry, clearClientInitData, clearLifecycleCallbacks, clearServiceRegistry, discoverAllPluginActions, discoverAndRegisterActions, discoverPluginActions, discoverPluginsWithInit, executeAction, executePluginServerInits, generateClientScript, getActionCacheHeaders, getClientInitData, getClientInitDataForKey, getRegisteredAction, getRegisteredActionNames, getService, hasAction, hasService, loadPageParts, onInit, onShutdown, preparePluginClientInits, registerAction, registerService, renderFastChangingData, resolveServices, runInitCallbacks, runLoadParams, runShutdownCallbacks, runSlowlyChangingRender, setClientInitData, sortPluginsByDependencies };