@adminide-stack/yantra-mobile 12.0.162-alpha.0 → 12.0.162-alpha.2

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 (103) hide show
  1. package/lib/components/CustomDrawer.js +70 -3
  2. package/lib/components/CustomDrawer.js.map +1 -1
  3. package/lib/compute.js +3 -1
  4. package/lib/config/env-config.js +4 -0
  5. package/lib/config/env-config.js.map +1 -1
  6. package/lib/features/credits/credits.js +151 -0
  7. package/lib/features/credits/credits.js.map +1 -0
  8. package/lib/features/credits/useLlmCredits.js +87 -0
  9. package/lib/features/credits/useLlmCredits.js.map +1 -0
  10. package/lib/features/design/surface/agentWriter.js +39 -0
  11. package/lib/features/design/surface/agentWriter.js.map +1 -0
  12. package/lib/features/design/surface/brandKit.js +9 -3
  13. package/lib/features/design/surface/brandKit.js.map +1 -1
  14. package/lib/features/design/surface/useBrandKitInUse.js.map +1 -1
  15. package/lib/features/design/surface/useDesignSurface.js +5 -39
  16. package/lib/features/design/surface/useDesignSurface.js.map +1 -1
  17. package/lib/features/webbuilder/WebBuilderExperience.js +64 -23
  18. package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
  19. package/lib/features/webbuilder/brandKitMove.js +52 -0
  20. package/lib/features/webbuilder/brandKitMove.js.map +1 -0
  21. package/lib/features/webbuilder/codeToolbox.js +129 -0
  22. package/lib/features/webbuilder/codeToolbox.js.map +1 -0
  23. package/lib/features/webbuilder/components/CloudSheet.js +1451 -0
  24. package/lib/features/webbuilder/components/CloudSheet.js.map +1 -0
  25. package/lib/features/webbuilder/components/CodeActionsSheet.js +125 -0
  26. package/lib/features/webbuilder/components/CodeActionsSheet.js.map +1 -0
  27. package/lib/features/webbuilder/components/CodeView.js +10 -3
  28. package/lib/features/webbuilder/components/CodeView.js.map +1 -1
  29. package/lib/features/webbuilder/components/Composer.js.map +1 -1
  30. package/lib/features/webbuilder/components/IntegrationsPanel.js +643 -0
  31. package/lib/features/webbuilder/components/IntegrationsPanel.js.map +1 -0
  32. package/lib/features/webbuilder/components/ProjectChat.js +57 -44
  33. package/lib/features/webbuilder/components/ProjectChat.js.map +1 -1
  34. package/lib/features/webbuilder/components/SecretsSheet.js +235 -0
  35. package/lib/features/webbuilder/components/SecretsSheet.js.map +1 -0
  36. package/lib/features/webbuilder/components/StudioHome.js +38 -1
  37. package/lib/features/webbuilder/components/StudioHome.js.map +1 -1
  38. package/lib/features/webbuilder/studioCatalog.js +4 -19
  39. package/lib/features/webbuilder/studioCatalog.js.map +1 -1
  40. package/lib/features/webbuilder/web/data/cloud.js +387 -0
  41. package/lib/features/webbuilder/web/data/cloud.js.map +1 -0
  42. package/lib/features/webbuilder/web/data/dataApi.js +227 -0
  43. package/lib/features/webbuilder/web/data/dataApi.js.map +1 -0
  44. package/lib/features/webbuilder/web/data/database.js +190 -0
  45. package/lib/features/webbuilder/web/data/database.js.map +1 -0
  46. package/lib/features/webbuilder/web/data/graphql.js +95 -0
  47. package/lib/features/webbuilder/web/data/graphql.js.map +1 -0
  48. package/lib/features/webbuilder/web/design/directions.js +343 -0
  49. package/lib/features/webbuilder/web/design/directions.js.map +1 -0
  50. package/lib/features/webbuilder/web/integrations/appToken.js +165 -0
  51. package/lib/features/webbuilder/web/integrations/appToken.js.map +1 -0
  52. package/lib/features/webbuilder/web/integrations/catalog.js +238 -0
  53. package/lib/features/webbuilder/web/integrations/catalog.js.map +1 -0
  54. package/lib/features/webbuilder/web/integrations/siteBilling.js +67 -0
  55. package/lib/features/webbuilder/web/integrations/siteBilling.js.map +1 -0
  56. package/lib/features/webbuilder/web/integrations/siteMail.js +190 -0
  57. package/lib/features/webbuilder/web/integrations/siteMail.js.map +1 -0
  58. package/lib/features/webbuilder/web/project/projectSettings.js +11 -0
  59. package/lib/features/webbuilder/web/project/projectSettings.js.map +1 -0
  60. package/lib/features/webbuilder/web/project/restorePoint.js +16 -0
  61. package/lib/features/webbuilder/web/project/restorePoint.js.map +1 -0
  62. package/lib/features/webbuilder/web/project/serverSettings.js +157 -0
  63. package/lib/features/webbuilder/web/project/serverSettings.js.map +1 -0
  64. package/lib/features/webbuilder/web/secrets/secrets.js +162 -0
  65. package/lib/features/webbuilder/web/secrets/secrets.js.map +1 -0
  66. package/lib/features/webbuilder/web/secrets/secretsApi.js +302 -0
  67. package/lib/features/webbuilder/web/secrets/secretsApi.js.map +1 -0
  68. package/lib/features/webbuilder/web/secrets/secretsStore.js +39 -0
  69. package/lib/features/webbuilder/web/secrets/secretsStore.js.map +1 -0
  70. package/lib/features/webbuilder/web/sharing/okResult.js +40 -0
  71. package/lib/features/webbuilder/web/sharing/okResult.js.map +1 -0
  72. package/lib/features/webbuilder/web/sharing/roles.js +3 -0
  73. package/lib/features/webbuilder/web/sharing/roles.js.map +1 -0
  74. package/lib/features/webbuilder/web/state/storageKeys.js +59 -0
  75. package/lib/features/webbuilder/web/state/storageKeys.js.map +1 -0
  76. package/lib/features/webbuilder/web/webServices.js +282 -0
  77. package/lib/features/webbuilder/web/webServices.js.map +1 -0
  78. package/lib/features/webbuilder/workflow.js +1 -1
  79. package/lib/features/webbuilder/workflow.js.map +1 -1
  80. package/lib/routes.json +3 -1
  81. package/lib/screens/Account/AccountSheets.js +1049 -0
  82. package/lib/screens/Account/AccountSheets.js.map +1 -0
  83. package/lib/screens/Account/WorkspaceSection.js +271 -0
  84. package/lib/screens/Account/WorkspaceSection.js.map +1 -0
  85. package/lib/screens/Account/accountRules.js +103 -0
  86. package/lib/screens/Account/accountRules.js.map +1 -0
  87. package/lib/screens/Account/index.js +563 -259
  88. package/lib/screens/Account/index.js.map +1 -1
  89. package/lib/screens/Account/useAccountPreferences.js +87 -0
  90. package/lib/screens/Account/useAccountPreferences.js.map +1 -0
  91. package/lib/screens/WebBuilderNative/index.js +1 -1
  92. package/lib/screens/WebBuilderNative/index.js.map +1 -1
  93. package/lib/screens/WebBuilderNative/useWebBuilderHost.js +122 -12
  94. package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
  95. package/lib/utils/authUserDisplay.js +1 -9
  96. package/lib/utils/authUserDisplay.js.map +1 -1
  97. package/package.json +4 -4
  98. package/lib/features/webbuilder/brandKitStorage.js +0 -69
  99. package/lib/features/webbuilder/brandKitStorage.js.map +0 -1
  100. package/lib/features/webbuilder/components/BrandKitSheet.js +0 -197
  101. package/lib/features/webbuilder/components/BrandKitSheet.js.map +0 -1
  102. package/lib/screens/Account/splitDisplayName.js +0 -15
  103. package/lib/screens/Account/splitDisplayName.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projectSettings.js","sources":["../../../../../src/features/webbuilder/web/project/projectSettings.ts"],"sourcesContent":["/**\n * W20: project management and knowledge (pure; storage injected).\n *\n * Storage decision (spec §2): the backend has NO per-channel or per-project\n * settings field the surface can write through an existing GraphQL mutation\n * for these builds. `deleteChannel(id)` exists, but there is no\n * updateChannel/renameChannel, and `updateProjectMetadata` needs a real\n * Project document, while a build's `projectId` is minted client-side. So:\n * - project instructions (\"project knowledge\", max 4000 chars) live in\n * localStorage under `wb:projectKnowledge:<key>`;\n * - a rename lives in localStorage under `wb:projectTitle:<key>`.\n * `<key>` is the build's channelId (falling back to projectId): one board\n * tile = one channel, while older builds can share one projectId (the old\n * DEFAULT_YANTRA_PROJECT), which would leak instructions across projects.\n * Both are per browser; moving them server side needs a backend field.\n *\n * Phase 5 §7: the server now has that field (`aiCodeProjectSettings`, see\n * `serverSettings.ts` / `projectSettingsSync.ts`). This store stays as the\n * local mirror and the fallback when the server doesn't answer, and records\n * which projects had their local values uploaded (`wb:projectSettingsMigrated:<key>`).\n * Integrations / GitHub settings fall back to `wb:projectExtra:<key>` (JSON).\n */\n\nimport { storageKeys } from '../state/storageKeys';\n\nexport const PROJECT_KNOWLEDGE_MAX = 4000;\nexport const PROJECT_TITLE_MAX = 80;\n\nexport interface KeyValueStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport interface ProjectRef {\n channelId?: string | null;\n projectId?: string | null;\n}\n\n/** Storage key for a project: channelId first (see the note above), else projectId. Null when neither is usable. */\nexport function projectStorageKey(ref: ProjectRef | null | undefined): string | null {\n const id = (ref?.channelId || '').trim() || (ref?.projectId || '').trim();\n return id && /^[A-Za-z0-9_.:-]{1,128}$/.test(id) ? id : null;\n}\n\n/** Trimmed, LF line endings, at most 4000 characters. '' when empty. */\nexport function normalizeProjectKnowledge(text: string | null | undefined): string {\n const t = String(text ?? '')\n .replace(/\\r\\n?/g, '\\n')\n .replace(/\\u0000/g, '')\n .trim();\n return t.length > PROJECT_KNOWLEDGE_MAX ? t.slice(0, PROJECT_KNOWLEDGE_MAX) : t;\n}\n\n/** One line, collapsed whitespace, max 80 characters. Null when empty. */\nexport function normalizeProjectTitle(name: string | null | undefined): string | null {\n const t = String(name ?? '')\n .replace(/[\\u0000-\\u001f\\u007f]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n if (!t) return null;\n return t.length > PROJECT_TITLE_MAX ? t.slice(0, PROJECT_TITLE_MAX).trim() : t;\n}\n\n/** `props.projectKnowledge` for the USER post (spec §2): present only when non-empty. */\nexport function knowledgeTurnProps(text: string | null | undefined): { projectKnowledge?: string } {\n const t = normalizeProjectKnowledge(text);\n return t ? { projectKnowledge: t } : {};\n}\n\nfunction safeGet(storage: KeyValueStorage | null, key: string): string | null {\n try {\n return storage?.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\nfunction safeSet(storage: KeyValueStorage | null, key: string, value: string | null): boolean {\n if (!storage) return false;\n try {\n if (value === null) storage.removeItem(key);\n else storage.setItem(key, value);\n return true;\n } catch {\n return false; // quota / private mode\n }\n}\n\n/** Per-project instructions and title overrides. Every storage access is guarded. */\nexport class ProjectSettingsStore {\n private readonly storage: KeyValueStorage | null;\n\n constructor(storage: KeyValueStorage | null) {\n this.storage = storage;\n }\n\n getKnowledge(ref: ProjectRef | null | undefined): string {\n const key = projectStorageKey(ref);\n return key ? normalizeProjectKnowledge(safeGet(this.storage, storageKeys.projectKnowledge(key))) : '';\n }\n\n /** Saves (or clears, when empty). False when it couldn't be stored. */\n setKnowledge(ref: ProjectRef | null | undefined, text: string): boolean {\n const key = projectStorageKey(ref);\n if (!key) return false;\n const t = normalizeProjectKnowledge(text);\n return safeSet(this.storage, storageKeys.projectKnowledge(key), t || null);\n }\n\n getTitle(ref: ProjectRef | null | undefined): string | null {\n const key = projectStorageKey(ref);\n return key ? normalizeProjectTitle(safeGet(this.storage, storageKeys.projectTitle(key))) : null;\n }\n\n setTitle(ref: ProjectRef | null | undefined, title: string | null): boolean {\n const key = projectStorageKey(ref);\n if (!key) return false;\n return safeSet(this.storage, storageKeys.projectTitle(key), normalizeProjectTitle(title));\n }\n\n /** Phase 5: the local values were uploaded to the server (or there was nothing to upload). */\n isMigrated(ref: ProjectRef | null | undefined): boolean {\n const key = projectStorageKey(ref);\n return key ? safeGet(this.storage, storageKeys.projectSettingsMigrated(key)) === '1' : false;\n }\n\n markMigrated(ref: ProjectRef | null | undefined): boolean {\n const key = projectStorageKey(ref);\n return key ? safeSet(this.storage, storageKeys.projectSettingsMigrated(key), '1') : false;\n }\n\n /** Fallback copy of the other settings (integrations, github) as a JSON object; {} when none. */\n getExtra(ref: ProjectRef | null | undefined): Record<string, unknown> {\n const key = projectStorageKey(ref);\n const raw = key ? safeGet(this.storage, storageKeys.projectExtra(key)) : null;\n if (!raw) return {};\n try {\n const v = JSON.parse(raw) as unknown;\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n\n setExtra(ref: ProjectRef | null | undefined, value: Record<string, unknown>): boolean {\n const key = projectStorageKey(ref);\n if (!key) return false;\n const clean = Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined));\n return safeSet(\n this.storage,\n storageKeys.projectExtra(key),\n Object.keys(clean).length ? JSON.stringify(clean) : null,\n );\n }\n\n /** Forget everything about a deleted project. */\n forget(ref: ProjectRef | null | undefined): void {\n const key = projectStorageKey(ref);\n if (!key) return;\n safeSet(this.storage, storageKeys.projectKnowledge(key), null);\n safeSet(this.storage, storageKeys.projectTitle(key), null);\n safeSet(this.storage, storageKeys.projectSettingsMigrated(key), null);\n safeSet(this.storage, storageKeys.projectExtra(key), null);\n }\n}\n\n/** Apply stored title overrides; keeps object identity when nothing changes. */\nexport function applyTitleOverrides<T extends ProjectRef & { title: string }>(\n list: T[],\n titleFor: (ref: ProjectRef) => string | null,\n): T[] {\n let changed = false;\n const out = list.map((item) => {\n const title = titleFor(item);\n if (!title || title === item.title) return item;\n changed = true;\n return { ...item, title };\n });\n return changed ? out : list;\n}\n\n/** GraphQL: the existing messenger mutation that deletes a channel (= one build/project tile). */\nexport const DELETE_CHANNEL_MUTATION = `mutation WebbuilderDeleteChannel($id: ID!) {\n deleteChannel(id: $id)\n}`;\n\n/** Variables for {@link DELETE_CHANNEL_MUTATION}; null for an id we won't send. */\nexport function deleteChannelVariables(channelId: string | null | undefined): { id: string } | null {\n const id = (channelId || '').trim();\n return /^[A-Za-z0-9_-]{6,64}$/.test(id) ? { id } : null;\n}\n"],"names":[],"mappings":"AAwBO,MAAM,qBAAwB,GAAA;AAC9B,MAAM,iBAAoB,GAAA;AAkB1B,SAAS,0BAA0B,IAAyC,EAAA;AACjF,EAAA,MAAM,CAAI,GAAA,MAAA,CAAO,IAAQ,IAAA,IAAA,GAAA,IAAA,GAAA,EAAE,CAAE,CAAA,OAAA,CAAQ,QAAU,EAAA,IAAI,CAAE,CAAA,OAAA,CAAQ,SAAW,EAAA,EAAE,EAAE,IAAK,EAAA;AACjF,EAAA,OAAO,EAAE,MAAS,GAAA,qBAAA,GAAwB,EAAE,KAAM,CAAA,CAAA,EAAG,qBAAqB,CAAI,GAAA,CAAA;AAChF;AAGO,SAAS,sBAAsB,IAAgD,EAAA;AACpF,EAAA,MAAM,CAAI,GAAA,MAAA,CAAO,IAAQ,IAAA,IAAA,GAAA,IAAA,GAAA,EAAE,CAAE,CAAA,OAAA,CAAQ,yBAA2B,EAAA,GAAG,CAAE,CAAA,OAAA,CAAQ,MAAQ,EAAA,GAAG,EAAE,IAAK,EAAA;AAC/F,EAAI,IAAA,CAAC,GAAU,OAAA,IAAA;AACf,EAAO,OAAA,CAAA,CAAE,SAAS,iBAAoB,GAAA,CAAA,CAAE,MAAM,CAAG,EAAA,iBAAiB,CAAE,CAAA,IAAA,EAAS,GAAA,CAAA;AAC/E"}
@@ -0,0 +1,16 @@
1
+ const SNAPSHOT_ID_RE = /^[A-Za-z0-9._:/-]{1,200}$/;
2
+ const snapshotOf = (v) => {
3
+ const s = typeof v === "string" ? v.trim() : "";
4
+ return s && SNAPSHOT_ID_RE.test(s) ? s : null;
5
+ };
6
+ function parseRestorePoint(raw) {
7
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
8
+ const r = raw;
9
+ const snapshotId = snapshotOf(r.snapshotId);
10
+ if (!snapshotId) return null;
11
+ const ms = typeof r.createdAt === "string" ? Date.parse(r.createdAt) : NaN;
12
+ return {
13
+ snapshotId,
14
+ createdAt: Number.isFinite(ms) ? new Date(ms).toISOString() : null
15
+ };
16
+ }export{parseRestorePoint};//# sourceMappingURL=restorePoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restorePoint.js","sources":["../../../../../src/features/webbuilder/web/project/restorePoint.ts"],"sourcesContent":["/**\n * The project's latest restore point. The server keeps it in channel settings (`aiCodeProjectSettings`\n * returns `restorePoint`); posts and this browser's build record are fallbacks for projects saved\n * before that, or a backend that doesn't return it yet.\n */\n\nexport interface RestorePoint {\n snapshotId: string;\n createdAt: string | null;\n}\n\nexport type RestorePointSource = 'server' | 'post' | 'local';\n\nconst SNAPSHOT_ID_RE = /^[A-Za-z0-9._:/-]{1,200}$/;\n\nconst snapshotOf = (v: unknown): string | null => {\n const s = typeof v === 'string' ? v.trim() : '';\n return s && SNAPSHOT_ID_RE.test(s) ? s : null;\n};\n\n/** `aiCodeProjectSettings().restorePoint` -> a validated restore point, or null. */\nexport function parseRestorePoint(raw: unknown): RestorePoint | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;\n const r = raw as Record<string, unknown>;\n const snapshotId = snapshotOf(r.snapshotId);\n if (!snapshotId) return null;\n const ms = typeof r.createdAt === 'string' ? Date.parse(r.createdAt) : NaN;\n return { snapshotId, createdAt: Number.isFinite(ms) ? new Date(ms).toISOString() : null };\n}\n\n/**\n * Which snapshot to wake a project from: the server's record wins; then the newest post that names one\n * (`postSnapshots` newest first); then this browser's copy.\n */\nexport function pickRestorePoint(input: {\n server?: RestorePoint | null;\n postSnapshots?: readonly unknown[];\n local?: unknown;\n}): { snapshotId: string; source: RestorePointSource } | null {\n if (input.server) return { snapshotId: input.server.snapshotId, source: 'server' };\n for (const s of input.postSnapshots ?? []) {\n const id = snapshotOf(s);\n if (id) return { snapshotId: id, source: 'post' };\n }\n const local = snapshotOf(input.local);\n return local ? { snapshotId: local, source: 'local' } : null;\n}\n\n/** Newest first by `createdAt`; undated or tied items keep \"later in the list is newer\". */\nexport function newestFirst<T extends { createdAt?: string | null }>(items: readonly T[]): T[] {\n const at = (v: T) => {\n const ms = Date.parse(String(v.createdAt ?? ''));\n return Number.isFinite(ms) ? ms : -Infinity;\n };\n return items\n .map((item, i) => ({ item, i, t: at(item) }))\n .sort((a, b) => (b.t === a.t ? b.i - a.i : b.t > a.t ? 1 : -1))\n .map((x) => x.item);\n}\n"],"names":[],"mappings":"AAWA,MAAM,cAAiB,GAAA,2BAAA;AACvB,MAAM,UAAA,GAAa,CAAC,CAA8B,KAAA;AAChD,EAAA,MAAM,IAAI,OAAO,CAAA,KAAM,QAAW,GAAA,CAAA,CAAE,MAAS,GAAA,EAAA;AAC7C,EAAA,OAAO,CAAK,IAAA,cAAA,CAAe,IAAK,CAAA,CAAC,IAAI,CAAI,GAAA,IAAA;AAC3C,CAAA;AAGO,SAAS,kBAAkB,GAAmC,EAAA;AACnE,EAAI,IAAA,CAAC,OAAO,OAAO,GAAA,KAAQ,YAAY,KAAM,CAAA,OAAA,CAAQ,GAAG,CAAA,EAAU,OAAA,IAAA;AAClE,EAAA,MAAM,CAAI,GAAA,GAAA;AACV,EAAM,MAAA,UAAA,GAAa,UAAW,CAAA,CAAA,CAAE,UAAU,CAAA;AAC1C,EAAI,IAAA,CAAC,YAAmB,OAAA,IAAA;AACxB,EAAM,MAAA,EAAA,GAAK,OAAO,CAAE,CAAA,SAAA,KAAc,WAAW,IAAK,CAAA,KAAA,CAAM,CAAE,CAAA,SAAS,CAAI,GAAA,GAAA;AACvE,EAAO,OAAA;AAAA,IACL,UAAA;AAAA,IACA,SAAA,EAAW,MAAO,CAAA,QAAA,CAAS,EAAE,CAAA,GAAI,IAAI,IAAK,CAAA,EAAE,CAAE,CAAA,WAAA,EAAgB,GAAA;AAAA,GAChE;AACF"}
@@ -0,0 +1,157 @@
1
+ import {normalizeProjectKnowledge,normalizeProjectTitle}from'./projectSettings.js';import {parseRestorePoint}from'./restorePoint.js';import {toDesignDirection}from'../design/directions.js';var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ const IMPORT_KINDS = ["vite", "next", "unknown"];
18
+ function toImportKind(raw) {
19
+ const k = String(raw != null ? raw : "");
20
+ if (IMPORT_KINDS.includes(k)) return k;
21
+ return /^[a-z]+-(vite|tanstack)$/.test(k) ? "vite" : null;
22
+ }
23
+ const PROJECT_SETTINGS_QUERY = `query WebbuilderProjectSettings($channelId: String!) {
24
+ aiCodeProjectSettings(channelId: $channelId)
25
+ }`;
26
+ const MAX_INTEGRATIONS = 20;
27
+ const PURPOSE_MAX = 300;
28
+ function asObject(raw) {
29
+ let v = raw;
30
+ if (typeof v === "string") {
31
+ try {
32
+ v = JSON.parse(v);
33
+ } catch (e) {
34
+ return null;
35
+ }
36
+ }
37
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
38
+ }
39
+ const CONNECTOR_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
40
+ const OBJECT_ID_RE = /^[A-Za-z0-9_-]{6,64}$/;
41
+ function oneLine(text, max) {
42
+ const t = String(text != null ? text : "").replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
43
+ return t.length > max ? t.slice(0, max).trim() : t;
44
+ }
45
+ function normalizeIntegrations(raw) {
46
+ var _a, _b, _c;
47
+ if (!Array.isArray(raw)) return [];
48
+ const byId = /* @__PURE__ */ new Map();
49
+ for (const item of raw) {
50
+ if (!item || typeof item !== "object") continue;
51
+ const r = item;
52
+ const connectorId = String((_a = r.connectorId) != null ? _a : "").trim();
53
+ if (!CONNECTOR_ID_RE.test(connectorId)) continue;
54
+ const title = normalizeProjectTitle(String((_b = r.title) != null ? _b : "")) || connectorId;
55
+ const credentialId = String((_c = r.credentialId) != null ? _c : "").trim();
56
+ const purpose = oneLine(r.purpose, PURPOSE_MAX);
57
+ byId.delete(connectorId);
58
+ byId.set(connectorId, __spreadValues(__spreadValues({
59
+ connectorId,
60
+ title
61
+ }, OBJECT_ID_RE.test(credentialId) ? {
62
+ credentialId
63
+ } : {}), purpose ? {
64
+ purpose
65
+ } : {}));
66
+ }
67
+ return [...byId.values()].slice(-20);
68
+ }
69
+ function normalizeGithubRepoUrl(raw) {
70
+ const s = String(raw != null ? raw : "").trim();
71
+ if (!s) return null;
72
+ try {
73
+ const u = new URL(s);
74
+ if (u.protocol !== "https:" || u.hostname.toLowerCase() !== "github.com" || u.username || u.password) return null;
75
+ const [owner, repo] = u.pathname.replace(/\.git$/i, "").split("/").filter(Boolean);
76
+ if (!owner || !repo || !/^[A-Za-z0-9-]{1,39}$/.test(owner) || !/^[A-Za-z0-9._-]{1,100}$/.test(repo)) return null;
77
+ return `https://github.com/${owner}/${repo}`;
78
+ } catch (e) {
79
+ return null;
80
+ }
81
+ }
82
+ function normalizeBranch(raw) {
83
+ const b = String(raw != null ? raw : "").trim();
84
+ if (!/^[A-Za-z0-9._/-]{1,100}$/.test(b)) return null;
85
+ if (b.startsWith("-") || b.startsWith("/") || b.endsWith("/") || b.endsWith(".lock") || b.includes("..") || b.includes("//")) {
86
+ return null;
87
+ }
88
+ return b;
89
+ }
90
+ function isoOrNull(raw) {
91
+ const s = typeof raw === "string" ? raw.trim() : "";
92
+ return s && !Number.isNaN(new Date(s).getTime()) ? s : null;
93
+ }
94
+ function normalizeGithubSettings(raw) {
95
+ const r = asObject(raw);
96
+ if (!r) return null;
97
+ const repoUrl = normalizeGithubRepoUrl(r.repoUrl);
98
+ if (!repoUrl) return null;
99
+ return {
100
+ repoUrl,
101
+ branch: normalizeBranch(r.branch) || "main",
102
+ sync: r.sync === true,
103
+ lastPulledAt: isoOrNull(r.lastPulledAt),
104
+ lastPushedAt: isoOrNull(r.lastPushedAt),
105
+ syncBranch: normalizeBranch(r.syncBranch),
106
+ lastCommit: typeof r.lastCommit === "string" && /^[0-9a-f]{7,40}$/i.test(r.lastCommit) ? r.lastCommit : null
107
+ };
108
+ }
109
+ const SETTINGS_NOT_SAVED = "The settings could not be saved.";
110
+ function readSettingsUpdateReply(raw) {
111
+ var _a;
112
+ const r = asObject(raw);
113
+ if ((r == null ? void 0 : r.ok) === true) return {
114
+ ok: true,
115
+ settings: (_a = r.settings) != null ? _a : null
116
+ };
117
+ if ((r == null ? void 0 : r.ok) === false) {
118
+ const errors = Array.isArray(r.errors) ? r.errors.map((e) => String(e != null ? e : "").trim()).filter(Boolean) : [];
119
+ return {
120
+ ok: false,
121
+ error: errors.join("; ") || SETTINGS_NOT_SAVED
122
+ };
123
+ }
124
+ return {
125
+ ok: false,
126
+ error: SETTINGS_NOT_SAVED
127
+ };
128
+ }
129
+ function parseServerProjectSettings(raw) {
130
+ var _a;
131
+ const r = asObject(raw);
132
+ if (!r) return null;
133
+ const cred = String((_a = r.secretsCredentialId) != null ? _a : "").trim();
134
+ return {
135
+ title: normalizeProjectTitle(typeof r.title === "string" ? r.title : ""),
136
+ instructions: normalizeProjectKnowledge(typeof r.instructions === "string" ? r.instructions : ""),
137
+ secretsCredentialId: OBJECT_ID_RE.test(cred) ? cred : null,
138
+ integrations: normalizeIntegrations(r.integrations),
139
+ github: normalizeGithubSettings(r.github),
140
+ database: asObject(r.database),
141
+ designDirection: toDesignDirection(asObject(r.designDirection)),
142
+ importedFrom: normalizeImportedFrom(r.importedFrom),
143
+ restorePoint: parseRestorePoint(asObject(r.restorePoint))
144
+ };
145
+ }
146
+ function normalizeImportedFrom(raw) {
147
+ const r = asObject(raw);
148
+ const repoUrl = normalizeGithubRepoUrl(r == null ? void 0 : r.repoUrl);
149
+ const at = isoOrNull(r == null ? void 0 : r.at);
150
+ const kind = toImportKind(r == null ? void 0 : r.kind);
151
+ if (!r || !repoUrl || !at || !kind) return null;
152
+ return {
153
+ kind,
154
+ repoUrl,
155
+ at
156
+ };
157
+ }export{IMPORT_KINDS,MAX_INTEGRATIONS,PROJECT_SETTINGS_QUERY,normalizeBranch,normalizeGithubRepoUrl,normalizeGithubSettings,normalizeImportedFrom,normalizeIntegrations,parseServerProjectSettings,readSettingsUpdateReply,toImportKind};//# sourceMappingURL=serverSettings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverSettings.js","sources":["../../../../../src/features/webbuilder/web/project/serverSettings.ts"],"sourcesContent":["/**\n * Phase 5 §3/§7: per-project settings stored on the server (channel\n * `settings`) through `aiCodeProjectSettings` / `aiCodeUpdateProjectSettings`.\n * Pure: GraphQL documents, parsing, validation and the local -> server merge\n * and migration rules. The transport lives in `projectSettingsSync.ts`.\n *\n * The server never returns keys; nothing here ever holds one.\n */\n\nimport { PROJECT_KNOWLEDGE_MAX, normalizeProjectKnowledge, normalizeProjectTitle } from './projectSettings';\nimport { parseRestorePoint, type RestorePoint } from './restorePoint';\nimport { toDesignDirection, type DesignDirection } from '../design/directions';\n\n/** W28: one integration added to the site (Phase 5 spec §2). */\nexport interface ProjectIntegration {\n connectorId: string;\n title: string;\n credentialId?: string;\n purpose?: string;\n}\n\n/** W29: GitHub sync settings; the `last*` / `syncBranch` fields are written by the pipeline. */\nexport interface ProjectGithubSettings {\n repoUrl: string;\n branch: string;\n sync: boolean;\n lastPulledAt?: string | null;\n lastPushedAt?: string | null;\n /** Set when the repo diverged: our changes went to this branch instead (spec §4). */\n syncBranch?: string | null;\n lastCommit?: string | null;\n}\n\nexport interface ServerProjectSettings {\n title: string | null;\n instructions: string;\n secretsCredentialId: string | null;\n integrations: ProjectIntegration[];\n github: ProjectGithubSettings | null;\n /** W25 (stream D shows it): `{ provisioned, slug, url, status }` or null. */\n database: Record<string, unknown> | null;\n /** G4: the style direction picked before the first build; later edits keep its tokens. */\n designDirection?: DesignDirection | null;\n importedFrom?: ProjectImportedFrom | null;\n /** The latest restore point the server recorded (read-only; never sent in a patch). */\n restorePoint?: RestorePoint | null;\n}\n\nexport const IMPORT_KINDS = ['vite', 'next', 'unknown'] as const;\nexport type ImportKind = (typeof IMPORT_KINDS)[number];\n\n/** Kinds stored with a builder prefix (\"<builder>-vite\", \"<builder>-tanstack\") all run as Vite apps. */\nexport function toImportKind(raw: unknown): ImportKind | null {\n const k = String(raw ?? '');\n if ((IMPORT_KINDS as readonly string[]).includes(k)) return k as ImportKind;\n return /^[a-z]+-(vite|tanstack)$/.test(k) ? 'vite' : null;\n}\n\n/** Where an imported project came from; the server stamps `at`. */\nexport interface ProjectImportedFrom {\n kind: ImportKind;\n repoUrl: string;\n at: string;\n}\n\nexport const DATABASE_MODES = ['auto', 'yantra', 'none'] as const;\nexport type DatabaseMode = (typeof DATABASE_MODES)[number];\n\n/** The fields `aiCodeUpdateProjectSettings` accepts (spec §3). */\nexport interface ProjectSettingsPatch {\n title?: string | null;\n instructions?: string;\n secretsCredentialId?: string | null;\n integrations?: ProjectIntegration[];\n github?: { repoUrl: string; branch: string; sync: boolean } | null;\n designDirection?: DesignDirection | null;\n importedFrom?: { kind: ImportKind; repoUrl: string };\n database?: { mode: DatabaseMode };\n}\n\nexport const PROJECT_SETTINGS_QUERY = `query WebbuilderProjectSettings($channelId: String!) {\n aiCodeProjectSettings(channelId: $channelId)\n}`;\n\nexport const UPDATE_PROJECT_SETTINGS_MUTATION = `mutation WebbuilderUpdateProjectSettings($channelId: String!, $input: JSON!) {\n aiCodeUpdateProjectSettings(channelId: $channelId, input: $input)\n}`;\n\nexport const MAX_INTEGRATIONS = 20;\nconst PURPOSE_MAX = 300;\n\n/** The server doesn't have the field yet (P5 not deployed): fall back to localStorage, silently. */\nexport function isSchemaMissingError(errors: ReadonlyArray<{ message?: string }> | null | undefined): boolean {\n return Boolean(\n errors?.some((e) =>\n /Cannot query field|Unknown (argument|type)|is not defined by type|Unknown field/i.test(\n String(e?.message || ''),\n ),\n ),\n );\n}\n\n/** A JSON scalar may arrive as an object or a JSON string. */\nfunction asObject(raw: unknown): Record<string, unknown> | null {\n let v = raw;\n if (typeof v === 'string') {\n try {\n v = JSON.parse(v);\n } catch {\n return null;\n }\n }\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null;\n}\n\nconst CONNECTOR_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\nconst OBJECT_ID_RE = /^[A-Za-z0-9_-]{6,64}$/;\n\nfunction oneLine(text: unknown, max: number): string {\n const t = String(text ?? '')\n .replace(/[\\u0000-\\u001f\\u007f]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n return t.length > max ? t.slice(0, max).trim() : t;\n}\n\n/** Valid, de-duplicated (by connectorId, last wins) integrations, at most 20. */\nexport function normalizeIntegrations(raw: unknown): ProjectIntegration[] {\n if (!Array.isArray(raw)) return [];\n const byId = new Map<string, ProjectIntegration>();\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const r = item as Record<string, unknown>;\n const connectorId = String(r.connectorId ?? '').trim();\n if (!CONNECTOR_ID_RE.test(connectorId)) continue;\n const title = normalizeProjectTitle(String(r.title ?? '')) || connectorId;\n const credentialId = String(r.credentialId ?? '').trim();\n const purpose = oneLine(r.purpose, PURPOSE_MAX);\n byId.delete(connectorId);\n byId.set(connectorId, {\n connectorId,\n title,\n ...(OBJECT_ID_RE.test(credentialId) ? { credentialId } : {}),\n ...(purpose ? { purpose } : {}),\n });\n }\n return [...byId.values()].slice(-MAX_INTEGRATIONS);\n}\n\n/** `https://github.com/<owner>/<repo>` (no `.git`, no credentials), or null. */\nexport function normalizeGithubRepoUrl(raw: unknown): string | null {\n const s = String(raw ?? '').trim();\n if (!s) return null;\n try {\n const u = new URL(s);\n if (u.protocol !== 'https:' || u.hostname.toLowerCase() !== 'github.com' || u.username || u.password)\n return null;\n const [owner, repo] = u.pathname\n .replace(/\\.git$/i, '')\n .split('/')\n .filter(Boolean);\n if (!owner || !repo || !/^[A-Za-z0-9-]{1,39}$/.test(owner) || !/^[A-Za-z0-9._-]{1,100}$/.test(repo))\n return null;\n return `https://github.com/${owner}/${repo}`;\n } catch {\n return null;\n }\n}\n\n/** A safe git branch name, or null. */\nexport function normalizeBranch(raw: unknown): string | null {\n const b = String(raw ?? '').trim();\n if (!/^[A-Za-z0-9._/-]{1,100}$/.test(b)) return null;\n if (\n b.startsWith('-') ||\n b.startsWith('/') ||\n b.endsWith('/') ||\n b.endsWith('.lock') ||\n b.includes('..') ||\n b.includes('//')\n ) {\n return null;\n }\n return b;\n}\n\nfunction isoOrNull(raw: unknown): string | null {\n const s = typeof raw === 'string' ? raw.trim() : '';\n return s && !Number.isNaN(new Date(s).getTime()) ? s : null;\n}\n\nexport function normalizeGithubSettings(raw: unknown): ProjectGithubSettings | null {\n const r = asObject(raw);\n if (!r) return null;\n const repoUrl = normalizeGithubRepoUrl(r.repoUrl);\n if (!repoUrl) return null;\n return {\n repoUrl,\n branch: normalizeBranch(r.branch) || 'main',\n sync: r.sync === true,\n lastPulledAt: isoOrNull(r.lastPulledAt),\n lastPushedAt: isoOrNull(r.lastPushedAt),\n syncBranch: normalizeBranch(r.syncBranch),\n lastCommit: typeof r.lastCommit === 'string' && /^[0-9a-f]{7,40}$/i.test(r.lastCommit) ? r.lastCommit : null,\n };\n}\n\nexport function emptyServerSettings(): ServerProjectSettings {\n return { title: null, instructions: '', secretsCredentialId: null, integrations: [], github: null, database: null };\n}\n\n/** One shape with optional fields (native: no strict null checks, see `DataResult`). */\nexport interface SettingsUpdateReply {\n ok: boolean;\n settings?: unknown;\n error?: string;\n}\n\nconst SETTINGS_NOT_SAVED = 'The settings could not be saved.';\n\n/**\n * `aiCodeUpdateProjectSettings` answers `{ ok: true, settings }` or\n * `{ ok: false, errors: string[] }`, never the settings themselves. Anything\n * else counts as a failure, so a refused save is never reported as saved.\n */\nexport function readSettingsUpdateReply(raw: unknown): SettingsUpdateReply {\n const r = asObject(raw);\n if (r?.ok === true) return { ok: true, settings: r.settings ?? null };\n if (r?.ok === false) {\n const errors = Array.isArray(r.errors) ? r.errors.map((e) => String(e ?? '').trim()).filter(Boolean) : [];\n return { ok: false, error: errors.join('; ') || SETTINGS_NOT_SAVED };\n }\n return { ok: false, error: SETTINGS_NOT_SAVED };\n}\n\n/** `aiCodeProjectSettings` -> a validated settings object (null when the reply isn't one). */\nexport function parseServerProjectSettings(raw: unknown): ServerProjectSettings | null {\n const r = asObject(raw);\n if (!r) return null;\n const cred = String(r.secretsCredentialId ?? '').trim();\n return {\n title: normalizeProjectTitle(typeof r.title === 'string' ? r.title : ''),\n instructions: normalizeProjectKnowledge(typeof r.instructions === 'string' ? r.instructions : ''),\n secretsCredentialId: OBJECT_ID_RE.test(cred) ? cred : null,\n integrations: normalizeIntegrations(r.integrations),\n github: normalizeGithubSettings(r.github),\n database: asObject(r.database),\n designDirection: toDesignDirection(asObject(r.designDirection)),\n importedFrom: normalizeImportedFrom(r.importedFrom),\n restorePoint: parseRestorePoint(asObject(r.restorePoint)),\n };\n}\n\nexport function normalizeImportedFrom(raw: unknown): ProjectImportedFrom | null {\n const r = asObject(raw);\n const repoUrl = normalizeGithubRepoUrl(r?.repoUrl);\n const at = isoOrNull(r?.at);\n const kind = toImportKind(r?.kind);\n if (!r || !repoUrl || !at || !kind) return null;\n return { kind, repoUrl, at };\n}\n\n/** Validates a patch before it is sent; drops what the server would refuse. */\nexport function sanitizePatch(patch: ProjectSettingsPatch): ProjectSettingsPatch {\n const out: ProjectSettingsPatch = {};\n if ('title' in patch) out.title = normalizeProjectTitle(patch.title ?? '');\n if ('instructions' in patch)\n out.instructions = normalizeProjectKnowledge(patch.instructions).slice(0, PROJECT_KNOWLEDGE_MAX);\n if ('secretsCredentialId' in patch) {\n const c = String(patch.secretsCredentialId ?? '').trim();\n out.secretsCredentialId = OBJECT_ID_RE.test(c) ? c : null;\n }\n if ('integrations' in patch) out.integrations = normalizeIntegrations(patch.integrations);\n if ('github' in patch) {\n const g = patch.github ? normalizeGithubSettings(patch.github) : null;\n out.github = g ? { repoUrl: g.repoUrl, branch: g.branch, sync: g.sync } : null;\n }\n if ('designDirection' in patch)\n out.designDirection = patch.designDirection ? toDesignDirection(patch.designDirection) : null;\n if (patch.importedFrom) {\n const repoUrl = normalizeGithubRepoUrl(patch.importedFrom.repoUrl);\n const kind = toImportKind(patch.importedFrom.kind);\n if (repoUrl && kind) out.importedFrom = { kind, repoUrl };\n }\n if (patch.database && DATABASE_MODES.includes(patch.database.mode)) out.database = { mode: patch.database.mode };\n return out;\n}\n\n/** Apply a (sanitized) patch to settings we already hold. */\nexport function applyPatch(base: ServerProjectSettings | null, patch: ProjectSettingsPatch): ServerProjectSettings {\n const s = { ...(base ?? emptyServerSettings()) };\n if ('title' in patch) s.title = patch.title ?? null;\n if ('instructions' in patch) s.instructions = patch.instructions ?? '';\n if ('secretsCredentialId' in patch) s.secretsCredentialId = patch.secretsCredentialId ?? null;\n if ('integrations' in patch) s.integrations = patch.integrations ?? [];\n if ('designDirection' in patch) s.designDirection = patch.designDirection ?? null;\n if ('github' in patch) {\n s.github = patch.github\n ? {\n ...(s.github && s.github.repoUrl === patch.github.repoUrl ? s.github : {}),\n ...patch.github,\n }\n : null;\n }\n return s;\n}\n\nexport interface LocalProjectValues {\n title: string | null;\n instructions: string;\n}\n\n/**\n * The values the surface shows and sends.\n * - Server not loaded (unavailable, offline, not yet fetched): the local values.\n * - Server loaded, not yet migrated: the server's value where it has one, else the local one.\n * - Server loaded and migrated: the server is the truth (an empty server value\n * is a deliberate clear, possibly from another browser).\n */\nexport function mergeProjectSettings(\n server: ServerProjectSettings | null,\n local: LocalProjectValues,\n migrated: boolean,\n): LocalProjectValues {\n if (!server) return { title: local.title, instructions: local.instructions };\n if (migrated) return { title: server.title, instructions: server.instructions };\n return {\n title: server.title || local.title,\n instructions: server.instructions || local.instructions,\n };\n}\n\n/**\n * The one-time upload of values that so far lived only in this browser: the\n * local value for each field the server doesn't have yet. Null when nothing\n * needs uploading (the caller then just marks the project migrated).\n */\nexport function migrationPatch(local: LocalProjectValues, server: ServerProjectSettings): ProjectSettingsPatch | null {\n const patch: ProjectSettingsPatch = {};\n const title = normalizeProjectTitle(local.title ?? '');\n const instructions = normalizeProjectKnowledge(local.instructions);\n if (title && !server.title) patch.title = title;\n if (instructions && !server.instructions) patch.instructions = instructions;\n return Object.keys(patch).length ? patch : null;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AA8CO,MAAM,YAAe,GAAA,CAAC,MAAQ,EAAA,MAAA,EAAQ,SAAS;AAI/C,SAAS,aAAa,GAAiC,EAAA;AAC5D,EAAM,MAAA,CAAA,GAAI,MAAO,CAAA,GAAA,IAAA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+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]{1,63}$/;
21
+ const SECRET_VALUE_MAX = 16384;
22
+ const PUBLIC_SECRET_WARNING = "visible to anyone visiting the site";
23
+ const SECRETS_CREDENTIAL_PREFIX = "webbuilder-app-secrets:";
24
+ const PLATFORM_SECRET_NAMES = /* @__PURE__ */ new Set(["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_KEY", "CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_EMAIL", "CLOUDFLARE_PAGES_DOMAIN_SUFFIX", "ACCESSTOKEN", "BRIDGE_SECRET", "FLY_API_TOKEN"]);
25
+ const PLATFORM_PREFIXES = ["E2B_", "SYSTEM_PROVIDER_", "CDECLI_", "WEBBUILDER_", "YANTRA_WEBBUILDER_", "CF_"];
26
+ function isPublicSecretName(name) {
27
+ return /^(VITE_|NEXT_PUBLIC_)/.test(name);
28
+ }
29
+ function isPlatformSecretName(name) {
30
+ return PLATFORM_SECRET_NAMES.has(name) || PLATFORM_PREFIXES.some((p) => name.startsWith(p));
31
+ }
32
+ function normalizeSecretName(raw) {
33
+ return String(raw || "").trim().toUpperCase().replace(/[\s-]+/g, "_");
34
+ }
35
+ function validateSecretName(name) {
36
+ if (!name) return {
37
+ ok: false,
38
+ error: "Enter a name."
39
+ };
40
+ if (!SECRET_NAME_RE.test(name)) {
41
+ return {
42
+ ok: false,
43
+ error: "Use 2-64 capital letters, digits and underscores, starting with a letter (like STRIPE_SECRET_KEY)."
44
+ };
45
+ }
46
+ if (isPlatformSecretName(name)) {
47
+ return {
48
+ ok: false,
49
+ error: `${name} is reserved by the platform. Pick another name, like MY_${name}.`
50
+ };
51
+ }
52
+ if (isPublicSecretName(name)) {
53
+ return {
54
+ ok: true,
55
+ warning: `Names starting with VITE_ or NEXT_PUBLIC_ are ${PUBLIC_SECRET_WARNING}.`
56
+ };
57
+ }
58
+ return {
59
+ ok: true
60
+ };
61
+ }
62
+ function validateSecretValue(value) {
63
+ if (!value || !value.trim()) return {
64
+ ok: false,
65
+ error: "Enter a value."
66
+ };
67
+ if (value.length > SECRET_VALUE_MAX) return {
68
+ ok: false,
69
+ error: "That value is too long."
70
+ };
71
+ return {
72
+ ok: true
73
+ };
74
+ }
75
+ function secretsCredentialName(channelId) {
76
+ return `${SECRETS_CREDENTIAL_PREFIX}${channelId}`;
77
+ }
78
+ function secretVaultKey(channelId, name) {
79
+ const scope = String(channelId || "").replace(/[^A-Za-z0-9]/g, "").slice(0, 48);
80
+ const key = `WB_APP_${scope}_${name}`;
81
+ return /_[a-f0-9]{24}$/i.test(key) ? `${key}_V` : key;
82
+ }
83
+ function refsFromCredential(raw) {
84
+ const rec = raw && typeof raw === "object" ? raw : {};
85
+ const refs = Array.isArray(rec.vaultSecretRefs) ? rec.vaultSecretRefs : [];
86
+ const out = [];
87
+ const seen = /* @__PURE__ */ new Set();
88
+ for (const r of refs) {
89
+ const ref = r && typeof r === "object" ? r : {};
90
+ const fieldName = typeof ref.fieldName === "string" ? ref.fieldName : "";
91
+ if (!fieldName || seen.has(fieldName)) continue;
92
+ seen.add(fieldName);
93
+ const secret = ref.secret && typeof ref.secret === "object" ? ref.secret : {};
94
+ const secretKey = typeof secret.secretKey === "string" && secret.secretKey ? secret.secretKey : void 0;
95
+ out.push(secretKey ? {
96
+ fieldName,
97
+ secretKey
98
+ } : {
99
+ fieldName
100
+ });
101
+ }
102
+ return out;
103
+ }
104
+ function namesFromRefs(refs) {
105
+ return refs.map((r) => r.fieldName).sort((a, b) => a.localeCompare(b));
106
+ }
107
+ const keep = (channelId, r) => ({
108
+ fieldName: r.fieldName,
109
+ secretKey: r.secretKey || secretVaultKey(channelId, r.fieldName)
110
+ });
111
+ function buildCreateCredentialInput(opts) {
112
+ var _a, _b;
113
+ const values = (_b = opts.values) != null ? _b : opts.name ? {
114
+ [opts.name]: (_a = opts.value) != null ? _a : ""
115
+ } : {};
116
+ return {
117
+ name: secretsCredentialName(opts.channelId),
118
+ description: "App secrets for a Yantra webbuilder project (env vars for the app).",
119
+ project: opts.project,
120
+ vaultSecretRefs: Object.entries(values).map(([fieldName, secretValue]) => ({
121
+ fieldName,
122
+ secretKey: secretVaultKey(opts.channelId, fieldName),
123
+ secretValue,
124
+ secretType: "ENVIRONMENT_VAR"
125
+ }))
126
+ };
127
+ }
128
+ function buildRefsForSave(channelId, existing, nameOrValues, value = "") {
129
+ const values = typeof nameOrValues === "string" ? {
130
+ [nameOrValues]: value
131
+ } : nameOrValues;
132
+ const names = new Set(Object.keys(values));
133
+ const others = existing.filter((r) => !names.has(r.fieldName)).map((r) => keep(channelId, r));
134
+ return [...others, ...[...names].map((name) => {
135
+ var _a;
136
+ return {
137
+ fieldName: name,
138
+ secretKey: ((_a = existing.find((r) => r.fieldName === name)) == null ? void 0 : _a.secretKey) || secretVaultKey(channelId, name),
139
+ secretValue: values[name],
140
+ secretType: "ENVIRONMENT_VAR"
141
+ };
142
+ })];
143
+ }
144
+ function buildRefsForDelete(channelId, existing, name) {
145
+ return existing.filter((r) => r.fieldName !== name).map((r) => keep(channelId, r));
146
+ }
147
+ function buildSecretsStartParams(opts) {
148
+ const envFromCredential = {};
149
+ for (const n of opts.names) if (SECRET_NAME_RE.test(n)) envFromCredential[n] = n;
150
+ const envRemove = (opts.remove || []).filter((n) => SECRET_NAME_RE.test(n) && !(n in envFromCredential));
151
+ return __spreadValues(__spreadProps(__spreadValues(__spreadValues({
152
+ sandbox_id: opts.sandboxId
153
+ }, opts.builder ? {
154
+ builder: opts.builder
155
+ } : {}), opts.workDir ? {
156
+ workDir: opts.workDir
157
+ } : {}), {
158
+ envFromCredential
159
+ }), envRemove.length ? {
160
+ envRemove
161
+ } : {});
162
+ }export{PLATFORM_SECRET_NAMES,PUBLIC_SECRET_WARNING,SECRETS_CREDENTIAL_PREFIX,SECRET_NAME_RE,SECRET_VALUE_MAX,buildCreateCredentialInput,buildRefsForDelete,buildRefsForSave,buildSecretsStartParams,isPlatformSecretName,isPublicSecretName,namesFromRefs,normalizeSecretName,refsFromCredential,secretVaultKey,secretsCredentialName,validateSecretName,validateSecretValue};//# sourceMappingURL=secrets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.js","sources":["../../../../../src/features/webbuilder/web/secrets/secrets.ts"],"sourcesContent":["/**\n * W27 app secrets: pure validation and payload builders (Phase 5 spec §5).\n *\n * Storage: ONE FormBuilderCredential per project, named\n * `webbuilder-app-secrets:<channelId>`, whose vault fields are the env var\n * names. It is created and updated with the user's own token.\n *\n * Where the credential's `project` comes from: the Yantra project of the\n * user's surface token. The cdecli JWT carries `cdecodeUri =\n * cdecode://<tenant>/<orgName>/<projectId>` (the same claim the notes surface\n * reads in forms-stack `surfaces/notion/src/scope.ts`); the server accepts the\n * project's Mongo id or its UUID there (`loadAccessibleProject`). The\n * webbuilder's own `projectId` is a chat-session id, NOT an org project, so it\n * is never used here.\n *\n * Vault keys: on update the server only stores a NEW value when the ref has a\n * `secretKey` (a value without one takes a different, non-vault path), and a\n * plain credential's key is shared across the project's vault. So every field\n * gets its own key, scoped to this app: `WB_APP_<channelId>_<NAME>`.\n *\n * Values are never logged and never returned by any helper except the payload\n * builders, which hand them straight to the mutation.\n */\n\nexport const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]{1,63}$/;\nexport const SECRET_VALUE_MAX = 16_384;\nexport const PUBLIC_SECRET_WARNING = 'visible to anyone visiting the site';\nexport const SECRETS_CREDENTIAL_PREFIX = 'webbuilder-app-secrets:';\n\n/**\n * Env names the connector refuses to write into an app for any credential\n * (yantra-webbuilder audit patch, envFromCredential \"refused targets\": its own\n * platform config). Ordinary app names like STRIPE_API_KEY or OPENAI_API_KEY are\n * allowed from the user's own credential. Refusing these here saves a confusing\n * failure at preview start or publish.\n */\nexport const PLATFORM_SECRET_NAMES: ReadonlySet<string> = new Set([\n 'CLOUDFLARE_API_TOKEN',\n 'CLOUDFLARE_API_KEY',\n 'CLOUDFLARE_ACCOUNT_ID',\n 'CLOUDFLARE_EMAIL',\n 'CLOUDFLARE_PAGES_DOMAIN_SUFFIX',\n 'ACCESSTOKEN',\n 'BRIDGE_SECRET',\n 'FLY_API_TOKEN',\n]);\n\nconst PLATFORM_PREFIXES = ['E2B_', 'SYSTEM_PROVIDER_', 'CDECLI_', 'WEBBUILDER_', 'YANTRA_WEBBUILDER_', 'CF_'];\n\nexport interface NameCheck {\n ok: boolean;\n /** Why the name can't be used. */\n error?: string;\n /** Usable, but the user should know (browser-visible names). */\n warning?: string;\n}\n\nexport function isPublicSecretName(name: string): boolean {\n return /^(VITE_|NEXT_PUBLIC_)/.test(name);\n}\n\nexport function isPlatformSecretName(name: string): boolean {\n return PLATFORM_SECRET_NAMES.has(name) || PLATFORM_PREFIXES.some((p) => name.startsWith(p));\n}\n\n/** Trim and upper-case what the user typed (spaces and dashes become underscores). */\nexport function normalizeSecretName(raw: string): string {\n return String(raw || '')\n .trim()\n .toUpperCase()\n .replace(/[\\s-]+/g, '_');\n}\n\nexport function validateSecretName(name: string): NameCheck {\n if (!name) return { ok: false, error: 'Enter a name.' };\n if (!SECRET_NAME_RE.test(name)) {\n return {\n ok: false,\n error: 'Use 2-64 capital letters, digits and underscores, starting with a letter (like STRIPE_SECRET_KEY).',\n };\n }\n if (isPlatformSecretName(name)) {\n return { ok: false, error: `${name} is reserved by the platform. Pick another name, like MY_${name}.` };\n }\n if (isPublicSecretName(name)) {\n return { ok: true, warning: `Names starting with VITE_ or NEXT_PUBLIC_ are ${PUBLIC_SECRET_WARNING}.` };\n }\n return { ok: true };\n}\n\nexport function validateSecretValue(value: string): { ok: boolean; error?: string } {\n if (!value || !value.trim()) return { ok: false, error: 'Enter a value.' };\n if (value.length > SECRET_VALUE_MAX) return { ok: false, error: 'That value is too long.' };\n return { ok: true };\n}\n\nexport function secretsCredentialName(channelId: string): string {\n return `${SECRETS_CREDENTIAL_PREFIX}${channelId}`;\n}\n\n/** The vault key for one field of this app's credential (see the module comment). */\nexport function secretVaultKey(channelId: string, name: string): string {\n const scope = String(channelId || '')\n .replace(/[^A-Za-z0-9]/g, '')\n .slice(0, 48);\n const key = `WB_APP_${scope}_${name}`;\n // The server reads a `_<24 hex>` tail as \"bound to that credential\" and refuses it.\n return /_[a-f0-9]{24}$/i.test(key) ? `${key}_V` : key;\n}\n\nexport interface TokenScope {\n orgName?: string;\n project?: string;\n}\n\n/** Org and project from the cdecli JWT claims (see the module comment). */\nexport function scopeFromClaims(claims: Record<string, unknown> | null | undefined): TokenScope {\n const c = claims || {};\n const uri = typeof c.cdecodeUri === 'string' ? c.cdecodeUri : typeof c.cdebaseUri === 'string' ? c.cdebaseUri : '';\n const m = uri.match(/^[a-z][a-z0-9+.-]*:\\/\\/[^/]*\\/([^/?#]+)(?:\\/([^/?#]+))?/i);\n const decode = (s?: string) => {\n if (!s) return undefined;\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n };\n const orgClaim = typeof c.orgName === 'string' && c.orgName ? c.orgName : undefined;\n const projectClaim = typeof c.projectId === 'string' && c.projectId ? c.projectId : undefined;\n return {\n orgName: orgClaim || decode(m?.[1]),\n project: decode(m?.[2]) || projectClaim,\n };\n}\n\n/** Decode a JWT's claims without verifying it (only to read the scope). */\nexport function claimsFromJwt(token: string | null | undefined): Record<string, unknown> {\n const jwt = String(token || '')\n .replace(/^Bearer\\s+/i, '')\n .trim();\n const seg = jwt.split('.')[1];\n if (!seg) return {};\n try {\n const b64 = seg.replace(/-/g, '+').replace(/_/g, '/');\n const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);\n const text =\n typeof atob === 'function'\n ? atob(padded)\n : (globalThis as { Buffer?: any }).Buffer.from(padded, 'base64').toString('binary');\n const parsed = JSON.parse(text) as unknown;\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\n/** One stored field as read back from `formBuilderCredential` (no value, ever). */\nexport interface StoredSecretRef {\n fieldName: string;\n secretKey?: string;\n}\n\n/** Read `vaultSecretRefs` from a credential answer: names and vault keys only. */\nexport function refsFromCredential(raw: unknown): StoredSecretRef[] {\n const rec = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};\n const refs = Array.isArray(rec.vaultSecretRefs) ? (rec.vaultSecretRefs as unknown[]) : [];\n const out: StoredSecretRef[] = [];\n const seen = new Set<string>();\n for (const r of refs) {\n const ref = r && typeof r === 'object' ? (r as Record<string, unknown>) : {};\n const fieldName = typeof ref.fieldName === 'string' ? ref.fieldName : '';\n if (!fieldName || seen.has(fieldName)) continue;\n seen.add(fieldName);\n const secret = ref.secret && typeof ref.secret === 'object' ? (ref.secret as Record<string, unknown>) : {};\n const secretKey = typeof secret.secretKey === 'string' && secret.secretKey ? secret.secretKey : undefined;\n out.push(secretKey ? { fieldName, secretKey } : { fieldName });\n }\n return out;\n}\n\nexport function namesFromRefs(refs: StoredSecretRef[]): string[] {\n return refs.map((r) => r.fieldName).sort((a, b) => a.localeCompare(b));\n}\n\nexport interface VaultSecretRefInput {\n fieldName: string;\n secretKey: string;\n secretValue?: string;\n secretType?: 'ENVIRONMENT_VAR';\n description?: string;\n}\n\nconst keep = (channelId: string, r: StoredSecretRef): VaultSecretRefInput => ({\n fieldName: r.fieldName,\n secretKey: r.secretKey || secretVaultKey(channelId, r.fieldName),\n});\n\n/** `createFormBuilderCredential` input for a project's first secret. */\nexport function buildCreateCredentialInput(opts: {\n channelId: string;\n project: string;\n name?: string;\n value?: string;\n /** Several values at once (instead of `name` / `value`). */\n values?: Record<string, string>;\n}): Record<string, unknown> {\n const values = opts.values ?? (opts.name ? { [opts.name]: opts.value ?? '' } : {});\n return {\n name: secretsCredentialName(opts.channelId),\n description: 'App secrets for a Yantra webbuilder project (env vars for the app).',\n project: opts.project,\n vaultSecretRefs: Object.entries(values).map(([fieldName, secretValue]) => ({\n fieldName,\n secretKey: secretVaultKey(opts.channelId, fieldName),\n secretValue,\n secretType: 'ENVIRONMENT_VAR',\n })),\n };\n}\n\n/**\n * The FULL ref list for an add / replace (the server replaces the whole list,\n * so every other field is kept by its vault key without a value). Pass a\n * `{ name: value }` map to set several fields in one write.\n */\nexport function buildRefsForSave(\n channelId: string,\n existing: StoredSecretRef[],\n nameOrValues: string | Record<string, string>,\n value: string = '',\n): VaultSecretRefInput[] {\n const values: Record<string, string> = typeof nameOrValues === 'string' ? { [nameOrValues]: value } : nameOrValues;\n const names = new Set(Object.keys(values));\n const others = existing.filter((r) => !names.has(r.fieldName)).map((r) => keep(channelId, r));\n return [\n ...others,\n ...[...names].map((name) => ({\n fieldName: name,\n secretKey: existing.find((r) => r.fieldName === name)?.secretKey || secretVaultKey(channelId, name),\n secretValue: values[name],\n secretType: 'ENVIRONMENT_VAR' as const,\n })),\n ];\n}\n\n/** The FULL ref list without `name`. */\nexport function buildRefsForDelete(\n channelId: string,\n existing: StoredSecretRef[],\n name: string,\n): VaultSecretRefInput[] {\n return existing.filter((r) => r.fieldName !== name).map((r) => keep(channelId, r));\n}\n\n/** `props.secretsCredentialId` for every turn (spec §2): present only when set. */\nexport function secretsTurnProps(credentialId: string | null | undefined): { secretsCredentialId?: string } {\n const id = String(credentialId || '').trim();\n return id ? { secretsCredentialId: id } : {};\n}\n\n/**\n * WEBBUILDER_START params for an edit-free restart that applies the secrets:\n * `envFromCredential` maps each field to the env var of the same name. The\n * credential itself is attached as `--credential-id` by the caller.\n */\nexport function buildSecretsStartParams(opts: {\n sandboxId: string;\n names: string[];\n workDir?: string;\n builder?: string;\n /** Deleted names to drop from the sandbox .env / .dev.vars (connector `envRemove`). */\n remove?: string[];\n}): Record<string, unknown> {\n const envFromCredential: Record<string, string> = {};\n for (const n of opts.names) if (SECRET_NAME_RE.test(n)) envFromCredential[n] = n;\n const envRemove = (opts.remove || []).filter((n) => SECRET_NAME_RE.test(n) && !(n in envFromCredential));\n return {\n sandbox_id: opts.sandboxId,\n ...(opts.builder ? { builder: opts.builder } : {}),\n ...(opts.workDir ? { workDir: opts.workDir } : {}),\n envFromCredential,\n ...(envRemove.length ? { envRemove } : {}),\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAwBO,MAAM,cAAiB,GAAA;AACvB,MAAM,gBAAmB,GAAA;AACzB,MAAM,qBAAwB,GAAA;AAC9B,MAAM,yBAA4B,GAAA;AASlC,MAAM,qBAA6C,mBAAA,IAAI,GAAI,CAAA,CAAC,sBAAwB,EAAA,oBAAA,EAAsB,uBAAyB,EAAA,kBAAA,EAAoB,gCAAkC,EAAA,aAAA,EAAe,eAAiB,EAAA,eAAe,CAAC;AAChP,MAAM,oBAAoB,CAAC,MAAA,EAAQ,oBAAoB,SAAW,EAAA,aAAA,EAAe,sBAAsB,KAAK,CAAA;AAQrG,SAAS,mBAAmB,IAAuB,EAAA;AACxD,EAAO,OAAA,uBAAA,CAAwB,KAAK,IAAI,CAAA;AAC1C;AACO,SAAS,qBAAqB,IAAuB,EAAA;AAC1D,EAAO,OAAA,qBAAA,CAAsB,GAAI,CAAA,IAAI,CAAK,IAAA,iBAAA,CAAkB,KAAK,CAAK,CAAA,KAAA,IAAA,CAAK,UAAW,CAAA,CAAC,CAAC,CAAA;AAC1F;AAGO,SAAS,oBAAoB,GAAqB,EAAA;AACvD,EAAO,OAAA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