-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
5834 lines (5113 loc) · 189 KB
/
Copy pathapp.js
File metadata and controls
5834 lines (5113 loc) · 189 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import posthog from "posthog-js";
import {
getPrimaryArtifact,
normalizeArtifactBundle,
} from "./src/artifactBundle.js";
import {
buildArchitectPrompt,
buildArtifactRegenerationPrompt,
buildBundleRegenerationPrompt,
buildGeneratorPrompt,
buildReviewPrompt,
createBuildShipContext,
} from "./src/pipelineContracts.js";
import { createModelArmorError } from "./src/modelArmorResponse.js";
import {
getCustomActionReturnTypeError,
getCustomClassFileNameError,
getDeclaredDartTypes,
validateBundleCompatibility,
} from "./src/flutterFlowArtifactValidation.js";
import { buildBundleDeployPlan } from "./src/bundleDeployPlanner.js";
import {
excludeProvisionedCodeFiles,
findMissingCodeFiles,
} from "./src/flutterFlowCodeFileProvisioning.js";
import { buildReviewPresentation } from "./src/reviewPresentation.js";
import { formatFlutterFlowFileError } from "./src/flutterFlowFileErrors.js";
import { extractPackageImports } from "./src/dartPackageImports.js";
import { buildFlutterFlowSyncMetadata } from "./src/flutterFlowSyncMetadata.js";
import {
mergeDependenciesIntoYaml,
validateProjectPubspec,
} from "./src/pubspecSync.js";
import { escapeAttr, escapeHtml, escapeHtmlText } from "./src/htmlEscape.js";
import {
extractCodeFromMarkdown,
highlightCode,
renderMarkdownAudit,
} from "./src/auditRenderer.js";
// --- CONFIGURATION ---
const IS_DEV = import.meta.env.DEV
const FLUTTERFLOW_CLASS_PROVISION_ENDPOINT =
import.meta.env.VITE_FLUTTERFLOW_CLASS_PROVISION_ENDPOINT ||
import.meta.env.VITE_FLUTTERFLOW_DSL_DEPLOY_ENDPOINT ||
"https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";
// --- ANALYTICS ---
const POSTHOG_KEY = import.meta.env.VITE_PUBLIC_POSTHOG_KEY;
const POSTHOG_HOST = import.meta.env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com';
if (POSTHOG_KEY) {
posthog.init(POSTHOG_KEY, {
api_host: POSTHOG_HOST,
person_profiles: 'identified_only'
});
}
function trackEvent(eventName, properties = {}) {
if (POSTHOG_KEY) {
try {
posthog.capture(eventName, properties);
} catch(e) {
console.error("PostHog tracking failed", e);
}
}
}
// --- AUTH / SUBSCRIPTION CONFIG ---
const BUILDSHIP_BASE_URL = 'https://4tgke4.buildship.run'
const STRIPE_PRICE_IDS = {
professional: 'price_1T2ldCKszA2slvDXatdeCpbI',
power: 'price_1T2le9KszA2slvDXR4mPvw7M'
}
const AUTH_SESSION_STORAGE_KEY = 'ccc_auth_session'
const proGateAttachedSet = new WeakSet()
let authState = {
email: null,
sessionToken: null,
isVerified: false,
}
function createSubscriptionState(overrides = {}) {
return {
tier: 'free',
status: 'none',
periodEnd: null,
isLoading: false,
isResolved: false,
error: null,
...overrides,
}
}
let subscriptionState = createSubscriptionState({ isResolved: true })
// --- PIPELINE ---
const PIPELINE_ENDPOINT = `${BUILDSHIP_BASE_URL}/service/runpipeline`
// --- IDENTITY RESOLUTION ---
const IDENTITY_COOKIE_KEY = 'bs_identity'
const IDENTITY_SESSION_KEY = 'bs_user_id'
const IDENTITY_ENDPOINT = `${BUILDSHIP_BASE_URL}/authUserCheck`
let identityState = {
userId: null,
status: null, // 'recognized' | 'new' | null
resolved: false,
}
// --- TIER LIMITS ---
const TIER_LIMITS = {
free: 2,
professional: 50,
power: 2000,
}
const SUBSCRIPTION_CACHE_KEY = 'ccc_subscription'
const SUBSCRIPTION_CACHE_VERSION = 3
const PAID_SUBSCRIPTION_STATUSES = new Set(['active', 'trialing', 'paid'])
const FREE_MODEL = 'google/gemini-3.6-flash'
const PRO_MODELS = [
'anthropic/claude-opus-5',
'openai/gpt-5.6-sol',
'z-ai/glm-5.2',
'moonshotai/kimi-k3',
'openrouter/auto-beta',
'openrouter/free',
'openrouter/deepseek/deepseek-v4-pro',
]
// Display names for every selectable model. Keep in sync with the
// #code-generator-model options in index.html.
const MODEL_LABELS = {
'google/gemini-3.6-flash': 'Gemini 3.6 Flash',
'anthropic/claude-opus-5': 'Claude Opus 5',
'openai/gpt-5.6-sol': 'GPT-5.6 Sol',
'z-ai/glm-5.2': 'GLM 5.2',
'moonshotai/kimi-k3': 'Kimi K3',
'openrouter/auto-beta': 'OpenRouter: Auto Router',
'openrouter/free': 'OpenRouter: Free Models',
'openrouter/deepseek/deepseek-v4-pro': 'DeepSeek v4 Pro',
}
function getModelLabel(model) {
return MODEL_LABELS[model] || model
}
const USAGE_STORAGE_KEY = 'ccc_usage'
// Model Configuration
const PROMPT_ARCHITECT_MODEL = "google/gemini-3.6-flash"
const CODE_REVIEW_MODEL = "google/gemini-3.6-flash"
const FALLBACK_MODEL = "google/gemini-3.6-flash"
// --- DYNAMIC PRICING ---
const BASE_PRICES_AUD = { professional: 11, power: 49 }
const LOCALE_CURRENCY_MAP = {
en_US: 'USD', en_GB: 'GBP', en_AU: 'AUD', en_NZ: 'NZD', en_CA: 'CAD',
en_IN: 'INR', en_SG: 'SGD', en_HK: 'HKD', en_PH: 'PHP', en_ZA: 'ZAR',
en: 'USD',
de: 'EUR', fr: 'EUR', es: 'EUR', it: 'EUR', nl: 'EUR', pt_PT: 'EUR',
pt_BR: 'BRL', pt: 'BRL',
ja: 'JPY', ko: 'KRW', zh_CN: 'CNY', zh_TW: 'TWD', zh: 'CNY',
th: 'THB', vi: 'VND', id: 'IDR', ms_MY: 'MYR', ms: 'MYR',
sv: 'SEK', nb: 'NOK', da: 'DKK', pl: 'PLN', cs: 'CZK',
hu: 'HUF', ro: 'RON', tr: 'TRY',
ar: 'AED', he: 'ILS', ru: 'RUB', uk: 'UAH',
}
const AUD_EXCHANGE_RATES_FALLBACK = {
AUD: 1, USD: 0.65, EUR: 0.60, GBP: 0.52, CAD: 0.88,
NZD: 1.08, JPY: 97, KRW: 870, INR: 54, SGD: 0.87,
HKD: 5.08, BRL: 3.18, CNY: 4.70, TWD: 20.5, THB: 22.5,
VND: 16200, IDR: 10200, MYR: 2.88, SEK: 6.80, NOK: 6.95,
DKK: 4.48, PLN: 2.60, CZK: 15.2, HUF: 238, RON: 2.98,
TRY: 20.9, AED: 2.39, ILS: 2.38, PHP: 36.4, ZAR: 11.8,
RUB: 58, UAH: 26.8, CHF: 0.57, MXN: 11.1, ARS: 580,
CLP: 610, COP: 2700, PEN: 2.44,
}
let AUD_EXCHANGE_RATES = { ...AUD_EXCHANGE_RATES_FALLBACK }
async function fetchAudExchangeRates() {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 5000)
try {
const res = await fetch('https://open.er-api.com/v6/latest/AUD', { signal: controller.signal })
if (!res.ok) return
const data = await res.json()
if (data.result !== 'success' || !data.rates) return
const rates = data.rates
const updated = { AUD: 1 }
const allCurrencies = new Set([
...Object.keys(AUD_EXCHANGE_RATES_FALLBACK),
...Object.values(TIMEZONE_CURRENCY_MAP),
...Object.values(LOCALE_CURRENCY_MAP),
])
for (const code of allCurrencies) {
if (code === 'AUD') continue
if (typeof rates[code] === 'number' && rates[code] > 0) {
updated[code] = rates[code]
} else if (AUD_EXCHANGE_RATES_FALLBACK[code]) {
updated[code] = AUD_EXCHANGE_RATES_FALLBACK[code]
}
}
AUD_EXCHANGE_RATES = updated
} catch {
} finally {
clearTimeout(timeout)
}
}
const TIMEZONE_CURRENCY_MAP = {
'America/Sao_Paulo': 'BRL', 'America/Fortaleza': 'BRL', 'America/Recife': 'BRL',
'America/Bahia': 'BRL', 'America/Belem': 'BRL', 'America/Manaus': 'BRL',
'America/Cuiaba': 'BRL', 'America/Campo_Grande': 'BRL', 'America/Araguaina': 'BRL',
'America/Noronha': 'BRL', 'America/Rio_Branco': 'BRL', 'America/Porto_Velho': 'BRL',
'America/Boa_Vista': 'BRL', 'America/Maceio': 'BRL', 'America/Santarem': 'BRL',
'America/Eirunepe': 'BRL',
'Europe/London': 'GBP', 'Europe/Paris': 'EUR', 'Europe/Berlin': 'EUR',
'Europe/Madrid': 'EUR', 'Europe/Rome': 'EUR', 'Europe/Amsterdam': 'EUR',
'Europe/Brussels': 'EUR', 'Europe/Vienna': 'EUR', 'Europe/Lisbon': 'EUR',
'Europe/Dublin': 'EUR', 'Europe/Helsinki': 'EUR', 'Europe/Athens': 'EUR',
'Europe/Bucharest': 'RON', 'Europe/Budapest': 'HUF', 'Europe/Warsaw': 'PLN',
'Europe/Prague': 'CZK', 'Europe/Copenhagen': 'DKK', 'Europe/Stockholm': 'SEK',
'Europe/Oslo': 'NOK', 'Europe/Zurich': 'CHF', 'Europe/Istanbul': 'TRY',
'Europe/Moscow': 'RUB', 'Europe/Kiev': 'UAH', 'Europe/Kyiv': 'UAH',
'Asia/Tokyo': 'JPY', 'Asia/Seoul': 'KRW', 'Asia/Shanghai': 'CNY',
'Asia/Taipei': 'TWD', 'Asia/Hong_Kong': 'HKD', 'Asia/Singapore': 'SGD',
'Asia/Kolkata': 'INR', 'Asia/Calcutta': 'INR', 'Asia/Bangkok': 'THB',
'Asia/Ho_Chi_Minh': 'VND', 'Asia/Jakarta': 'IDR', 'Asia/Kuala_Lumpur': 'MYR',
'Asia/Dubai': 'AED', 'Asia/Jerusalem': 'ILS', 'Asia/Tel_Aviv': 'ILS',
'Asia/Manila': 'PHP',
'Pacific/Auckland': 'NZD',
'Australia/Sydney': 'AUD', 'Australia/Melbourne': 'AUD', 'Australia/Brisbane': 'AUD',
'Australia/Perth': 'AUD', 'Australia/Adelaide': 'AUD', 'Australia/Hobart': 'AUD',
'Australia/Darwin': 'AUD', 'Australia/Lord_Howe': 'AUD',
'America/Toronto': 'CAD', 'America/Vancouver': 'CAD', 'America/Edmonton': 'CAD',
'America/Winnipeg': 'CAD', 'America/Halifax': 'CAD', 'America/St_Johns': 'CAD',
'America/Regina': 'CAD',
'America/New_York': 'USD', 'America/Chicago': 'USD', 'America/Denver': 'USD',
'America/Los_Angeles': 'USD', 'America/Phoenix': 'USD', 'America/Anchorage': 'USD',
'Pacific/Honolulu': 'USD',
'America/Mexico_City': 'MXN', 'America/Cancun': 'MXN', 'America/Tijuana': 'MXN',
'America/Argentina/Buenos_Aires': 'ARS',
'America/Santiago': 'CLP', 'America/Bogota': 'COP', 'America/Lima': 'PEN',
'Africa/Johannesburg': 'ZAR',
}
function detectUserCurrency() {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone
if (tz && TIMEZONE_CURRENCY_MAP[tz]) return TIMEZONE_CURRENCY_MAP[tz]
} catch {}
const locale = navigator.language || 'en-US'
const normalized = locale.replace('-', '_')
const exactMatch = LOCALE_CURRENCY_MAP[normalized]
if (exactMatch) return exactMatch
const langOnly = normalized.split('_')[0]
const langMatch = LOCALE_CURRENCY_MAP[langOnly]
if (langMatch) return langMatch
return 'USD'
}
function formatPrice(audAmount, currency) {
const rate = AUD_EXCHANGE_RATES[currency] ?? AUD_EXCHANGE_RATES.USD
const converted = audAmount * rate
const rounded = Math.round(converted * 100) / 100
try {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
minimumFractionDigits: 0,
maximumFractionDigits: rounded >= 100 ? 0 : rounded % 1 === 0 ? 0 : 2,
}).format(rounded)
} catch {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0,
maximumFractionDigits: 2,
}).format(audAmount * AUD_EXCHANGE_RATES.USD)
}
}
// --- SECURE STORAGE (AES-256-GCM encryption) ---
const STORAGE_KEY_PREFIX = "ccc_api_key_";
const SESSION_STORAGE_KEY_PREFIX = "ccc_session_api_key_";
const ENCRYPTION_KEY_NAME = "ccc_encryption_key";
const SESSION_KEY_SCOPE_NAME = "ccc_encryption_key_scope";
const KEY_DB_NAME = "ccc_keystore";
const KEY_DB_STORE = "keys";
const KEY_VERSION_NAME = "ccc_encryption_key_version";
/** @type {Promise<CryptoKey> | null} */
let encryptionKeyPromise = null;
let cachedEncryptionKeyVersion = null;
let usingSessionKeyFallback = false;
let sessionFallbackSupportsDurableCredentials = false;
let keyStorageWarningShown = false;
class CredentialStorageUnavailableError extends Error {
constructor() {
super("Secure browser key storage is unavailable.");
this.name = "CredentialStorageUnavailableError";
}
}
function notifyKeyStorageFallback() {
if (keyStorageWarningShown) return;
keyStorageWarningShown = true;
const message =
"Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";
console.warn(message);
if (document.body) showToast(message, "warning");
}
function currentEncryptionKeyVersion() {
return localStorage.getItem(KEY_VERSION_NAME) || "";
}
function newEncryptionKeyVersion() {
return crypto.randomUUID?.()
|| arrayBufferToBase64(crypto.getRandomValues(new Uint8Array(16)));
}
function ensureEncryptionKeyVersion() {
const current = currentEncryptionKeyVersion();
if (current) return current;
const created = newEncryptionKeyVersion();
localStorage.setItem(KEY_VERSION_NAME, created);
return created;
}
function invalidateEncryptionKeyCache() {
encryptionKeyPromise = null;
cachedEncryptionKeyVersion = null;
usingSessionKeyFallback = false;
sessionFallbackSupportsDurableCredentials = false;
}
window.addEventListener("storage", (event) => {
if (event.key === KEY_VERSION_NAME) invalidateEncryptionKeyCache();
});
// IndexedDB can persist a CryptoKey object without exposing its raw bytes.
// This prevents an injected script from exporting the key for offline use.
// It does not let browser storage survive arbitrary same-origin script: XSS
// could still ask Web Crypto to decrypt while it is running.
/** @returns {Promise<IDBDatabase>} */
function openKeyDatabase() {
return /** @type {Promise<IDBDatabase>} */ (new Promise((resolve, reject) => {
const request = indexedDB.open(KEY_DB_NAME, 1);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(KEY_DB_STORE)) {
db.createObjectStore(KEY_DB_STORE);
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
}));
}
/**
* @template T
* @param {IDBTransactionMode} mode
* @param {(store: IDBObjectStore) => IDBRequest<T>} operation
* @returns {Promise<T>}
*/
async function runKeyDatabaseRequest(mode, operation) {
const db = /** @type {IDBDatabase} */ (await openKeyDatabase());
return new Promise((resolve, reject) => {
const transaction = db.transaction(KEY_DB_STORE, mode);
let request;
try {
request = operation(transaction.objectStore(KEY_DB_STORE));
} catch (error) {
db.close();
reject(error);
return;
}
let result;
request.onsuccess = () => {
result = request.result;
};
request.onerror = () => reject(request.error);
transaction.oncomplete = () => {
db.close();
resolve(result);
};
transaction.onerror = () => {
db.close();
reject(transaction.error || new Error("Encryption key transaction failed."));
};
transaction.onabort = () => {
db.close();
reject(transaction.error || new Error("Encryption key transaction aborted."));
};
});
}
/** @param {unknown} key */
function isUsableEncryptionKey(key) {
return key instanceof CryptoKey
&& key.algorithm?.name === "AES-GCM"
&& key.extractable === false
&& key.usages.includes("encrypt")
&& key.usages.includes("decrypt");
}
/** @returns {Promise<CryptoKey | null>} */
async function loadStoredEncryptionKey() {
const key = await runKeyDatabaseRequest("readonly", (store) =>
store.get(ENCRYPTION_KEY_NAME),
);
return isUsableEncryptionKey(key) ? key : null;
}
/** @param {CryptoKey} key */
async function persistEncryptionKey(key) {
await runKeyDatabaseRequest("readwrite", (store) =>
store.put(key, ENCRYPTION_KEY_NAME),
);
}
async function deleteStoredEncryptionKey() {
invalidateEncryptionKeyCache();
try {
await runKeyDatabaseRequest("readwrite", (store) =>
store.delete(ENCRYPTION_KEY_NAME),
);
} catch (error) {
console.warn("Could not delete the stored encryption key:", error);
}
}
// Re-import an earlier sessionStorage JWK as non-extractable before removing
// the exportable copy. This keeps existing encrypted credentials readable.
/** @returns {Promise<CryptoKey | null>} */
async function migrateLegacySessionKey() {
const legacy = sessionStorage.getItem(ENCRYPTION_KEY_NAME);
if (!legacy) return null;
const key = await crypto.subtle.importKey(
"jwk",
JSON.parse(legacy),
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
await persistEncryptionKey(key);
// The legacy JWK is the only recovery path until the IndexedDB write has
// committed successfully.
sessionStorage.removeItem(ENCRYPTION_KEY_NAME);
sessionStorage.removeItem(SESSION_KEY_SCOPE_NAME);
localStorage.removeItem(STORAGE_KEY_PREFIX + "salt");
return key;
}
/**
* @param {boolean} allowCreation
* @returns {Promise<CryptoKey>}
*/
async function resolveSessionEncryptionKey(allowCreation) {
const stored = sessionStorage.getItem(ENCRYPTION_KEY_NAME);
if (stored) {
sessionFallbackSupportsDurableCredentials =
sessionStorage.getItem(SESSION_KEY_SCOPE_NAME) !== "session";
return crypto.subtle.importKey(
"jwk",
JSON.parse(stored),
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
if (!allowCreation) throw new CredentialStorageUnavailableError();
const exportableKey = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"],
);
const jwk = await crypto.subtle.exportKey("jwk", exportableKey);
sessionStorage.setItem(ENCRYPTION_KEY_NAME, JSON.stringify(jwk));
sessionStorage.setItem(SESSION_KEY_SCOPE_NAME, "session");
sessionFallbackSupportsDurableCredentials = false;
return crypto.subtle.importKey(
"jwk",
jwk,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
/**
* @param {boolean} allowSessionFallbackCreation
* @returns {Promise<CryptoKey>}
*/
async function resolveEncryptionKey(allowSessionFallbackCreation) {
if (
sessionStorage.getItem(SESSION_KEY_SCOPE_NAME) === "session"
&& sessionStorage.getItem(ENCRYPTION_KEY_NAME)
) {
notifyKeyStorageFallback();
usingSessionKeyFallback = true;
return resolveSessionEncryptionKey(allowSessionFallbackCreation);
}
try {
const stored = await loadStoredEncryptionKey();
if (stored) return stored;
const migrated = await migrateLegacySessionKey();
if (migrated) return migrated;
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
await persistEncryptionKey(key);
return key;
} catch (error) {
console.warn("IndexedDB encryption-key storage failed:", error);
notifyKeyStorageFallback();
usingSessionKeyFallback = true;
return resolveSessionEncryptionKey(allowSessionFallbackCreation);
}
}
/**
* @param {{allowSessionFallbackCreation?: boolean}} [options]
* @returns {Promise<CryptoKey>}
*/
async function getEncryptionKey(options = {}) {
const { allowSessionFallbackCreation = true } = options;
const version = ensureEncryptionKeyVersion();
if (cachedEncryptionKeyVersion !== version) {
invalidateEncryptionKeyCache();
}
const pending = /** @type {Promise<CryptoKey>} */ (
encryptionKeyPromise || resolveEncryptionKey(allowSessionFallbackCreation)
);
encryptionKeyPromise = pending;
cachedEncryptionKeyVersion = version;
try {
return await pending;
} catch (error) {
invalidateEncryptionKeyCache();
throw error;
}
}
// Encrypt data using AES-256-GCM
async function encryptData(plaintext) {
const key = /** @type {CryptoKey} */ (await getEncryptionKey());
const keyVersion = cachedEncryptionKeyVersion;
const encoder = new TextEncoder();
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
key,
encoder.encode(plaintext),
);
// Combine IV + encrypted data
const combined = new Uint8Array(iv.length + encrypted.byteLength);
combined.set(iv);
combined.set(new Uint8Array(encrypted), iv.length);
return {
ciphertext: arrayBufferToBase64(combined),
keyVersion,
sessionFallback: usingSessionKeyFallback,
};
}
// Decrypt data using AES-256-GCM
async function decryptData(encryptedBase64, options = {}) {
const { isSessionCredential = false } = options;
try {
const key = /** @type {CryptoKey} */ (await getEncryptionKey({
allowSessionFallbackCreation: false,
}));
if (
usingSessionKeyFallback
&& !isSessionCredential
&& !sessionFallbackSupportsDurableCredentials
) {
throw new CredentialStorageUnavailableError();
}
const combined = base64ToArrayBuffer(encryptedBase64);
const iv = combined.slice(0, 12);
const encrypted = combined.slice(12);
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: iv },
key,
encrypted,
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
} catch (error) {
if (error instanceof CredentialStorageUnavailableError) throw error;
console.error("Decryption failed:", error);
return null;
}
}
// Helper functions for base64 encoding/decoding
function arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToArrayBuffer(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
// --- API KEY MANAGEMENT ---
async function saveApiKey(provider, apiKey) {
if (!apiKey || apiKey.trim() === "") {
localStorage.removeItem(STORAGE_KEY_PREFIX + provider);
sessionStorage.removeItem(SESSION_STORAGE_KEY_PREFIX + provider);
return;
}
for (let attempt = 0; attempt < 2; attempt++) {
const encrypted = await encryptData(apiKey.trim());
if (encrypted.keyVersion === currentEncryptionKeyVersion()) {
const storage = encrypted.sessionFallback ? sessionStorage : localStorage;
const prefix = encrypted.sessionFallback
? SESSION_STORAGE_KEY_PREFIX
: STORAGE_KEY_PREFIX;
storage.setItem(prefix + provider, encrypted.ciphertext);
if (!encrypted.sessionFallback) {
sessionStorage.removeItem(SESSION_STORAGE_KEY_PREFIX + provider);
}
return;
}
invalidateEncryptionKeyCache();
}
throw new Error("Encryption key changed while saving. Please try again.");
}
async function getApiKey(provider) {
// Only check user-stored key - no environment fallback
const sessionEncrypted = sessionStorage.getItem(
SESSION_STORAGE_KEY_PREFIX + provider,
);
const encrypted = sessionEncrypted
|| localStorage.getItem(STORAGE_KEY_PREFIX + provider);
if (encrypted) {
let decrypted;
try {
decrypted = await decryptData(encrypted, {
isSessionCredential: Boolean(sessionEncrypted),
});
} catch (error) {
if (error instanceof CredentialStorageUnavailableError) return "";
throw error;
}
if (decrypted) return decrypted;
// If decryption failed, clean up the stale encrypted data
const storage = sessionEncrypted ? sessionStorage : localStorage;
const prefix = sessionEncrypted
? SESSION_STORAGE_KEY_PREFIX
: STORAGE_KEY_PREFIX;
storage.removeItem(prefix + provider);
}
// Return empty string if no user key is configured
return "";
}
function getFlutterFlowEndpoint() {
return (
localStorage.getItem("flutterflow_api_endpoint") ||
FF_API_ENDPOINTS.production
);
}
function setFlutterFlowEndpoint(endpoint) {
localStorage.setItem("flutterflow_api_endpoint", endpoint);
return true;
}
function hasStoredKey(provider) {
const keys = {
flutterflow: flutterflowApiKey,
flutterflow_project_id: flutterflowProjectId,
}
return keys[provider] && keys[provider].length > 0
}
// Get current active API keys (for use in API calls)
let flutterflowApiKey = "";
let flutterflowProjectId = "";
async function initializeApiKeys() {
// Remove an exportable key left by an earlier version even if its encrypted
// credentials were already cleared.
if (sessionStorage.getItem(ENCRYPTION_KEY_NAME)) {
await getEncryptionKey();
}
flutterflowApiKey = await getApiKey("flutterflow");
flutterflowProjectId = await getApiKey("flutterflow_project_id");
updateApiKeyStatusIndicators();
updateDeployButtonVisibility();
}
// --- API KEY UI FUNCTIONS ---
function openApiKeysModal() {
const modal = document.getElementById("api-keys-modal");
modal.classList.add("open");
// Load current keys into inputs (masked)
loadApiKeyInputs();
// The project dropdown is the only way to pick a project, so populate it as
// soon as a stored key is available.
if (flutterflowApiKey) {
fetchProjects(flutterflowApiKey);
}
}
function closeApiKeysModal(event) {
if (event && event.target !== event.currentTarget) return;
const modal = document.getElementById("api-keys-modal");
if (modal) {
modal.classList.remove("open");
}
// Show walkthrough again after closing API keys
const walkthroughModal = document.getElementById("walkthrough-modal");
if (walkthroughModal) {
advanceWalkthrough();
walkthroughModal.classList.add("open");
}
}
let walkthroughStep = 1;
function getWalkthroughSteps() {
const container = document.querySelector('.wt-steps');
if (!container) return [];
return Array.from(container.querySelectorAll('.wt-step-card'));
}
function updateWalkthroughUI() {
const steps = getWalkthroughSteps();
if (!steps.length) return;
steps.forEach((stepEl, idx) => {
const i = idx + 1;
if (i === walkthroughStep) {
stepEl.classList.remove("opacity-60", "bg-gray-50", "border-gray-200");
stepEl.classList.add("bg-blue-50", "border-blue-200");
const numEl = stepEl.querySelector("div:first-child");
if (numEl) {
numEl.classList.remove("bg-gray-400");
numEl.classList.add("bg-blue-500");
numEl.innerHTML = i;
}
} else if (i < walkthroughStep) {
stepEl.classList.remove("opacity-60", "bg-blue-50", "border-blue-200");
stepEl.classList.add("bg-green-50", "border-green-200");
const numEl = stepEl.querySelector("div:first-child");
if (numEl) {
numEl.classList.remove("bg-blue-500", "bg-gray-400");
numEl.classList.add("bg-green-500");
numEl.innerHTML = "✓";
}
} else {
stepEl.classList.add("opacity-60", "bg-gray-50", "border-gray-200");
stepEl.classList.remove(
"bg-blue-50",
"border-blue-200",
"bg-green-50",
"border-green-200",
);
const numEl = stepEl.querySelector("div:first-child");
if (numEl) {
numEl.classList.remove("bg-blue-500", "bg-green-500");
numEl.classList.add("bg-gray-400");
numEl.innerHTML = i;
}
}
});
}
function advanceWalkthrough() {
const totalSteps = getWalkthroughSteps().length;
if (totalSteps > 0 && walkthroughStep <= totalSteps) {
walkthroughStep++;
updateWalkthroughUI();
}
}
function openWalkthroughModal() {
const modal = document.getElementById("walkthrough-modal");
if (modal) {
walkthroughStep = 1;
updateWalkthroughUI();
modal.classList.add("open");
}
}
function closeWalkthroughModal(event) {
if (event && event.target !== event.currentTarget) return;
const modal = document.getElementById("walkthrough-modal");
if (modal) {
modal.classList.remove("open");
}
const dontShow = document.getElementById("walkthrough-dont-show");
if (dontShow && dontShow.checked) {
localStorage.setItem("hasSeenWalkthrough", "true");
}
}
function showWalkthroughIfNeeded() {
// Never show walkthrough for paid users
if (authState.isVerified && isSubscriptionResolved() && subscriptionState.tier !== 'free') return;
const hasSeen = localStorage.getItem("hasSeenWalkthrough");
if (!hasSeen) {
const modal = document.getElementById("walkthrough-modal");
if (modal) {
walkthroughStep = 1;
updateWalkthroughUI();
modal.classList.add("open");
}
}
}
async function loadApiKeyInputs() {
const flutterflowInput = document.getElementById("flutterflow-api-key-input");
if (flutterflowApiKey) {
flutterflowInput.value = "";
flutterflowInput.placeholder = "Key saved (enter new to replace)";
} else {
flutterflowInput.placeholder = "Enter your FlutterFlow API key";
}
updateModalKeyStatuses();
}
function updateModalKeyStatuses() {
updateKeyStatus("flutterflow", "flutterflow-key-status");
updateKeyStatus("flutterflow_project_id", "flutterflow-project-status");
}
function updateKeyStatus(provider, statusElementId) {
const statusEl = document.getElementById(statusElementId);
if (!statusEl) return;
const dot = statusEl.querySelector(".key-status-dot");
const text = statusEl.querySelector("span");
if (hasStoredKey(provider)) {
dot.className = "key-status-dot configured";
text.className = "text-green-600";
text.textContent = "User key configured";
} else {
dot.className = "key-status-dot missing";
text.className = "text-gray-500";
text.textContent = "Not configured";
}
}
function updateDeployButtonVisibility() {
const hasGeneratedCode =
pipelineState.step2Result && pipelineState.step2Result.length > 0;
const deployBtn = document.getElementById("btn-deploy-to-ff");
const runBtn = document.getElementById("btn-run-pipeline");
// Run Pipeline stays visible next to Deploy so a generation can be restarted
// without closing the results.
if (runBtn) runBtn.classList.remove("hidden");
if (deployBtn) {
deployBtn.classList.toggle("hidden", !hasGeneratedCode);
}
}
function updateApiKeyStatusIndicators() {
const container = document.getElementById("api-keys-status");
if (!container) return;
const dots = container.querySelectorAll(".key-status-dot");
const providers = [
"flutterflow",
];
dots.forEach((dot, index) => {
const provider = providers[index];
if (provider === "flutterflow") {
// For FlutterFlow, check both API key and Project ID
if (
hasStoredKey("flutterflow") &&
hasStoredKey("flutterflow_project_id")
) {
dot.className = "key-status-dot configured";
dot.title = "FlutterFlow (Fully configured)";
} else if (
hasStoredKey("flutterflow") ||
hasStoredKey("flutterflow_project_id")
) {
dot.className = "key-status-dot env";
dot.title = "FlutterFlow (Partially configured)";
} else {
dot.className = "key-status-dot missing";
dot.title = "FlutterFlow (Not configured)";
}
} else if (hasStoredKey(provider)) {
dot.className = "key-status-dot configured";
dot.title =
provider.charAt(0).toUpperCase() + provider.slice(1) + " (User key)";
} else {
dot.className = "key-status-dot missing";
dot.title =
provider.charAt(0).toUpperCase() +
provider.slice(1) +
" (Not configured)";
}
});
// Toggle deploy button visibility
updateDeployButtonVisibility();
}
async function saveApiKeys() {
const flutterflowInput = document.getElementById("flutterflow-api-key-input");
const projectSelect = document.getElementById("flutterflow-projects-select");
// Only save if user entered a new value
if (flutterflowInput.value.trim()) {
await saveApiKey("flutterflow", flutterflowInput.value);
}
const selectedProjectId = projectSelect?.value.trim() || "";
if (selectedProjectId) {
if (!validateFlutterFlowProjectId(selectedProjectId)) {
showToast("The selected FlutterFlow project has an unexpected ID format.", "error");
projectSelect.focus();
return;
}
await saveApiKey("flutterflow_project_id", selectedProjectId);
}
// Reinitialize keys
await initializeApiKeys();
// Update UI
loadApiKeyInputs();
// Show confirmation
const btn = document.querySelector("#api-keys-modal .bg-blue-500");
const originalText = btn.textContent;
btn.textContent = "Saved!";
btn.classList.remove("bg-blue-500", "hover:bg-blue-600");
btn.classList.add("bg-green-500");
setTimeout(() => {
btn.textContent = originalText;
btn.classList.remove("bg-green-500");
btn.classList.add("bg-blue-500", "hover:bg-blue-600");
closeApiKeysModal();
}, 1000);
}
async function clearAllApiKeys() {
if (!confirm("Are you sure you want to clear all stored API keys?")) return;