@ultrst-armada/kloks 1.8.0 → 1.9.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.
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "packageName": "@ultrst-armada/kloks",
4
- "version": "1.8.0",
5
- "sourceCommit": "d364f4fd5a705bea93c4fb0a93ff9740c1050f49",
4
+ "version": "1.9.0",
5
+ "sourceCommit": "b6205d2c4f27f354324b4029676d614418fae89d",
6
6
  "releaseWorkflow": "npm Release",
7
- "workflowRunId": "40208606705"
7
+ "workflowRunId": "40212539594"
8
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultrst-armada/kloks",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -3,7 +3,7 @@ import {
3
3
  BaseAccountProvider,
4
4
  LocalAccountProvider,
5
5
  PasswordHasher
6
- } from "../chunk-HT2SEDHD.js";
6
+ } from "../chunk-W6JNJD3Q.js";
7
7
  import {
8
8
  CanonicalAuthClient,
9
9
  RateLimiter,
@@ -11,7 +11,7 @@ import {
11
11
  createCanonicalAuthClient,
12
12
  loginSystemUser,
13
13
  resolveUserFromToken
14
- } from "../chunk-M4GSR46Y.js";
14
+ } from "../chunk-WTBAG4AV.js";
15
15
  export {
16
16
  AdminGuard,
17
17
  BaseAccountProvider,
@@ -1,10 +1,16 @@
1
+ import {
2
+ workspaceGraphService
3
+ } from "./chunk-VKSGYMAH.js";
1
4
  import {
2
5
  getSrklAccounts,
3
6
  srklListBackblazeBuckets
4
7
  } from "./chunk-XHADDA75.js";
5
8
  import {
6
- workspaceGraphService
7
- } from "./chunk-5RXXC6GE.js";
9
+ StorageAdapterFactory
10
+ } from "./chunk-SHZAQTIT.js";
11
+ import {
12
+ b2ListBuckets
13
+ } from "./chunk-4QEMALXF.js";
8
14
  import {
9
15
  formatCanonicalWorkspaceFolderName,
10
16
  sanitizeWorkspaceName
@@ -19,18 +25,12 @@ import {
19
25
  import {
20
26
  queryUnifiedDb
21
27
  } from "./chunk-VAFCR2MS.js";
22
- import {
23
- b2ListBuckets
24
- } from "./chunk-4QEMALXF.js";
25
- import {
26
- StorageAdapterFactory
27
- } from "./chunk-SHZAQTIT.js";
28
28
  import {
29
29
  RateLimiter,
30
30
  SessionManager,
31
31
  loginSystemUser,
32
32
  resolveUserFromToken
33
- } from "./chunk-M4GSR46Y.js";
33
+ } from "./chunk-WTBAG4AV.js";
34
34
  import {
35
35
  createService,
36
36
  createServiceDefinition
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  RateLimiter,
3
3
  SessionManager
4
- } from "./chunk-M4GSR46Y.js";
4
+ } from "./chunk-WTBAG4AV.js";
5
5
 
6
6
  // src/auth/PasswordHasher.ts
7
7
  var bcrypt = null;
@@ -180,9 +180,11 @@ async function resolveUserFromToken(tokenOrUserId, _queryDb, env) {
180
180
  if (!tokenOrUserId) return null;
181
181
  try {
182
182
  const client = createCanonicalAuthClient(requireAuthBaseUrl(env));
183
- const session = await client.getSession(
184
- tokenOrUserId.startsWith("Bearer ") ? `better-auth.session_token=${tokenOrUserId.slice(7).trim()}` : void 0
185
- );
183
+ const credential = tokenOrUserId.trim();
184
+ if (!credential) return null;
185
+ const token = credential.replace(/^Bearer[ \t]+/i, "").trim();
186
+ if (!token) return null;
187
+ const session = await client.getSession(`better-auth.session_token=${token}`);
186
188
  if (!session?.user) return null;
187
189
  return {
188
190
  ...session.user,
@@ -765,6 +765,7 @@ declare function buildProjectObservability(projects: any[], deployments: any[],
765
765
  fastDataTransferFormatted: string;
766
766
  middlewareInvocations: number;
767
767
  middlewareInvocationsFormatted: string;
768
+ latestDeploymentId: any;
768
769
  latestDeploymentUrl: string;
769
770
  latestDeploymentStatus: string;
770
771
  latestDeploymentCreatedAt: string;
@@ -780,8 +781,46 @@ declare function buildProjectsList(observability: any[]): {
780
781
  domain: any;
781
782
  domains: any;
782
783
  updatedAt: any;
784
+ deploymentId: any;
783
785
  }[];
784
786
 
787
+ /**
788
+ * Provider deployment-control operations.
789
+ *
790
+ * Vercel: pauses/resumes a project's production service.
791
+ * Cloudflare Pages: disables/enables automatic production and preview deployments.
792
+ */
793
+ type CloudflarePagesPreviewSetting = 'all' | 'none' | 'custom';
794
+ interface CloudflarePagesPauseState {
795
+ productionDeploymentsEnabled: boolean;
796
+ previewDeploymentSetting: CloudflarePagesPreviewSetting;
797
+ }
798
+ interface DeploymentControlResult {
799
+ success: true;
800
+ provider: 'VERCEL' | 'CLOUDFLARE';
801
+ projectId: string;
802
+ controlState: 'ACTIVE' | 'PAUSED';
803
+ pauseState?: CloudflarePagesPauseState;
804
+ }
805
+ interface CredentialPayload {
806
+ token?: string;
807
+ apiToken?: string;
808
+ accessToken?: string;
809
+ teamId?: string;
810
+ accountId?: string;
811
+ cfAccountId?: string;
812
+ accountTag?: string;
813
+ authKey?: string;
814
+ globalApiKey?: string;
815
+ authEmail?: string;
816
+ email?: string;
817
+ credentials?: Record<string, any>;
818
+ }
819
+ declare function pauseVercelProject(projectId: string, payload?: CredentialPayload, userId?: string, env?: Record<string, unknown>): Promise<DeploymentControlResult>;
820
+ declare function resumeVercelProject(projectId: string, payload?: CredentialPayload, userId?: string, env?: Record<string, unknown>): Promise<DeploymentControlResult>;
821
+ declare function pauseCloudflarePagesProject(projectName: string, payload?: CredentialPayload, userId?: string, env?: Record<string, unknown>): Promise<DeploymentControlResult>;
822
+ declare function resumeCloudflarePagesProject(projectName: string, pauseState: CloudflarePagesPauseState, payload?: CredentialPayload, userId?: string, env?: Record<string, unknown>): Promise<DeploymentControlResult>;
823
+
785
824
  declare function createWavBuffer(sampleRate: number, numChannels: number, samples: Float32Array[]): Buffer;
786
825
 
787
826
  declare function ensureGlobalSamples(globalSamplesDir: string): Promise<void>;
@@ -1638,4 +1677,4 @@ declare function resolveSystemDatabaseUrl(env?: Record<string, string | undefine
1638
1677
  */
1639
1678
  declare function tryResolveSystemDatabaseUrl(env?: Record<string, string | undefined>): string | null;
1640
1679
 
1641
- export { type AssetChannelType, type AssetDataType, type AssetFolderInfo, type AssetPoolItem, type AssetPoolScope, type B2AuthData, type BackendFacade, BaseDataProvider, BaseResourceFetcher, type CloudflareObservability, type CloudflareProjectItem, CloudflareResourceFetcher, type CloudflareUsageMetrics, type CredentialEntry, type CredentialManifest, type Deployment, type FunctionSet, FunctionalityTable, GRAPHS_ROOT, type IDataProvider, LEGACY_PROJECTS_ROOT, type OrchestrationFn, PROJECTS_ROOT, type ProjectMetadata, type PublicRouteRecord, type QueryFilter, ResourceFetcherRegistry, type Runtime, SAMPLES_GLOBAL_ROOT, SUPPORTED_AUDIO_EXTS, SUPPORTED_MIDI_EXTS, type ServerAudioSampleItem, type ServiceFacade, type ServiceRegistryRecord, type SortOrder, type SrklB2Account, SrklStorageService, type SyncFileResult, type UnifiedQueryResult, type UnifiedResourceMetricItem, type UnifiedResourceMetrics, VercelResourceFetcher, WORKSPACE_ASSETS_ROOT, WORKSPACE_ROOT, type WorkingWorkspaceConfig, type WorkspaceFolderResolution, type WorkspaceStorageConfig, b2DeleteFileVersion, b2DeleteFolder, buildProjectObservability, buildProjectsList, cleanDbUrl, computeDeploymentFinalWeight, computeUsageWeightScore, configureStarterProjectTemplate, createAssetSubfolder, createCredential, createGraphAssetFolder, createGraphAssetFolder as createGraphAssetSubfolder, createGraphPackage, createWavBuffer, createWorkspace, createWorkspaceGraph, decryptSecretFromBlob, deleteAssetFromGraph, deleteAssetFromPool, deleteCredential, deleteGlobalSample, deleteGraphPackage, deleteProject, deleteProjectSample, deleteRoute, deleteWorkspace, deleteWorkspaceFile, deleteWorkspaceFolder, deleteWorkspaceGraph, encryptSecretToBlob, ensureAssetPoolDirectories, ensureGlobalSamples, ensureGraphAssetDirectories, ensureProjectAssets, ensureProjectsRoot, ensureWorkspaceStructure, exportEncryptedCredentials, fetchCloudflareData, fetchVercelData, findUserWorkspace, findWorkspaceRecord, formatRelativeCreated, getAllRoutes, getAssetPoolLocationPath, getAssetPoolPublicUrl, getB2BucketId, getConnectedDeploymentNode, getConnectedWeightModifiers, getCredential, getDefaultWorkingWorkspaceDir, getExecutions, getGatewayConfig, getGraphPackageById, getPrimarySrklDeploymentUrl as getPrimarySrklCoreDeploymentUrl, getProjectById, getPublicRouteByPath, getPublicRoutes, getSrklAccounts as getSrklCoreAccounts, getSrklStatus, getUnifiedDbUrl, getUsers, getWeightModifierScore, getWorkingWorkspaceConfig, getWorkingWorkspaceDir, getWorkspaceFolderKey, getWorkspaceFolderPrefix, getWorkspaceGraph, getWorkspaceStorageDetails, getWorkspaces, importEncryptedCredentials, importGraphDependency, initGlobalSamplesDirectory, isB2Workspace, listAllGraphPackages, listAllProjects, listBackblazeBuckets, listCredentials, listGlobalSamples, listProjectSamples, listWorkspaceFiles, listWorkspaceGraphs, loadCredentialManifest, loadWorkspaceData, loginUser, matchGatewayIngress, matchGatewayIngressAsync, queryUnifiedDb, readWorkspaceFile, recordExecution, removeGraphDependency, renameAppInWorkspaceData, resolveDynamicRouteFromDb, resolveSystemDatabaseUrl, resolveWorkspaceConnection, resolveWorkspaceDir, saveAssetToGraph, saveAssetToPool, saveCredentialManifest, saveGlobalSample, saveGraphPackage, saveProject, saveProjectSample, saveWorkspaceData, saveWorkspaceGraph, scanAssetPool, scanGraphAssets, seedDefaultAssets, seedStarterGraphAssets, serverPublicRoutes, setServerPublicRoutes, setWorkingWorkspaceConfig, srklListBackblazeBuckets as srklCoreListBackblazeBuckets, syncWorkspace, syncWorkspaceCreateToBucket, syncWorkspaceDataToBucket, syncWorkspaceDeleteToBucket, tryResolveSystemDatabaseUrl, updateCredential, updateWorkspace, upsertRoute, validateServiceDefinition, writeWorkspaceFile };
1680
+ export { type AssetChannelType, type AssetDataType, type AssetFolderInfo, type AssetPoolItem, type AssetPoolScope, type B2AuthData, type BackendFacade, BaseDataProvider, BaseResourceFetcher, type CloudflareObservability, type CloudflarePagesPauseState, type CloudflarePagesPreviewSetting, type CloudflareProjectItem, CloudflareResourceFetcher, type CloudflareUsageMetrics, type CredentialEntry, type CredentialManifest, type Deployment, type DeploymentControlResult, type FunctionSet, FunctionalityTable, GRAPHS_ROOT, type IDataProvider, LEGACY_PROJECTS_ROOT, type OrchestrationFn, PROJECTS_ROOT, type ProjectMetadata, type PublicRouteRecord, type QueryFilter, ResourceFetcherRegistry, type Runtime, SAMPLES_GLOBAL_ROOT, SUPPORTED_AUDIO_EXTS, SUPPORTED_MIDI_EXTS, type ServerAudioSampleItem, type ServiceFacade, type ServiceRegistryRecord, type SortOrder, type SrklB2Account, SrklStorageService, type SyncFileResult, type UnifiedQueryResult, type UnifiedResourceMetricItem, type UnifiedResourceMetrics, VercelResourceFetcher, WORKSPACE_ASSETS_ROOT, WORKSPACE_ROOT, type WorkingWorkspaceConfig, type WorkspaceFolderResolution, type WorkspaceStorageConfig, b2DeleteFileVersion, b2DeleteFolder, buildProjectObservability, buildProjectsList, cleanDbUrl, computeDeploymentFinalWeight, computeUsageWeightScore, configureStarterProjectTemplate, createAssetSubfolder, createCredential, createGraphAssetFolder, createGraphAssetFolder as createGraphAssetSubfolder, createGraphPackage, createWavBuffer, createWorkspace, createWorkspaceGraph, decryptSecretFromBlob, deleteAssetFromGraph, deleteAssetFromPool, deleteCredential, deleteGlobalSample, deleteGraphPackage, deleteProject, deleteProjectSample, deleteRoute, deleteWorkspace, deleteWorkspaceFile, deleteWorkspaceFolder, deleteWorkspaceGraph, encryptSecretToBlob, ensureAssetPoolDirectories, ensureGlobalSamples, ensureGraphAssetDirectories, ensureProjectAssets, ensureProjectsRoot, ensureWorkspaceStructure, exportEncryptedCredentials, fetchCloudflareData, fetchVercelData, findUserWorkspace, findWorkspaceRecord, formatRelativeCreated, getAllRoutes, getAssetPoolLocationPath, getAssetPoolPublicUrl, getB2BucketId, getConnectedDeploymentNode, getConnectedWeightModifiers, getCredential, getDefaultWorkingWorkspaceDir, getExecutions, getGatewayConfig, getGraphPackageById, getPrimarySrklDeploymentUrl as getPrimarySrklCoreDeploymentUrl, getProjectById, getPublicRouteByPath, getPublicRoutes, getSrklAccounts as getSrklCoreAccounts, getSrklStatus, getUnifiedDbUrl, getUsers, getWeightModifierScore, getWorkingWorkspaceConfig, getWorkingWorkspaceDir, getWorkspaceFolderKey, getWorkspaceFolderPrefix, getWorkspaceGraph, getWorkspaceStorageDetails, getWorkspaces, importEncryptedCredentials, importGraphDependency, initGlobalSamplesDirectory, isB2Workspace, listAllGraphPackages, listAllProjects, listBackblazeBuckets, listCredentials, listGlobalSamples, listProjectSamples, listWorkspaceFiles, listWorkspaceGraphs, loadCredentialManifest, loadWorkspaceData, loginUser, matchGatewayIngress, matchGatewayIngressAsync, pauseCloudflarePagesProject, pauseVercelProject, queryUnifiedDb, readWorkspaceFile, recordExecution, removeGraphDependency, renameAppInWorkspaceData, resolveDynamicRouteFromDb, resolveSystemDatabaseUrl, resolveWorkspaceConnection, resolveWorkspaceDir, resumeCloudflarePagesProject, resumeVercelProject, saveAssetToGraph, saveAssetToPool, saveCredentialManifest, saveGlobalSample, saveGraphPackage, saveProject, saveProjectSample, saveWorkspaceData, saveWorkspaceGraph, scanAssetPool, scanGraphAssets, seedDefaultAssets, seedStarterGraphAssets, serverPublicRoutes, setServerPublicRoutes, setWorkingWorkspaceConfig, srklListBackblazeBuckets as srklCoreListBackblazeBuckets, syncWorkspace, syncWorkspaceCreateToBucket, syncWorkspaceDataToBucket, syncWorkspaceDeleteToBucket, tryResolveSystemDatabaseUrl, updateCredential, updateWorkspace, upsertRoute, validateServiceDefinition, writeWorkspaceFile };
@@ -1,3 +1,17 @@
1
+ import {
2
+ CompositeBackend,
3
+ EndpointGenerator,
4
+ LOCAL_STORAGE_GRAPHS_PREFIX,
5
+ NodeGraphPersistenceService,
6
+ createBackend,
7
+ createCompositeService,
8
+ createLocalService,
9
+ createRemoteService,
10
+ exportGraphAsJsonFile,
11
+ nodeGraphPersistence,
12
+ parseGraphJsonFile,
13
+ validateGraphDocument
14
+ } from "./chunk-RBF2OGMC.js";
1
15
  import {
2
16
  CANONICAL_SRKL_URL,
3
17
  SrklClient,
@@ -17,19 +31,8 @@ import {
17
31
  useSrklServices
18
32
  } from "./chunk-3IUA66RS.js";
19
33
  import {
20
- CompositeBackend,
21
- EndpointGenerator,
22
- LOCAL_STORAGE_GRAPHS_PREFIX,
23
- NodeGraphPersistenceService,
24
- createBackend,
25
- createCompositeService,
26
- createLocalService,
27
- createRemoteService,
28
- exportGraphAsJsonFile,
29
- nodeGraphPersistence,
30
- parseGraphJsonFile,
31
- validateGraphDocument
32
- } from "./chunk-RBF2OGMC.js";
34
+ S3Adapter
35
+ } from "./chunk-RBQ4CW3T.js";
33
36
  import {
34
37
  RemoteWorkspaceService,
35
38
  SyncEngine,
@@ -46,9 +49,6 @@ import {
46
49
  syncWorkspace,
47
50
  workingWorkspaceService
48
51
  } from "./chunk-BTMIK44G.js";
49
- import {
50
- S3Adapter
51
- } from "./chunk-RBQ4CW3T.js";
52
52
  import {
53
53
  AuthServiceDefinition,
54
54
  AuthServiceFacade,
@@ -82,15 +82,35 @@ import {
82
82
  krnlWorkspaceGraphServiceFacade,
83
83
  krnlWorkspaceServiceDefinition,
84
84
  krnlWorkspaceServiceFacade
85
- } from "./chunk-BPFZCDS4.js";
85
+ } from "./chunk-UMEO6XS4.js";
86
+ import {
87
+ workspaceGraphService
88
+ } from "./chunk-VKSGYMAH.js";
86
89
  import {
87
90
  getPrimarySrklDeploymentUrl,
88
91
  getSrklAccounts,
89
92
  srklListBackblazeBuckets
90
93
  } from "./chunk-XHADDA75.js";
91
94
  import {
92
- workspaceGraphService
93
- } from "./chunk-5RXXC6GE.js";
95
+ BackblazeB2Adapter,
96
+ LocalFSAdapter,
97
+ StorageAdapterFactory,
98
+ SupabaseStorageAdapter,
99
+ ensureS3DirectoryMarker,
100
+ isSecretMasked,
101
+ normalizeBackblazeCredentials,
102
+ permanentDeleteS3Folder,
103
+ permanentDeleteS3Object,
104
+ renameS3Folder,
105
+ resolveBackblazeEndpoint
106
+ } from "./chunk-SHZAQTIT.js";
107
+ import {
108
+ authorizeB2,
109
+ b2DownloadFile,
110
+ b2ListBuckets,
111
+ b2ListFileNames,
112
+ b2UploadFile
113
+ } from "./chunk-4QEMALXF.js";
94
114
  import {
95
115
  formatCanonicalWorkspaceFolderName,
96
116
  sanitizeWorkspaceName
@@ -125,26 +145,6 @@ import {
125
145
  getUnifiedDbUrl,
126
146
  queryUnifiedDb
127
147
  } from "./chunk-VAFCR2MS.js";
128
- import {
129
- authorizeB2,
130
- b2DownloadFile,
131
- b2ListBuckets,
132
- b2ListFileNames,
133
- b2UploadFile
134
- } from "./chunk-4QEMALXF.js";
135
- import {
136
- BackblazeB2Adapter,
137
- LocalFSAdapter,
138
- StorageAdapterFactory,
139
- SupabaseStorageAdapter,
140
- ensureS3DirectoryMarker,
141
- isSecretMasked,
142
- normalizeBackblazeCredentials,
143
- permanentDeleteS3Folder,
144
- permanentDeleteS3Object,
145
- renameS3Folder,
146
- resolveBackblazeEndpoint
147
- } from "./chunk-SHZAQTIT.js";
148
148
  import {
149
149
  BaseStorageAdapter,
150
150
  GoogleDriveAdapter,
@@ -163,7 +163,7 @@ import {
163
163
  BaseAccountProvider,
164
164
  LocalAccountProvider,
165
165
  PasswordHasher
166
- } from "./chunk-HT2SEDHD.js";
166
+ } from "./chunk-W6JNJD3Q.js";
167
167
  import {
168
168
  CanonicalAuthClient,
169
169
  RateLimiter,
@@ -171,7 +171,7 @@ import {
171
171
  createCanonicalAuthClient,
172
172
  loginSystemUser,
173
173
  resolveUserFromToken
174
- } from "./chunk-M4GSR46Y.js";
174
+ } from "./chunk-WTBAG4AV.js";
175
175
  import {
176
176
  BackendProvider,
177
177
  useBackend,
@@ -2058,6 +2058,8 @@ async function fetchCloudflareData(payload, rawUserId, env) {
2058
2058
  id: p.name || p.id,
2059
2059
  name: p.name,
2060
2060
  type: "PAGES_PROJECT",
2061
+ providerProjectId: p.id,
2062
+ providerDeploymentId: p.latest_deployment?.id,
2061
2063
  status: p.latest_deployment?.status || "READY",
2062
2064
  framework: "Cloudflare Pages",
2063
2065
  domain: pDomain,
@@ -2192,6 +2194,7 @@ function buildProjectObservability(projects, deployments, user) {
2192
2194
  fastDataTransferFormatted: "100 MB",
2193
2195
  middlewareInvocations: 10,
2194
2196
  middlewareInvocationsFormatted: "10",
2197
+ latestDeploymentId: latestDep?.id,
2195
2198
  latestDeploymentUrl: `https://${cleanDeploymentUrl}`,
2196
2199
  latestDeploymentStatus: displayStatus,
2197
2200
  latestDeploymentCreatedAt: new Date(createdAtTime).toISOString(),
@@ -2209,7 +2212,8 @@ function buildProjectsList(observability) {
2209
2212
  url: po.latestDeploymentUrl,
2210
2213
  domain: po.domains && po.domains[0] || `${po.projectName}.vercel.app`,
2211
2214
  domains: po.domains || [`${po.projectName}.vercel.app`],
2212
- updatedAt: po.latestDeploymentCreatedAt
2215
+ updatedAt: po.latestDeploymentCreatedAt,
2216
+ deploymentId: po.latestDeploymentId
2213
2217
  }));
2214
2218
  }
2215
2219
 
@@ -2378,6 +2382,142 @@ async function fetchVercelData(payload, rawUserId, env) {
2378
2382
  }
2379
2383
  }
2380
2384
 
2385
+ // src/core/deploymentControlCore.ts
2386
+ function firstString(...values) {
2387
+ return values.find((value) => typeof value === "string" && value.trim().length > 0)?.trim() || "";
2388
+ }
2389
+ async function resolveVercelCredentials(payload, userId, env) {
2390
+ const credentials = payload.credentials || {};
2391
+ let token = firstString(payload.token, payload.apiToken, payload.accessToken, credentials.token, credentials.apiToken, credentials.accessToken);
2392
+ let teamId = firstString(payload.teamId, credentials.teamId);
2393
+ if ((!token || !teamId) && userId && (payload.accountId || credentials.accountId)) {
2394
+ const accountId = firstString(payload.accountId, credentials.accountId);
2395
+ const srkl = await getSrklAccounts2(userId, "vercel", env);
2396
+ const account = srkl.accounts?.find((item) => item.id === accountId);
2397
+ const accountCredentials = account?.credentials || account?.metadata?.credentials || {};
2398
+ token ||= firstString(accountCredentials.token, accountCredentials.apiToken, accountCredentials.accessToken);
2399
+ teamId ||= firstString(accountCredentials.teamId);
2400
+ }
2401
+ if (!token) throw new Error("Vercel API token is missing or not configured for this account.");
2402
+ return { token, teamId };
2403
+ }
2404
+ async function resolveCloudflareCredentials(payload, userId, env) {
2405
+ const credentials = payload.credentials || {};
2406
+ let token = firstString(payload.token, payload.apiToken, payload.accessToken, credentials.token, credentials.apiToken, credentials.accessToken);
2407
+ let accountId = firstString(payload.accountId, payload.cfAccountId, payload.accountTag, credentials.accountId, credentials.cfAccountId, credentials.accountTag);
2408
+ let authKey = firstString(payload.authKey, payload.globalApiKey, credentials.authKey, credentials.globalApiKey);
2409
+ let authEmail = firstString(payload.authEmail, payload.email, credentials.authEmail, credentials.email);
2410
+ if (!token && !authKey || !accountId) {
2411
+ const requestedAccountId = firstString(payload.accountId, credentials.accountId);
2412
+ if (userId && requestedAccountId) {
2413
+ const srkl = await getSrklAccounts2(userId, "cloudflare", env);
2414
+ const account = srkl.accounts?.find((item) => item.id === requestedAccountId);
2415
+ const accountCredentials = account?.credentials || account?.metadata?.credentials || {};
2416
+ token ||= firstString(accountCredentials.token, accountCredentials.apiToken, accountCredentials.accessToken);
2417
+ accountId ||= firstString(accountCredentials.accountId, accountCredentials.cfAccountId, accountCredentials.accountTag);
2418
+ authKey ||= firstString(accountCredentials.authKey, accountCredentials.globalApiKey);
2419
+ authEmail ||= firstString(accountCredentials.authEmail, accountCredentials.email);
2420
+ }
2421
+ }
2422
+ if (!token && !authKey) throw new Error("Cloudflare API Token or Global API Key required.");
2423
+ if (!accountId) throw new Error("Cloudflare Account ID is required.");
2424
+ return { token, accountId, authKey, authEmail };
2425
+ }
2426
+ function cloudflareHeaders(token, authKey, authEmail) {
2427
+ const headers = { "Content-Type": "application/json", "User-Agent": "Kloks-DeploymentControl/1.0" };
2428
+ if (token) headers.Authorization = `Bearer ${token}`;
2429
+ else {
2430
+ headers["X-Auth-Key"] = authKey;
2431
+ headers["X-Auth-Email"] = authEmail;
2432
+ }
2433
+ return headers;
2434
+ }
2435
+ async function assertOk(response, provider) {
2436
+ if (response.ok) return;
2437
+ const body = await response.json().catch(() => ({}));
2438
+ const message = body?.error?.message || body?.errors?.[0]?.message || body?.message || response.statusText;
2439
+ throw new Error(`${provider} API error (${response.status}): ${message}`);
2440
+ }
2441
+ async function pauseVercelProject(projectId, payload = {}, userId, env) {
2442
+ if (!projectId?.trim()) throw new Error("Vercel project ID is required.");
2443
+ const { token, teamId } = await resolveVercelCredentials(payload, userId, env);
2444
+ const query = teamId ? `?teamId=${encodeURIComponent(teamId)}` : "";
2445
+ const response = await fetch(`https://api.vercel.com/v1/projects/${encodeURIComponent(projectId)}/pause${query}`, {
2446
+ method: "POST",
2447
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
2448
+ });
2449
+ await assertOk(response, "Vercel");
2450
+ return { success: true, provider: "VERCEL", projectId, controlState: "PAUSED" };
2451
+ }
2452
+ async function resumeVercelProject(projectId, payload = {}, userId, env) {
2453
+ if (!projectId?.trim()) throw new Error("Vercel project ID is required.");
2454
+ const { token, teamId } = await resolveVercelCredentials(payload, userId, env);
2455
+ const query = teamId ? `?teamId=${encodeURIComponent(teamId)}` : "";
2456
+ const response = await fetch(`https://api.vercel.com/v1/projects/${encodeURIComponent(projectId)}/unpause${query}`, {
2457
+ method: "POST",
2458
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
2459
+ });
2460
+ await assertOk(response, "Vercel");
2461
+ return { success: true, provider: "VERCEL", projectId, controlState: "ACTIVE" };
2462
+ }
2463
+ async function pauseCloudflarePagesProject(projectName, payload = {}, userId, env) {
2464
+ if (!projectName?.trim()) throw new Error("Cloudflare Pages project name is required.");
2465
+ const { token, accountId, authKey, authEmail } = await resolveCloudflareCredentials(payload, userId, env);
2466
+ const base = `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}`;
2467
+ const currentResponse = await fetch(base, { headers: cloudflareHeaders(token, authKey, authEmail) });
2468
+ await assertOk(currentResponse, "Cloudflare");
2469
+ const current = await currentResponse.json();
2470
+ const config = current?.result?.source?.config;
2471
+ if (!config) throw new Error("Cloudflare Pages project has no source deployment configuration to pause.");
2472
+ const pauseState = {
2473
+ productionDeploymentsEnabled: config.production_deployments_enabled !== false,
2474
+ previewDeploymentSetting: config.preview_deployment_setting || "all"
2475
+ };
2476
+ const updateResponse = await fetch(base, {
2477
+ method: "PATCH",
2478
+ headers: cloudflareHeaders(token, authKey, authEmail),
2479
+ body: JSON.stringify({
2480
+ source: {
2481
+ type: current?.result?.source?.type,
2482
+ config: {
2483
+ ...config,
2484
+ production_deployments_enabled: false,
2485
+ preview_deployment_setting: "none"
2486
+ }
2487
+ }
2488
+ })
2489
+ });
2490
+ await assertOk(updateResponse, "Cloudflare");
2491
+ return { success: true, provider: "CLOUDFLARE", projectId: projectName, controlState: "PAUSED", pauseState };
2492
+ }
2493
+ async function resumeCloudflarePagesProject(projectName, pauseState, payload = {}, userId, env) {
2494
+ if (!projectName?.trim()) throw new Error("Cloudflare Pages project name is required.");
2495
+ if (!pauseState) throw new Error("Cloudflare Pages pause state is required to resume safely.");
2496
+ const { token, accountId, authKey, authEmail } = await resolveCloudflareCredentials(payload, userId, env);
2497
+ const base = `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/pages/projects/${encodeURIComponent(projectName)}`;
2498
+ const currentResponse = await fetch(base, { headers: cloudflareHeaders(token, authKey, authEmail) });
2499
+ await assertOk(currentResponse, "Cloudflare");
2500
+ const current = await currentResponse.json();
2501
+ const config = current?.result?.source?.config;
2502
+ if (!config) throw new Error("Cloudflare Pages project has no source deployment configuration to resume.");
2503
+ const updateResponse = await fetch(base, {
2504
+ method: "PATCH",
2505
+ headers: cloudflareHeaders(token, authKey, authEmail),
2506
+ body: JSON.stringify({
2507
+ source: {
2508
+ type: current?.result?.source?.type,
2509
+ config: {
2510
+ ...config,
2511
+ production_deployments_enabled: pauseState.productionDeploymentsEnabled,
2512
+ preview_deployment_setting: pauseState.previewDeploymentSetting
2513
+ }
2514
+ }
2515
+ })
2516
+ });
2517
+ await assertOk(updateResponse, "Cloudflare");
2518
+ return { success: true, provider: "CLOUDFLARE", projectId: projectName, controlState: "ACTIVE" };
2519
+ }
2520
+
2381
2521
  // src/server/wavHelper.ts
2382
2522
  function createWavBuffer(sampleRate, numChannels, samples) {
2383
2523
  const numSamples = samples[0].length;
@@ -4430,6 +4570,8 @@ export {
4430
4570
  nodeGraphPersistence,
4431
4571
  normalizeBackblazeCredentials,
4432
4572
  parseGraphJsonFile,
4573
+ pauseCloudflarePagesProject,
4574
+ pauseVercelProject,
4433
4575
  permanentDeleteS3Folder,
4434
4576
  permanentDeleteS3Object,
4435
4577
  queryUnifiedDb,
@@ -4448,6 +4590,8 @@ export {
4448
4590
  resolveUserFromToken,
4449
4591
  resolveWorkspaceConnection,
4450
4592
  resolveWorkspaceDir,
4593
+ resumeCloudflarePagesProject,
4594
+ resumeVercelProject,
4451
4595
  sanitizeWorkspaceName,
4452
4596
  saveAssetToGraph,
4453
4597
  saveAssetToPool,
@@ -31,16 +31,16 @@ import {
31
31
  krnlWorkspaceGraphServiceFacade,
32
32
  krnlWorkspaceServiceDefinition,
33
33
  krnlWorkspaceServiceFacade
34
- } from "./chunk-BPFZCDS4.js";
34
+ } from "./chunk-UMEO6XS4.js";
35
+ import "./chunk-VKSGYMAH.js";
35
36
  import "./chunk-XHADDA75.js";
36
- import "./chunk-5RXXC6GE.js";
37
+ import "./chunk-SHZAQTIT.js";
38
+ import "./chunk-4QEMALXF.js";
37
39
  import "./chunk-FZKBTF34.js";
38
40
  import "./chunk-6K75XXFD.js";
39
41
  import "./chunk-VAFCR2MS.js";
40
- import "./chunk-4QEMALXF.js";
41
- import "./chunk-SHZAQTIT.js";
42
42
  import "./chunk-KKRWZDMN.js";
43
- import "./chunk-M4GSR46Y.js";
43
+ import "./chunk-WTBAG4AV.js";
44
44
  import "./chunk-TY32TUNI.js";
45
45
  export {
46
46
  AuthServiceDefinition,
@@ -14,10 +14,10 @@ import {
14
14
  } from "../chunk-RBF2OGMC.js";
15
15
  import {
16
16
  workspaceGraphService
17
- } from "../chunk-5RXXC6GE.js";
17
+ } from "../chunk-VKSGYMAH.js";
18
+ import "../chunk-SHZAQTIT.js";
18
19
  import "../chunk-6K75XXFD.js";
19
20
  import "../chunk-VAFCR2MS.js";
20
- import "../chunk-SHZAQTIT.js";
21
21
  import "../chunk-KKRWZDMN.js";
22
22
  import "../chunk-TY32TUNI.js";
23
23
  export {
@@ -16,8 +16,8 @@ import {
16
16
  getSrklAccounts,
17
17
  srklListBackblazeBuckets
18
18
  } from "../chunk-XHADDA75.js";
19
- import "../chunk-VAFCR2MS.js";
20
19
  import "../chunk-4QEMALXF.js";
20
+ import "../chunk-VAFCR2MS.js";
21
21
  export {
22
22
  CANONICAL_SRKL_URL,
23
23
  SrklClient,
@@ -1,13 +1,6 @@
1
1
  import {
2
2
  S3Adapter
3
3
  } from "../chunk-RBQ4CW3T.js";
4
- import {
5
- authorizeB2,
6
- b2DownloadFile,
7
- b2ListBuckets,
8
- b2ListFileNames,
9
- b2UploadFile
10
- } from "../chunk-4QEMALXF.js";
11
4
  import {
12
5
  BackblazeB2Adapter,
13
6
  LocalFSAdapter,
@@ -21,6 +14,13 @@ import {
21
14
  renameS3Folder,
22
15
  resolveBackblazeEndpoint
23
16
  } from "../chunk-SHZAQTIT.js";
17
+ import {
18
+ authorizeB2,
19
+ b2DownloadFile,
20
+ b2ListBuckets,
21
+ b2ListFileNames,
22
+ b2UploadFile
23
+ } from "../chunk-4QEMALXF.js";
24
24
  import {
25
25
  BaseStorageAdapter,
26
26
  GoogleDriveAdapter,
@@ -575,6 +575,111 @@ interface ServiceUISchema {
575
575
  operationBindings: OperationBinding[];
576
576
  }
577
577
 
578
+ type MonacoDiagnosticSeverity = 'error' | 'warning' | 'info' | 'hint';
579
+ interface MonacoDiagnostic {
580
+ message: string;
581
+ severity: MonacoDiagnosticSeverity;
582
+ startLineNumber: number;
583
+ startColumn: number;
584
+ endLineNumber: number;
585
+ endColumn: number;
586
+ code?: string;
587
+ }
588
+ interface MonacoDocument {
589
+ uri: string;
590
+ language: string;
591
+ value: string;
592
+ version: number;
593
+ diagnostics: MonacoDiagnostic[];
594
+ }
595
+ interface MonacoEditorOptions {
596
+ readOnly?: boolean;
597
+ minimap?: boolean;
598
+ fontSize?: number;
599
+ wordWrap?: 'off' | 'on' | 'wordWrapColumn' | 'bounded';
600
+ }
601
+ interface MonacoIdeSession {
602
+ sessionId: string;
603
+ document: MonacoDocument;
604
+ options: MonacoEditorOptions;
605
+ createdAt: number;
606
+ updatedAt: number;
607
+ }
608
+ interface MonacoCreateSessionInput {
609
+ sessionId?: string;
610
+ uri: string;
611
+ language: string;
612
+ value: string;
613
+ options?: MonacoEditorOptions;
614
+ }
615
+ interface MonacoUpdateDocumentInput {
616
+ sessionId: string;
617
+ value: string;
618
+ language?: string;
619
+ }
620
+
621
+ type UIAuthoringContext = 'service' | 'general-component' | 'application';
622
+ type UIAuthoringNodeKind = 'page' | 'section' | 'component';
623
+ interface UIAuthoringNode {
624
+ id: string;
625
+ kind: UIAuthoringNodeKind;
626
+ name: string;
627
+ componentId?: string;
628
+ assetRef?: AssetRef;
629
+ parentId?: string;
630
+ props: Record<string, string | number | boolean>;
631
+ }
632
+ interface UIAuthoringBinding {
633
+ componentId: string;
634
+ property: string;
635
+ target: {
636
+ kind: 'api-input';
637
+ apiId: string;
638
+ field: string;
639
+ fieldType: string;
640
+ } | {
641
+ kind: 'api-output';
642
+ apiId: string;
643
+ field: string;
644
+ fieldType: string;
645
+ };
646
+ }
647
+ interface UIAuthoringOperation {
648
+ operationId: string;
649
+ name: string;
650
+ description?: string;
651
+ inputFields?: Array<{
652
+ name: string;
653
+ type: string;
654
+ }>;
655
+ outputFields?: Array<{
656
+ name: string;
657
+ type: string;
658
+ }>;
659
+ }
660
+ interface UIAuthoringSession {
661
+ sessionId: string;
662
+ context: UIAuthoringContext;
663
+ nodes: UIAuthoringNode[];
664
+ bindings: UIAuthoringBinding[];
665
+ operations: UIAuthoringOperation[];
666
+ metadata: Record<string, string>;
667
+ }
668
+ interface UIAuthoringCreateInput {
669
+ sessionId?: string;
670
+ context: UIAuthoringContext;
671
+ operations?: UIAuthoringOperation[];
672
+ metadata?: Record<string, string>;
673
+ }
674
+ interface UIAuthoringValidation {
675
+ valid: boolean;
676
+ errors: string[];
677
+ warnings: string[];
678
+ }
679
+ declare const UI_AUTHORING_SCHEMA_VERSION = "1.0.0";
680
+ declare function suggestUIComponent(fieldType: string): string;
681
+ declare function buildServiceUISchema(session: UIAuthoringSession): ServiceUISchema;
682
+
578
683
  declare const KLOKS_CANONICAL_CONTRACT: {
579
684
  package: string;
580
685
  version: string;
@@ -594,4 +699,4 @@ declare const KLOKS_CANONICAL_CONTRACT: {
594
699
  validateCompatibility: (consumerSymbols?: string[]) => CompatibilityCheckResult;
595
700
  };
596
701
 
597
- export { type AssetRef, type AudioBusConfig, AudioBusConfigSchema, type AudioHardwareState, AudioHardwareStateSchema, type BackendOperation, BackendOperationSchema, type CompatibilityCheckResult, type ComponentDescriptor, type ContractDiffResult, type ContractSnapshot, ContractSnapshotSchema, type ExportSymbolEntry, type GraphEntityMetadata, GraphEntityMetadataSchema, KLOKS_CANONICAL_CONTRACT, KLOKS_PUBLIC_SURFACE, type MidiCommandType, MidiCommandTypeSchema, type MidiEventPayload, MidiEventPayloadSchema, type NodeDimensions2D, NodeDimensions2DSchema, type NodeHeaderStyle, NodeHeaderStyleSchema, type NodeScreenRect2D, NodeScreenRect2DSchema, type OperationBinding, type PageDescriptor, type PublicContractDefinition, PublicContractDefinitionSchema, QWNSR_REQUIRED_SURFACE, type SectionDescriptor, type ServiceUISchema, type SocketDirection, SocketDirectionSchema, type SocketGeometryConfig, SocketGeometryConfigSchema, type SocketPosition2D, SocketPosition2DSchema, type SocketStyleConfig, SocketStyleConfigSchema, type UIRequirementMode, type WireAnimationConfig, WireAnimationConfigSchema, type WireCurveStyle, WireCurveStyleSchema, type WireEndpoint2D, WireEndpoint2DSchema, type WireVisualConfig, WireVisualConfigSchema, createKloksSnapshot, diffContractSnapshots, validateConsumerSurfaceCompatibility };
702
+ export { type AssetRef, type AudioBusConfig, AudioBusConfigSchema, type AudioHardwareState, AudioHardwareStateSchema, type BackendOperation, BackendOperationSchema, type CompatibilityCheckResult, type ComponentDescriptor, type ContractDiffResult, type ContractSnapshot, ContractSnapshotSchema, type ExportSymbolEntry, type GraphEntityMetadata, GraphEntityMetadataSchema, KLOKS_CANONICAL_CONTRACT, KLOKS_PUBLIC_SURFACE, type MidiCommandType, MidiCommandTypeSchema, type MidiEventPayload, MidiEventPayloadSchema, type MonacoCreateSessionInput, type MonacoDiagnostic, type MonacoDiagnosticSeverity, type MonacoDocument, type MonacoEditorOptions, type MonacoIdeSession, type MonacoUpdateDocumentInput, type NodeDimensions2D, NodeDimensions2DSchema, type NodeHeaderStyle, NodeHeaderStyleSchema, type NodeScreenRect2D, NodeScreenRect2DSchema, type OperationBinding, type PageDescriptor, type PublicContractDefinition, PublicContractDefinitionSchema, QWNSR_REQUIRED_SURFACE, type SectionDescriptor, type ServiceUISchema, type SocketDirection, SocketDirectionSchema, type SocketGeometryConfig, SocketGeometryConfigSchema, type SocketPosition2D, SocketPosition2DSchema, type SocketStyleConfig, SocketStyleConfigSchema, type UIAuthoringBinding, type UIAuthoringContext, type UIAuthoringCreateInput, type UIAuthoringNode, type UIAuthoringNodeKind, type UIAuthoringOperation, type UIAuthoringSession, type UIAuthoringValidation, type UIRequirementMode, UI_AUTHORING_SCHEMA_VERSION, type WireAnimationConfig, WireAnimationConfigSchema, type WireCurveStyle, WireCurveStyleSchema, type WireEndpoint2D, WireEndpoint2DSchema, type WireVisualConfig, WireVisualConfigSchema, buildServiceUISchema, createKloksSnapshot, diffContractSnapshots, suggestUIComponent, validateConsumerSurfaceCompatibility };
@@ -381,6 +381,64 @@ function diffContractSnapshots(previous, current) {
381
381
  };
382
382
  }
383
383
 
384
+ // src/uiAuthoringSchema.ts
385
+ var UI_AUTHORING_SCHEMA_VERSION = "1.0.0";
386
+ function suggestUIComponent(fieldType) {
387
+ const normalized = fieldType.toLowerCase();
388
+ if (normalized === "email") return "TextInput.email";
389
+ if (normalized === "password") return "TextInput.password";
390
+ if (normalized === "boolean" || normalized === "bool") return "ToggleInput";
391
+ if (normalized === "number" || normalized === "integer" || normalized === "float") return "NumberInput";
392
+ if (normalized.includes("date")) return "DateInput";
393
+ return "TextInput";
394
+ }
395
+ function buildServiceUISchema(session) {
396
+ if (session.context !== "service") throw new Error("Service UI schema generation requires service context.");
397
+ const pages = session.nodes.filter((node) => node.kind === "page");
398
+ const sections = session.nodes.filter((node) => node.kind === "section");
399
+ const components = session.nodes.filter((node) => node.kind === "component");
400
+ const assetRefs = components.map((node) => node.assetRef).filter(Boolean);
401
+ return {
402
+ schemaId: `kloks.authored-ui.${session.sessionId}`,
403
+ schemaVersion: UI_AUTHORING_SCHEMA_VERSION,
404
+ serviceId: session.metadata.serviceId || "unknown-service",
405
+ requirementMode: "optional",
406
+ pages: pages.map((page) => ({
407
+ name: page.name,
408
+ sections: sections.filter((section) => section.parentId === page.id).map((section) => ({
409
+ name: section.name,
410
+ assetRef: section.assetRef,
411
+ components: components.filter((component) => component.parentId === section.id).map((component) => ({
412
+ name: component.name,
413
+ assetRef: component.assetRef,
414
+ description: component.props.description
415
+ })),
416
+ description: section.props.description
417
+ })),
418
+ description: page.props.description
419
+ })),
420
+ sections: sections.map((section) => ({
421
+ name: section.name,
422
+ assetRef: section.assetRef,
423
+ components: components.filter((component) => component.parentId === section.id).map((component) => ({
424
+ name: component.name,
425
+ assetRef: component.assetRef
426
+ })),
427
+ description: section.props.description
428
+ })),
429
+ components: components.map((component) => ({
430
+ name: component.name,
431
+ assetRef: component.assetRef,
432
+ description: component.props.description
433
+ })),
434
+ assetRefs,
435
+ operationBindings: session.bindings.map((binding) => ({
436
+ operationId: binding.target.apiId,
437
+ uiPath: binding.componentId
438
+ }))
439
+ };
440
+ }
441
+
384
442
  // src/index.ts
385
443
  var KLOKS_CANONICAL_CONTRACT = {
386
444
  package: "@ultrst-armada/kloks",
@@ -407,11 +465,14 @@ export {
407
465
  SocketGeometryConfigSchema,
408
466
  SocketPosition2DSchema,
409
467
  SocketStyleConfigSchema,
468
+ UI_AUTHORING_SCHEMA_VERSION,
410
469
  WireAnimationConfigSchema,
411
470
  WireCurveStyleSchema,
412
471
  WireEndpoint2DSchema,
413
472
  WireVisualConfigSchema,
473
+ buildServiceUISchema,
414
474
  createKloksSnapshot,
415
475
  diffContractSnapshots,
476
+ suggestUIComponent,
416
477
  validateConsumerSurfaceCompatibility
417
478
  };
@@ -3,7 +3,7 @@ import { ServiceDefinition, IService, EndpointDescriptor, ProtocolAdapter } from
3
3
  import { AdminDatabaseClusterConfig, DatabaseConnectionEntry, UserStorageConnection, AuthState, UserAccount, UserRole, UserWorkspaceRecord } from '@ultrst-armada/kloks/state-graph';
4
4
  export { AuthState, UserAccount, UserRole, UserSession, UserStorageConnection, UserWorkspaceRecord } from '@ultrst-armada/kloks/state-graph';
5
5
  import * as _kloks_contracts from '@ultrst-armada/kloks/contracts';
6
- import { ServiceUISchema } from '@ultrst-armada/kloks/contracts';
6
+ import { ServiceUISchema, MonacoIdeSession, UIAuthoringSession } from '@ultrst-armada/kloks/contracts';
7
7
 
8
8
  interface SystemEnvironmentStatus {
9
9
  databaseUrlConfigured: boolean;
@@ -276,6 +276,40 @@ declare const StorageServiceUISchema: ServiceUISchema;
276
276
 
277
277
  declare const SystemDbServiceUISchema: ServiceUISchema;
278
278
 
279
+ interface MonacoState extends Record<string, unknown> {
280
+ sessions: Record<string, MonacoIdeSession>;
281
+ }
282
+ declare const MonacoIdeServiceDefinition: ServiceDefinition<MonacoState>;
283
+ declare function createMonacoIdeService(): IService<MonacoState>;
284
+ declare const MonacoIdeServiceFacade: {
285
+ id: string;
286
+ name: string;
287
+ version: string;
288
+ runtime: "client";
289
+ deployment: "local";
290
+ definition: ServiceDefinition<MonacoState, Record<string, unknown>>;
291
+ service: IService<MonacoState, Record<string, unknown>>;
292
+ createInstance: typeof createMonacoIdeService;
293
+ execute: <TIn = unknown, TOut = unknown>(operation: string, input?: TIn) => Promise<TOut>;
294
+ };
295
+
296
+ interface UIAuthoringState extends Record<string, unknown> {
297
+ sessions: Record<string, UIAuthoringSession>;
298
+ }
299
+ declare const UIAuthoringServiceDefinition: ServiceDefinition<UIAuthoringState>;
300
+ declare function createUIAuthoringService(): IService<UIAuthoringState>;
301
+ declare const UIAuthoringServiceFacade: {
302
+ id: string;
303
+ name: string;
304
+ version: string;
305
+ runtime: "client";
306
+ deployment: "local";
307
+ definition: ServiceDefinition<UIAuthoringState, Record<string, unknown>>;
308
+ service: IService<UIAuthoringState, Record<string, unknown>>;
309
+ createInstance: typeof createUIAuthoringService;
310
+ execute: <TIn = unknown, TOut = unknown>(operation: string, input?: TIn) => Promise<TOut>;
311
+ };
312
+
279
313
  declare const AuthClientServiceDefinition: ServiceDefinition;
280
314
  declare const AuthClientServiceFacade: {
281
315
  id: string;
@@ -417,4 +451,4 @@ declare const krnlServiceDDefinition: ServiceDefinition<Record<string, unknown>,
417
451
  declare const krnlServiceDFacade: ServiceFacade<Record<string, unknown>, Record<string, unknown>>;
418
452
  declare const krnlExposeServiceD: typeof exposeServiceD;
419
453
 
420
- export { AuthClientServiceDefinition, AuthClientServiceFacade, type AuthListener, AuthService, AuthServiceUISchema, CLEAN_DATABASE_CLUSTER, type CounterState, DEFAULT_CONNECTIONS, type IAuthStore, type MathInput, type ProtocolExposureHandle, STORAGE_KEY_CONNECTIONS, ServiceADefinition, ServiceAFacade, ServiceBDefinition, ServiceBFacade, ServiceCDefinition, ServiceCFacade, ServiceDDefinition, ServiceDFacade, type ServiceFacade, StorageClientServiceDefinition, StorageClientServiceFacade, StorageService, StorageServiceUISchema, SystemDbClientServiceDefinition, SystemDbClientServiceFacade, SystemDbService, SystemDbServiceUISchema, type SystemEnvironmentStatus, type SystemTelemetry, type TelemetryEvents, authService, clearSession, createServiceB, createServiceC, createWorkspace, deleteWorkspace, exposeServiceD, fetchWorkspaces, krnlAuthClientServiceDefinition, krnlAuthClientServiceFacade, krnlCreateServiceB, krnlCreateServiceC, krnlExposeServiceD, krnlServiceADefinition, krnlServiceAFacade, krnlServiceBDefinition, krnlServiceBFacade, krnlServiceCDefinition, krnlServiceCFacade, krnlServiceDDefinition, krnlServiceDFacade, krnlStorageClientServiceDefinition, krnlStorageClientServiceFacade, krnlSystemDbClientServiceDefinition, krnlSystemDbClientServiceFacade, loadDatabase, loginAdmin, loginUser, persistDatabase, register, restoreSession, setActiveWorkspace, setSession, storageService, systemDbService, updateWorkspace, verifyPassword };
454
+ export { AuthClientServiceDefinition, AuthClientServiceFacade, type AuthListener, AuthService, AuthServiceUISchema, CLEAN_DATABASE_CLUSTER, type CounterState, DEFAULT_CONNECTIONS, type IAuthStore, type MathInput, MonacoIdeServiceDefinition, MonacoIdeServiceFacade, type ProtocolExposureHandle, STORAGE_KEY_CONNECTIONS, ServiceADefinition, ServiceAFacade, ServiceBDefinition, ServiceBFacade, ServiceCDefinition, ServiceCFacade, ServiceDDefinition, ServiceDFacade, type ServiceFacade, StorageClientServiceDefinition, StorageClientServiceFacade, StorageService, StorageServiceUISchema, SystemDbClientServiceDefinition, SystemDbClientServiceFacade, SystemDbService, SystemDbServiceUISchema, type SystemEnvironmentStatus, type SystemTelemetry, type TelemetryEvents, UIAuthoringServiceDefinition, UIAuthoringServiceFacade, authService, clearSession, createMonacoIdeService, createServiceB, createServiceC, createUIAuthoringService, createWorkspace, deleteWorkspace, exposeServiceD, fetchWorkspaces, krnlAuthClientServiceDefinition, krnlAuthClientServiceFacade, krnlCreateServiceB, krnlCreateServiceC, krnlExposeServiceD, krnlServiceADefinition, krnlServiceAFacade, krnlServiceBDefinition, krnlServiceBFacade, krnlServiceCDefinition, krnlServiceCFacade, krnlServiceDDefinition, krnlServiceDFacade, krnlStorageClientServiceDefinition, krnlStorageClientServiceFacade, krnlSystemDbClientServiceDefinition, krnlSystemDbClientServiceFacade, loadDatabase, loginAdmin, loginUser, persistDatabase, register, restoreSession, setActiveWorkspace, setSession, storageService, systemDbService, updateWorkspace, verifyPassword };
@@ -1651,6 +1651,251 @@ var StorageService = class {
1651
1651
  };
1652
1652
  var storageService = new StorageService();
1653
1653
 
1654
+ // src/client-services/monacoIdeService.ts
1655
+ var activeMonacoService;
1656
+ var MonacoIdeServiceDefinition = createServiceDefinition({
1657
+ id: "kloks.service.monacoIde",
1658
+ name: "MonacoIdeService",
1659
+ version: "1.0.0",
1660
+ state: { initial: { sessions: {} } },
1661
+ operations: {
1662
+ createSession: {
1663
+ id: "MonacoIdeService.createSession",
1664
+ name: "createSession",
1665
+ handler: async (input, ctx) => {
1666
+ const sessionId = input.sessionId || `monaco-${Date.now().toString(36)}`;
1667
+ const now = Date.now();
1668
+ const session = {
1669
+ sessionId,
1670
+ document: { uri: input.uri, language: input.language, value: input.value, version: 1, diagnostics: [] },
1671
+ options: input.options || {},
1672
+ createdAt: now,
1673
+ updatedAt: now
1674
+ };
1675
+ activeMonacoService.setState({ sessions: { ...activeMonacoService.getState().sessions, [sessionId]: session } });
1676
+ return session;
1677
+ }
1678
+ },
1679
+ updateDocument: {
1680
+ id: "MonacoIdeService.updateDocument",
1681
+ name: "updateDocument",
1682
+ handler: async (input, ctx) => {
1683
+ const current = activeMonacoService.getState().sessions[input.sessionId];
1684
+ if (!current) throw new Error(`Unknown Monaco session: ${input.sessionId}`);
1685
+ const document = {
1686
+ ...current.document,
1687
+ value: input.value,
1688
+ language: input.language || current.document.language,
1689
+ version: current.document.version + 1
1690
+ };
1691
+ const session = { ...current, document, updatedAt: Date.now() };
1692
+ activeMonacoService.setState({ sessions: { ...activeMonacoService.getState().sessions, [session.sessionId]: session } });
1693
+ return session;
1694
+ }
1695
+ },
1696
+ setDiagnostics: {
1697
+ id: "MonacoIdeService.setDiagnostics",
1698
+ name: "setDiagnostics",
1699
+ handler: async (input, ctx) => {
1700
+ const current = activeMonacoService.getState().sessions[input.sessionId];
1701
+ if (!current) throw new Error(`Unknown Monaco session: ${input.sessionId}`);
1702
+ const session = {
1703
+ ...current,
1704
+ document: { ...current.document, diagnostics: input.diagnostics },
1705
+ updatedAt: Date.now()
1706
+ };
1707
+ activeMonacoService.setState({ sessions: { ...activeMonacoService.getState().sessions, [session.sessionId]: session } });
1708
+ return session;
1709
+ }
1710
+ },
1711
+ setOptions: {
1712
+ id: "MonacoIdeService.setOptions",
1713
+ name: "setOptions",
1714
+ handler: async (input, ctx) => {
1715
+ const current = activeMonacoService.getState().sessions[input.sessionId];
1716
+ if (!current) throw new Error(`Unknown Monaco session: ${input.sessionId}`);
1717
+ const session = { ...current, options: { ...current.options, ...input.options }, updatedAt: Date.now() };
1718
+ activeMonacoService.setState({ sessions: { ...activeMonacoService.getState().sessions, [session.sessionId]: session } });
1719
+ return session;
1720
+ }
1721
+ },
1722
+ getSession: {
1723
+ id: "MonacoIdeService.getSession",
1724
+ name: "getSession",
1725
+ handler: async (input, ctx) => activeMonacoService.getState().sessions[input.sessionId] || null
1726
+ },
1727
+ disposeSession: {
1728
+ id: "MonacoIdeService.disposeSession",
1729
+ name: "disposeSession",
1730
+ handler: async (input, ctx) => {
1731
+ const sessions = { ...activeMonacoService.getState().sessions };
1732
+ delete sessions[input.sessionId];
1733
+ activeMonacoService.setState({ sessions });
1734
+ return { disposed: true, sessionId: input.sessionId };
1735
+ }
1736
+ }
1737
+ }
1738
+ });
1739
+ function createMonacoIdeService() {
1740
+ activeMonacoService = createService(MonacoIdeServiceDefinition);
1741
+ return activeMonacoService;
1742
+ }
1743
+ var defaultMonacoIdeService = createMonacoIdeService();
1744
+ var MonacoIdeServiceFacade = {
1745
+ id: MonacoIdeServiceDefinition.id,
1746
+ name: MonacoIdeServiceDefinition.name,
1747
+ version: MonacoIdeServiceDefinition.version,
1748
+ runtime: "client",
1749
+ deployment: "local",
1750
+ definition: MonacoIdeServiceDefinition,
1751
+ service: defaultMonacoIdeService,
1752
+ createInstance: createMonacoIdeService,
1753
+ execute: async (operation, input) => {
1754
+ await defaultMonacoIdeService.start();
1755
+ return defaultMonacoIdeService.call(operation, input);
1756
+ }
1757
+ };
1758
+
1759
+ // src/client-services/uiAuthoringService.ts
1760
+ import { buildServiceUISchema, suggestUIComponent } from "@ultrst-armada/kloks/contracts";
1761
+ var activeUIAuthoringService;
1762
+ var UIAuthoringServiceDefinition = createServiceDefinition({
1763
+ id: "kloks.service.uiAuthoring",
1764
+ name: "UIAuthoringService",
1765
+ version: "1.0.0",
1766
+ state: { initial: { sessions: {} } },
1767
+ operations: {
1768
+ createSession: {
1769
+ id: "UIAuthoringService.createSession",
1770
+ name: "createSession",
1771
+ handler: async (input, ctx) => {
1772
+ const sessionId = input.sessionId || `ui-authoring-${Date.now().toString(36)}`;
1773
+ const session = {
1774
+ sessionId,
1775
+ context: input.context,
1776
+ nodes: [],
1777
+ bindings: [],
1778
+ operations: input.operations || [],
1779
+ metadata: input.metadata || {}
1780
+ };
1781
+ activeUIAuthoringService.setState({ sessions: { ...activeUIAuthoringService.getState().sessions, [sessionId]: session } });
1782
+ return session;
1783
+ }
1784
+ },
1785
+ replaceSession: {
1786
+ id: "UIAuthoringService.replaceSession",
1787
+ name: "replaceSession",
1788
+ handler: async (input, ctx) => {
1789
+ if (input.sessionId !== input.session.sessionId) throw new Error("Session id mismatch.");
1790
+ return updateSession(activeUIAuthoringService, input.sessionId, () => input.session);
1791
+ }
1792
+ },
1793
+ addNode: {
1794
+ id: "UIAuthoringService.addNode",
1795
+ name: "addNode",
1796
+ handler: async (input, ctx) => updateSession(activeUIAuthoringService, input.sessionId, (session) => ({
1797
+ ...session,
1798
+ nodes: [...session.nodes.filter((node) => node.id !== input.node.id), input.node]
1799
+ }))
1800
+ },
1801
+ updateNode: {
1802
+ id: "UIAuthoringService.updateNode",
1803
+ name: "updateNode",
1804
+ handler: async (input, ctx) => updateSession(activeUIAuthoringService, input.sessionId, (session) => ({
1805
+ ...session,
1806
+ nodes: session.nodes.map((node) => node.id === input.nodeId ? { ...node, ...input.patch } : node)
1807
+ }))
1808
+ },
1809
+ removeNode: {
1810
+ id: "UIAuthoringService.removeNode",
1811
+ name: "removeNode",
1812
+ handler: async (input, ctx) => updateSession(activeUIAuthoringService, input.sessionId, (session) => ({
1813
+ ...session,
1814
+ nodes: session.nodes.filter((node) => node.id !== input.nodeId && node.parentId !== input.nodeId)
1815
+ }))
1816
+ },
1817
+ setBinding: {
1818
+ id: "UIAuthoringService.setBinding",
1819
+ name: "setBinding",
1820
+ handler: async (input, ctx) => updateSession(activeUIAuthoringService, input.sessionId, (session) => ({
1821
+ ...session,
1822
+ bindings: [...session.bindings.filter((binding) => binding.componentId !== input.binding.componentId || binding.property !== input.binding.property), input.binding]
1823
+ }))
1824
+ },
1825
+ setOperations: {
1826
+ id: "UIAuthoringService.setOperations",
1827
+ name: "setOperations",
1828
+ handler: async (input, ctx) => updateSession(activeUIAuthoringService, input.sessionId, (session) => ({ ...session, operations: input.operations }))
1829
+ },
1830
+ validate: {
1831
+ id: "UIAuthoringService.validate",
1832
+ name: "validate",
1833
+ handler: async (input, ctx) => validateSession(getSession(activeUIAuthoringService, input.sessionId))
1834
+ },
1835
+ serialize: {
1836
+ id: "UIAuthoringService.serialize",
1837
+ name: "serialize",
1838
+ handler: async (input, ctx) => JSON.stringify(getSession(activeUIAuthoringService, input.sessionId), null, 2)
1839
+ },
1840
+ generateServiceUI: {
1841
+ id: "UIAuthoringService.generateServiceUI",
1842
+ name: "generateServiceUI",
1843
+ handler: async (input, ctx) => buildServiceUISchema(getSession(activeUIAuthoringService, input.sessionId))
1844
+ },
1845
+ suggestComponent: {
1846
+ id: "UIAuthoringService.suggestComponent",
1847
+ name: "suggestComponent",
1848
+ handler: async (input) => suggestUIComponent(input.fieldType)
1849
+ },
1850
+ getSession: {
1851
+ id: "UIAuthoringService.getSession",
1852
+ name: "getSession",
1853
+ handler: async (input, ctx) => activeUIAuthoringService.getState().sessions[input.sessionId] || null
1854
+ }
1855
+ }
1856
+ });
1857
+ function getSession(service, sessionId) {
1858
+ const session = service.getState().sessions[sessionId];
1859
+ if (!session) throw new Error(`Unknown UI authoring session: ${sessionId}`);
1860
+ return session;
1861
+ }
1862
+ function updateSession(service, sessionId, update) {
1863
+ const session = update(getSession(service, sessionId));
1864
+ service.setState({ sessions: { ...service.getState().sessions, [sessionId]: session } });
1865
+ return session;
1866
+ }
1867
+ function validateSession(session) {
1868
+ const errors = [];
1869
+ const warnings = [];
1870
+ if (!session.nodes.some((node) => node.kind === "page")) errors.push("At least one page is required.");
1871
+ if (session.nodes.some((node) => node.kind === "component" && !node.assetRef)) errors.push("Every component node requires a FLOKS asset reference.");
1872
+ if (session.context === "service" && !session.metadata.serviceId) errors.push("Service authoring requires metadata.serviceId.");
1873
+ for (const binding of session.bindings) {
1874
+ if (!session.nodes.some((node) => node.id === binding.componentId)) errors.push(`Binding references missing component: ${binding.componentId}`);
1875
+ }
1876
+ if (!session.operations.length) warnings.push("No service operations have been attached to this authoring session.");
1877
+ return { valid: errors.length === 0, errors, warnings };
1878
+ }
1879
+ function createUIAuthoringService() {
1880
+ activeUIAuthoringService = createService(UIAuthoringServiceDefinition);
1881
+ return activeUIAuthoringService;
1882
+ }
1883
+ var defaultUIAuthoringService = createUIAuthoringService();
1884
+ var UIAuthoringServiceFacade = {
1885
+ id: UIAuthoringServiceDefinition.id,
1886
+ name: UIAuthoringServiceDefinition.name,
1887
+ version: UIAuthoringServiceDefinition.version,
1888
+ runtime: "client",
1889
+ deployment: "local",
1890
+ definition: UIAuthoringServiceDefinition,
1891
+ service: defaultUIAuthoringService,
1892
+ createInstance: createUIAuthoringService,
1893
+ execute: async (operation, input) => {
1894
+ await defaultUIAuthoringService.start();
1895
+ return defaultUIAuthoringService.call(operation, input);
1896
+ }
1897
+ };
1898
+
1654
1899
  // src/client-services/index.ts
1655
1900
  var AuthClientServiceDefinition = createServiceDefinition({
1656
1901
  id: "kloks.service.auth",
@@ -1973,6 +2218,8 @@ export {
1973
2218
  AuthServiceUISchema,
1974
2219
  CLEAN_DATABASE_CLUSTER,
1975
2220
  DEFAULT_CONNECTIONS,
2221
+ MonacoIdeServiceDefinition,
2222
+ MonacoIdeServiceFacade,
1976
2223
  STORAGE_KEY_CONNECTIONS,
1977
2224
  ServiceADefinition,
1978
2225
  ServiceAFacade,
@@ -1990,10 +2237,14 @@ export {
1990
2237
  SystemDbClientServiceFacade,
1991
2238
  SystemDbService,
1992
2239
  SystemDbServiceUISchema,
2240
+ UIAuthoringServiceDefinition,
2241
+ UIAuthoringServiceFacade,
1993
2242
  authService,
1994
2243
  clearSession,
2244
+ createMonacoIdeService,
1995
2245
  createServiceB,
1996
2246
  createServiceC,
2247
+ createUIAuthoringService,
1997
2248
  createWorkspace,
1998
2249
  deleteWorkspace,
1999
2250
  exposeServiceD,
@@ -7,6 +7,21 @@ import {
7
7
  instantiateSubgraph
8
8
  } from "./chunk-S22PMERU.js";
9
9
  import "./chunk-RHRXPY2U.js";
10
+ import {
11
+ AttractionEngine,
12
+ GhostInferenceEngine,
13
+ GhostLayoutResolver,
14
+ GhostTracePathBuilder,
15
+ calculateSocketCoordinates,
16
+ getBeamPoints,
17
+ useMagneticTraces
18
+ } from "./chunk-JXDJZSFW.js";
19
+ import {
20
+ ConnectionRuleStore,
21
+ HandleTypeRegistry,
22
+ WireTypeRegistry,
23
+ initializeDefaultGraphRules
24
+ } from "./chunk-TZOL3RN7.js";
10
25
  import {
11
26
  LifecycleCycleError,
12
27
  LifecycleGraph,
@@ -30,21 +45,6 @@ import {
30
45
  CustomViewWindow,
31
46
  DEFAULT_GRAPH_SETTINGS
32
47
  } from "./chunk-KG6QYS26.js";
33
- import {
34
- AttractionEngine,
35
- GhostInferenceEngine,
36
- GhostLayoutResolver,
37
- GhostTracePathBuilder,
38
- calculateSocketCoordinates,
39
- getBeamPoints,
40
- useMagneticTraces
41
- } from "./chunk-JXDJZSFW.js";
42
- import {
43
- ConnectionRuleStore,
44
- HandleTypeRegistry,
45
- WireTypeRegistry,
46
- initializeDefaultGraphRules
47
- } from "./chunk-TZOL3RN7.js";
48
48
  import {
49
49
  AutoSolidify,
50
50
  SpatialEngine,
@@ -1,9 +1,9 @@
1
- import {
2
- findUserWorkspace
3
- } from "./chunk-6K75XXFD.js";
4
1
  import {
5
2
  StorageAdapterFactory
6
3
  } from "./chunk-SHZAQTIT.js";
4
+ import {
5
+ findUserWorkspace
6
+ } from "./chunk-6K75XXFD.js";
7
7
 
8
8
  // src/services/workspaceGraphService.ts
9
9
  function slugify(name) {