Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
10105 lines (9115 loc) · 370 KB
/
Copy pathapp.js
File metadata and controls
10105 lines (9115 loc) · 370 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 {
closeModal,
initializeModalShells,
openModal,
setModalPending,
} from "./src/sharedControls.js";
import {
PLAN_LABELS as planLabels,
PLAN_LIMITS as planLimits,
PLAN_FEATURES as planFeatures,
} from "./src/plansSurface.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 {
getDeclaredDartTypes,
validateBundleCompatibility,
} from "./src/flutterFlowArtifactValidation.js";
import { applyFlutterFlowHeader } from "./src/flutterFlowHeader.js";
import { buildBundleDeployPlan } from "./src/bundleDeployPlanner.js";
import {
buildFinishPushFileMap,
excludeProvisionedCodeFiles,
findMissingCodeFiles,
isDeployFinishable,
partitionProvisionedCodeFiles,
} from "./src/flutterFlowCodeFileProvisioning.js";
import { buildReviewPresentation } from "./src/reviewPresentation.js";
import {
generateDeployRunId,
queryRunStatusWithinBudget,
} from "./src/runStatus.js";
import {
expectedWidgetClassFromFileName,
findUnbalancedBracketError,
getDeclaredWidgetClasses,
sanitizeGeneratedDart,
widgetFileNameForClass,
} from "./src/flutterFlowCodeSanitizer.js";
import { formatFlutterFlowFileError } from "./src/flutterFlowFileErrors.js";
import { extractPackageImports } from "./src/dartPackageImports.js";
import {
explainPlusAliasRule,
getMagicLinkResultMessage,
isKnownProviderPlusAlias,
isMagicLinkSuccess,
trimEmail,
} from "./src/authMagicLink.js";
import {
clearDisposableUiCaches,
createSendLinkController,
isDeleteAccountSupported,
performSignOut,
} from "./src/accountAccess.js";
import { planCustomCodeVerification } from "./src/customCodeVerification.js";
import {
deployOutcomeOfStreamResult,
isPreWriteRunnerFailure,
readProvisionResponse,
} from "./src/provisionStream.js";
import {
classifyDeployResult,
DeployOutcome,
DEPLOY_UI_TIMEOUT_MS,
exhaustedPushError,
PUSH_BODY_READ_TIMEOUT_MS,
UnconfirmedDeployError,
} from "./src/deployOutcome.js";
import { buildFlutterFlowSyncMetadata } from "./src/flutterFlowSyncMetadata.js";
import { initHeroMarkField } from "./src/heroMarkField.js";
import { createPipelineLogoLoop } from "./src/logoMotion.js";
import {
applyDependencyOverrides,
mergeDependenciesIntoYaml,
validateProjectPubspec,
} from "./src/pubspecSync.js";
import { planDependencyChanges } from "./src/dependencyResolution.js";
import { escapeAttr, escapeHtml, escapeHtmlText } from "./src/htmlEscape.js";
import { resolvePipelineErrorStep, classifyPipelineError } from "./src/pipelineErrors.js";
import {
extractCodeFromMarkdown,
highlightCode,
renderMarkdownAudit,
} from "./src/auditRenderer.js";
import { initComposer } from "./src/composerAdapter.js";
import { cancelSurfaceMotion, currentSurfaceRect, morphSurface, exitHero } from "./src/surfaceMotion.js";
// --- CONFIGURATION ---
const IS_DEV = import.meta.env.DEV
// The runner's CORS allowlist admits only the production origin, so a dev
// server must reach it through Vite's same-origin /api/ffai-runner proxy
// rather than calling the runner directly.
const FLUTTERFLOW_CLASS_PROVISION_ENDPOINT =
import.meta.env.VITE_FLUTTERFLOW_CLASS_PROVISION_ENDPOINT ||
import.meta.env.VITE_FLUTTERFLOW_DSL_DEPLOY_ENDPOINT ||
(IS_DEV
? "/api/ffai-runner/deployCustomClasses"
: "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'
// Where the user asked to sign in from (composer, plans, billing…), so a
// magic-link round trip — which reloads the page with no memory of the DOM —
// can return them to that surface instead of always landing on home.
const SIGNIN_RETURN_STORAGE_KEY = 'ccc_signin_return'
const SIGNIN_RETURN_TTL_MS = 30 * 60 * 1000
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 })
// Settles once startup auth + subscription fetches finish. The composer binds
// before they complete, so a submission that lands early waits on this rather
// than checking entitlements against free-tier defaults.
let sessionReadiness = Promise.resolve()
// --- 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_TOKEN_KEY = 'bs_identity_token'
const IDENTITY_ENDPOINT = `${BUILDSHIP_BASE_URL}/authUserCheck`
let identityState = {
userId: null,
token: null,
status: null, // 'recognized' | 'new' | null
resolved: false,
}
// --- TIER LIMITS ---
// Single source of truth in src/plansSurface.js so the plans page, the
// paywall and generation gating agree (STU-382 criterion 1).
const TIER_LIMITS = planLimits;
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.7-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.7-flash': 'Gemini 3.7 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
}
// Models whose image input is supported. Users can attach images to their
// prompt only when the selected model accepts vision through OpenRouter.
const IMAGE_SUPPORTED_MODELS = new Set([
'google/gemini-3.7-flash',
'anthropic/claude-opus-5',
'openai/gpt-5.6-sol',
'z-ai/glm-5.2',
'moonshotai/kimi-k3',
'openrouter/auto-beta',
])
function modelSupportsImages(model) {
return IMAGE_SUPPORTED_MODELS.has(model)
}
const MAX_PROMPT_IMAGES = 4
// Keep incoming files bounded so uploads stay quick. 8 MB per file is generous.
const MAX_PROMPT_IMAGE_BYTES = 8 * 1024 * 1024
const PIPELINE_IMAGE_ENDPOINT =
"https://4tgke4.buildship.run/service/runpipeline-image"
// Attached prompt images. Each item holds a local dataUrl (for the thumbnail
// preview) plus the uploaded url returned by the image endpoint — the url is
// what actually gets sent to the pipeline.
let promptImages = [] // Array of { dataUrl, name, url }
// In-flight attachment uploads, one entry per file: { slot, controller, job }.
// A submission that lands mid-upload waits on these before snapshotting
// promptImages, and the composer gates Send/Enter while any are pending.
// Ordering and cap claims live on the reserved slots in promptImages itself
// (url === null while a slot is pending); removing a slot aborts its entry.
const pendingImageUploads = []
// An unresponsive upload endpoint must not gate the composer forever.
const PROMPT_IMAGE_UPLOAD_TIMEOUT_MS = 30000
// Handle returned by initComposer; lets attachment state gate the Send button.
let composerControls = null
function readAsDataUrl(file, signal) {
return new Promise((resolve) => {
const reader = new FileReader()
const done = (value) => {
signal?.removeEventListener("abort", onAbort)
resolve(value)
}
const onAbort = () => {
reader.abort()
done(null)
}
reader.onload = () => done(reader.result)
reader.onerror = () => done(null)
// The upload timeout aborts this too: a FileReader that never settles
// must not hold its slot (and the send gate) forever.
if (signal) {
if (signal.aborted) { resolve(null); return }
signal.addEventListener("abort", onAbort, { once: true })
}
reader.readAsDataURL(file)
})
}
// Uploads one image file to the BuildShip image endpoint. The endpoint is
// called separately from the pipeline so we pass real URLs, not base64.
async function uploadPromptImage(file, signal) {
const formData = new FormData()
formData.append("file", file)
const res = await fetch(PIPELINE_IMAGE_ENDPOINT, {
method: "POST",
body: formData,
signal,
})
return res.json()
}
// Normalises an uploaded file object into a URL string. The image endpoint
// returns an ARRAY of per-file results, e.g.
// [{ item: {...file meta...}, index: 0, "<workflow-uuid>": { type: "external-url", file: "https://..." } }]
// The external URL is under the entry's non-item/non-index key → .file.
function uploadedFileUrl(uploaded) {
if (Array.isArray(uploaded)) {
const first = uploaded[0]
if (first && typeof first === "object") {
for (const key of Object.keys(first)) {
if (key === "item" || key === "index") continue
const entry = first[key]
if (entry && typeof entry === "object") {
if (typeof entry.file === "string") return entry.file
if (typeof entry.url === "string") return entry.url
}
if (typeof entry === "string") return entry
}
}
return ""
}
if (typeof uploaded === "string") return uploaded
if (uploaded && typeof uploaded === "object") {
return (
uploaded.url ||
uploaded.fileUrl ||
uploaded.file_url ||
uploaded.downloadUrl ||
uploaded.imageUrl ||
uploaded.image_url ||
uploaded.file ||
""
)
}
return ""
}
// Uploads one selected file into its reserved promptImages slot. The slot
// fixes the file's position and its claim on the cap at selection time; on
// failure the slot is removed, on user removal the commit is skipped.
// Resolves "added", "failed" (no usable upload URL, including a timeout),
// or "dropped" (the slot was removed while the upload was in flight).
async function addPromptImage(file, slot, signal) {
const dataUrl = await readAsDataUrl(file, signal)
if (dataUrl && promptImages.includes(slot)) {
// Fast local preview while the upload is still in flight.
slot.dataUrl = dataUrl
renderPromptImages()
}
let url = ""
if (dataUrl) {
try {
url = uploadedFileUrl(await uploadPromptImage(file, signal))
} catch (e) {
url = ""
}
}
// The slot may have been removed while the upload was in flight (remove
// button, or a non-vision model switch clearing attachments) — commit
// nothing then. discardImageUpload has already released the pending gate.
if (!promptImages.includes(slot)) return "dropped"
// A file that never produced an upload URL is reported by the caller and
// its slot removed — keeping it would render a thumbnail the pipeline
// silently filters out of the payload.
if (!dataUrl || !url) {
promptImages.splice(promptImages.indexOf(slot), 1)
renderPromptImages()
return "failed"
}
slot.url = url
renderPromptImages()
return "added"
}
function releaseImageUpload(entry) {
const i = pendingImageUploads.indexOf(entry)
if (i >= 0) pendingImageUploads.splice(i, 1)
updateAttachmentPending()
}
// Drop a pending upload: abort its request, free the send gate immediately,
// and pull the slot if it is still attached. A settled upload is already out
// of pendingImageUploads and can't reach this path.
function discardImageUpload(entry) {
entry.controller.abort()
releaseImageUpload(entry)
const i = promptImages.indexOf(entry.slot)
if (i >= 0) {
promptImages.splice(i, 1)
renderPromptImages()
}
}
function updateAttachmentPending() {
composerControls?.setAttachmentsPending(pendingImageUploads.length > 0)
}
async function handlePromptImageSelect(event) {
const files = Array.from(event.target.files || [])
if (!files.length) return
// Clear immediately so picking the same files again fires a change event.
event.target.value = ""
// A run already in flight has snapshotted its attachments; refuse new
// selections so an upload can't appear to belong to a run that omitted it.
if (pipelineState.isRunning) {
showToast("Wait for the current generation to finish before attaching images.", "info")
return
}
// Drop oversized files up front rather than uploading/reading them.
const oversized = files.filter((f) => f.size > MAX_PROMPT_IMAGE_BYTES)
if (oversized.length) {
showToast(
`Skipped ${oversized.length} image(s) over the ${(MAX_PROMPT_IMAGE_BYTES / 1024 / 1024).toFixed(0)} MB limit.`,
"warning",
)
}
const validFiles = files.filter((f) => f.size <= MAX_PROMPT_IMAGE_BYTES)
if (!validFiles.length) return
// Reserved slots already count toward the cap, so a second selection can't
// claim slots the first one is still filling.
const remaining = MAX_PROMPT_IMAGES - promptImages.length
const toAdd = validFiles.slice(0, remaining)
if (validFiles.length > remaining) {
showToast(`You can attach up to ${MAX_PROMPT_IMAGES} images.`, "info")
}
if (!toAdd.length) return
const jobs = toAdd.map((file) => {
// Reserve the ordered slot synchronously: thumbnails and the payload keep
// selection order even when uploads finish out of order.
const slot = { dataUrl: null, name: file.name, url: null }
promptImages.push(slot)
const entry = { slot, controller: new AbortController() }
const timeoutId = setTimeout(
() => entry.controller.abort(),
PROMPT_IMAGE_UPLOAD_TIMEOUT_MS,
)
entry.job = addPromptImage(file, slot, entry.controller.signal)
pendingImageUploads.push(entry)
entry.job.finally(() => {
clearTimeout(timeoutId)
releaseImageUpload(entry)
})
return entry.job
})
renderPromptImages()
updateAttachmentPending()
const results = await Promise.all(jobs)
const failed = results.filter((r) => r === "failed").length
if (failed) {
showToast(`${failed} image(s) could not be uploaded and were not attached.`, "error")
}
}
function removePromptImage(index) {
// A run already in flight snapshotted its attachments: removing a slot now
// would abort the upload that slot was promised, silently dropping a
// submitted image from the run's payload.
if (pipelineState.isRunning) {
showToast("Wait for the current generation to finish before removing images.", "info")
return
}
const slot = promptImages[index]
const entry = pendingImageUploads.find((e) => e.slot === slot)
// Removing a pending thumbnail aborts its upload and frees the send gate
// right away instead of waiting on the abandoned request.
if (entry) {
discardImageUpload(entry)
return
}
promptImages.splice(index, 1)
renderPromptImages()
}
function renderPromptImages() {
const container = document.getElementById("prompt-image-thumbnails")
const label = document.getElementById("prompt-image-btn-label")
if (!container) return
container.innerHTML = ""
promptImages.forEach((img, i) => {
const el = document.createElement("div")
// A slot whose upload is still in flight (url === null) renders dimmed
// with a spinner; it can already carry a local dataUrl preview.
el.className = "prompt-img-thumb" + (img.url ? "" : " is-pending")
el.innerHTML =
(img.dataUrl ? `<img src="${escapeAttr(img.dataUrl)}" alt="Prompt image">` : "") +
`<button type="button" class="prompt-img-remove" title="Remove image" onclick="removePromptImage(${i})">×</button>`
container.appendChild(el)
})
if (label) {
label.textContent =
promptImages.length >= MAX_PROMPT_IMAGES ? "Image limit reached" : "Add images"
}
}
function updatePromptImageAvailability() {
const section = document.getElementById("prompt-image-upload")
if (!section) return
const select = document.getElementById("code-generator-model")
const supports = modelSupportsImages(select?.value)
section.classList.toggle("hidden", !supports)
// Non-vision models have no way to consume images: drop any already
// attached. A run already in flight snapshotted its attachments — dropping
// them now would abort uploads the run's frozen slice still expects to
// commit, silently stripping the images it was started with.
if (!supports && promptImages.length && !pipelineState.isRunning) {
// Abort uploads still in flight so they release the send gate now.
pendingImageUploads.slice().forEach(discardImageUpload)
promptImages = []
renderPromptImages()
}
}
const USAGE_STORAGE_KEY = 'ccc_usage'
// Model Configuration
const PROMPT_ARCHITECT_MODEL = "google/gemini-3.7-flash"
const CODE_REVIEW_MODEL = "google/gemini-3.7-flash"
const FALLBACK_MODEL = "google/gemini-3.7-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);