@adminide-stack/yantra-mobile 12.0.163 → 12.0.164-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/components/CustomDrawer.js +8 -1
- package/lib/components/CustomDrawer.js.map +1 -1
- package/lib/components/NavigationHeader/HeaderSheet.js +23 -8
- package/lib/components/NavigationHeader/HeaderSheet.js.map +1 -1
- package/lib/components/NavigationHeader/HeaderSkillsButton.js +6 -3
- package/lib/components/NavigationHeader/HeaderSkillsButton.js.map +1 -1
- package/lib/components/NavigationHeader/HeaderSystemButtons.js +7 -0
- package/lib/components/NavigationHeader/HeaderSystemButtons.js.map +1 -0
- package/lib/components/NavigationHeader/HeaderTasksButton.js +144 -93
- package/lib/components/NavigationHeader/HeaderTasksButton.js.map +1 -1
- package/lib/components/NavigationHeader/NavigationHeader.js +2 -2
- package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -1
- package/lib/features/agent-chat/NativeAgentChat.js +3 -3
- package/lib/features/agent-chat/NativeAgentChat.js.map +1 -1
- package/lib/features/audio-input/AudioRecorderPanel.js +1 -1
- package/lib/features/audio-input/NativeDictationBar.js +1 -1
- package/lib/features/canvas/CanvasExperience.js +1 -1
- package/lib/features/channels/ConnectAppsSheet.js +1 -1
- package/lib/features/channels/HomeImessage.js +1 -1
- package/lib/features/channels/useChannelsApi.js +1 -1
- package/lib/features/chat/OneTimeCodePrompt.js +1 -1
- package/lib/features/chat/QueuedFollowUps.js +4 -3
- package/lib/features/chat/QueuedFollowUps.js.map +1 -1
- package/lib/features/chat/TemporaryChatView.js +238 -0
- package/lib/features/chat/TemporaryChatView.js.map +1 -0
- package/lib/features/chat/connectorConnect.js +1 -1
- package/lib/features/chat/temporaryChatStore.js +59 -7
- package/lib/features/chat/temporaryChatStore.js.map +1 -1
- package/lib/features/chat/withTemporaryChat.js +24 -0
- package/lib/features/chat/withTemporaryChat.js.map +1 -0
- package/lib/features/dictate/recorderStatus.js +22 -0
- package/lib/features/dictate/recorderStatus.js.map +1 -0
- package/lib/features/dictate/useDictationRecorder.js +4 -4
- package/lib/features/dictate/useDictationRecorder.js.map +1 -1
- package/lib/features/home/sky/HomeSky.js +1 -1
- package/lib/features/skills/SkillTemplatePicker.js +107 -143
- package/lib/features/skills/SkillTemplatePicker.js.map +1 -1
- package/lib/features/webbuilder/WebBuilderExperience.js +402 -33
- package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
- package/lib/features/webbuilder/components/CloudSheet.js +35 -15
- package/lib/features/webbuilder/components/CloudSheet.js.map +1 -1
- package/lib/features/webbuilder/components/Credits.js +149 -0
- package/lib/features/webbuilder/components/Credits.js.map +1 -0
- package/lib/features/webbuilder/components/PreviewFrame.js +15 -4
- package/lib/features/webbuilder/components/PreviewFrame.js.map +1 -1
- package/lib/features/webbuilder/components/PreviewScreen.js +5 -2
- package/lib/features/webbuilder/components/PreviewScreen.js.map +1 -1
- package/lib/features/webbuilder/components/ProjectChat.js +58 -8
- package/lib/features/webbuilder/components/ProjectChat.js.map +1 -1
- package/lib/features/webbuilder/components/ProjectSheets.js +29 -6
- package/lib/features/webbuilder/components/ProjectSheets.js.map +1 -1
- package/lib/features/webbuilder/components/ProjectsScreen.js +16 -7
- package/lib/features/webbuilder/components/ProjectsScreen.js.map +1 -1
- package/lib/features/webbuilder/components/PublishSheet.js +133 -2
- package/lib/features/webbuilder/components/PublishSheet.js.map +1 -1
- package/lib/features/webbuilder/components/RetentionBanner.js +130 -0
- package/lib/features/webbuilder/components/RetentionBanner.js.map +1 -0
- package/lib/features/webbuilder/components/ShareSheet.js +265 -0
- package/lib/features/webbuilder/components/ShareSheet.js.map +1 -0
- package/lib/features/webbuilder/components/SiteStatusSheet.js +533 -0
- package/lib/features/webbuilder/components/SiteStatusSheet.js.map +1 -0
- package/lib/features/webbuilder/components/StudioHome.js +8 -1
- package/lib/features/webbuilder/components/StudioHome.js.map +1 -1
- package/lib/features/webbuilder/components/TemplateSuggestions.js +98 -0
- package/lib/features/webbuilder/components/TemplateSuggestions.js.map +1 -0
- package/lib/features/webbuilder/connectorTemplates.js +3 -3
- package/lib/features/webbuilder/connectorTemplates.js.map +1 -1
- package/lib/features/webbuilder/creditsLinks.js +5 -0
- package/lib/features/webbuilder/creditsLinks.js.map +1 -0
- package/lib/features/webbuilder/previewAccess.js +207 -0
- package/lib/features/webbuilder/previewAccess.js.map +1 -0
- package/lib/features/webbuilder/previewProbe.js +49 -1
- package/lib/features/webbuilder/previewProbe.js.map +1 -1
- package/lib/features/webbuilder/readiness.js +14 -0
- package/lib/features/webbuilder/readiness.js.map +1 -0
- package/lib/features/webbuilder/shareLink.js +26 -0
- package/lib/features/webbuilder/shareLink.js.map +1 -0
- package/lib/features/webbuilder/templateCover.js +11 -0
- package/lib/features/webbuilder/templateCover.js.map +1 -0
- package/lib/features/webbuilder/templateSuggestions.js +112 -0
- package/lib/features/webbuilder/templateSuggestions.js.map +1 -0
- package/lib/features/webbuilder/useGithubAutoSync.js +83 -0
- package/lib/features/webbuilder/useGithubAutoSync.js.map +1 -0
- package/lib/features/webbuilder/usePreviewAccess.js +61 -0
- package/lib/features/webbuilder/usePreviewAccess.js.map +1 -0
- package/lib/features/webbuilder/useWebBuilderCredits.js +99 -0
- package/lib/features/webbuilder/useWebBuilderCredits.js.map +1 -0
- package/lib/features/webbuilder/web/credits/credits.js +203 -0
- package/lib/features/webbuilder/web/credits/credits.js.map +1 -0
- package/lib/features/webbuilder/web/credits/creditsReader.js +65 -0
- package/lib/features/webbuilder/web/credits/creditsReader.js.map +1 -0
- package/lib/features/webbuilder/web/data/cloud.js +3 -3
- package/lib/features/webbuilder/web/data/cloud.js.map +1 -1
- package/lib/features/webbuilder/web/data/database.js +4 -1
- package/lib/features/webbuilder/web/data/database.js.map +1 -1
- package/lib/features/webbuilder/web/github/autoSync.js +231 -0
- package/lib/features/webbuilder/web/github/autoSync.js.map +1 -0
- package/lib/features/webbuilder/web/github/autoSyncEngine.js +367 -0
- package/lib/features/webbuilder/web/github/autoSyncEngine.js.map +1 -0
- package/lib/features/webbuilder/web/github/githubSync.js +54 -0
- package/lib/features/webbuilder/web/github/githubSync.js.map +1 -0
- package/lib/features/webbuilder/web/history/versions.js +83 -0
- package/lib/features/webbuilder/web/history/versions.js.map +1 -0
- package/lib/features/webbuilder/web/project/retention.js +217 -0
- package/lib/features/webbuilder/web/project/retention.js.map +1 -0
- package/lib/features/webbuilder/web/publish/actionErrors.js +81 -0
- package/lib/features/webbuilder/web/publish/actionErrors.js.map +1 -0
- package/lib/features/webbuilder/web/publish/publishSteps.js +86 -0
- package/lib/features/webbuilder/web/publish/publishSteps.js.map +1 -0
- package/lib/features/webbuilder/web/publish/siteAddress.js +79 -0
- package/lib/features/webbuilder/web/publish/siteAddress.js.map +1 -0
- package/lib/features/webbuilder/web/publish/siteHealth.js +497 -0
- package/lib/features/webbuilder/web/publish/siteHealth.js.map +1 -0
- package/lib/features/webbuilder/web/publish/siteInsights.js +145 -0
- package/lib/features/webbuilder/web/publish/siteInsights.js.map +1 -0
- package/lib/features/webbuilder/web/sharing/roles.js +108 -2
- package/lib/features/webbuilder/web/sharing/roles.js.map +1 -1
- package/lib/features/webbuilder/web/sharing/share.js +52 -0
- package/lib/features/webbuilder/web/sharing/share.js.map +1 -0
- package/lib/features/webbuilder/web/sharing/sharingApi.js +199 -0
- package/lib/features/webbuilder/web/sharing/sharingApi.js.map +1 -0
- package/lib/features/webbuilder/web/webServices.js +13 -2
- package/lib/features/webbuilder/web/webServices.js.map +1 -1
- package/lib/features/webbuilder/webbuilderPrompts.js +4 -1
- package/lib/features/webbuilder/webbuilderPrompts.js.map +1 -1
- package/lib/features/webbuilder/workflow.js +2 -2
- package/lib/features/webbuilder/workflow.js.map +1 -1
- package/lib/hooks/useSurfaceJobs.js +113 -28
- package/lib/hooks/useSurfaceJobs.js.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/screens/Chat/index.js +3 -2
- package/lib/screens/Chat/index.js.map +1 -1
- package/lib/screens/Home/HomeScreen.js +1 -1
- package/lib/screens/Home/components/BuildTemplatesSection.js +1 -1
- package/lib/screens/Home/components/ChooseTemplateModal.js +1 -1
- package/lib/screens/Home/components/HomeHero.js +1 -1
- package/lib/screens/Home/components/HomeSuggestions.js +1 -1
- package/lib/screens/Home/components/TemplateBrowserModal.js +1 -1
- package/lib/screens/Home/index.js +1 -1
- package/lib/screens/Home/index.js.map +1 -1
- package/lib/screens/WebBuilderNative/index.js +1 -1
- package/lib/screens/WebBuilderNative/index.js.map +1 -1
- package/lib/screens/WebBuilderNative/sandboxProxyApi.js +33 -3
- package/lib/screens/WebBuilderNative/sandboxProxyApi.js.map +1 -1
- package/lib/screens/WebBuilderNative/useWebBuilderHost.js +33 -13
- package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
- package/lib/screens/WebBuilderNative/useWebBuilderJobs.js +11 -4
- package/lib/screens/WebBuilderNative/useWebBuilderJobs.js.map +1 -1
- package/lib/screens/WebBuilderNative/webbuilderTransport.js +1 -1
- package/lib/screens/WebBuilderNative/webbuilderTransport.js.map +1 -1
- package/lib/services/brainQuickReply.js +47 -14
- package/lib/services/brainQuickReply.js.map +1 -1
- package/package.json +4 -4
- package/lib/components/NavigationHeader/HeaderMoreMenu.js +0 -78
- package/lib/components/NavigationHeader/HeaderMoreMenu.js.map +0 -1
- package/lib/components/NavigationHeader/HeaderSettingsMenu.js +0 -132
- package/lib/components/NavigationHeader/HeaderSettingsMenu.js.map +0 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {useRef,useState,useCallback,useMemo,useEffect,useSyncExternalStore}from'react';import {GithubAutoSync}from'./web/github/autoSyncEngine.js';import {IDLE_STATUS}from'./web/github/autoSync.js';const SYNC_TIMEOUT_MS = 3e5;
|
|
2
|
+
const noop = () => () => void 0;
|
|
3
|
+
function useGithubAutoSync(opts) {
|
|
4
|
+
var _a;
|
|
5
|
+
const {
|
|
6
|
+
services,
|
|
7
|
+
run,
|
|
8
|
+
channelId,
|
|
9
|
+
build
|
|
10
|
+
} = opts;
|
|
11
|
+
const live = useRef(opts);
|
|
12
|
+
live.current = opts;
|
|
13
|
+
const [settings, setSettings] = useState(null);
|
|
14
|
+
const [epoch, setEpoch] = useState(0);
|
|
15
|
+
const reload = useCallback(() => setEpoch((n) => n + 1), []);
|
|
16
|
+
const engine = useMemo(() => {
|
|
17
|
+
if (!services || !run) return null;
|
|
18
|
+
return new GithubAutoSync({
|
|
19
|
+
run: async (channel, action, params) => {
|
|
20
|
+
var _a2;
|
|
21
|
+
const {
|
|
22
|
+
build: current,
|
|
23
|
+
channelId: open,
|
|
24
|
+
run: runNow
|
|
25
|
+
} = live.current;
|
|
26
|
+
if (!current || !runNow || channel !== open) return {
|
|
27
|
+
successful: false,
|
|
28
|
+
error: "The project is not open."
|
|
29
|
+
};
|
|
30
|
+
const r = await runNow(current, action, params, SYNC_TIMEOUT_MS);
|
|
31
|
+
return {
|
|
32
|
+
successful: r.successful,
|
|
33
|
+
data: r.data,
|
|
34
|
+
error: (_a2 = r.error) != null ? _a2 : void 0
|
|
35
|
+
};
|
|
36
|
+
},
|
|
37
|
+
settings: async (channel) => {
|
|
38
|
+
var _a2, _b;
|
|
39
|
+
return (_b = (_a2 = await services.serverSettings(channel).catch(() => null)) == null ? void 0 : _a2.github) != null ? _b : null;
|
|
40
|
+
},
|
|
41
|
+
role: (channel) => services.sharing.myRole(channel).catch(() => null),
|
|
42
|
+
sandboxOf: (channel) => {
|
|
43
|
+
var _a2, _b;
|
|
44
|
+
return channel === live.current.channelId ? (_b = (_a2 = live.current.build) == null ? void 0 : _a2.sandboxId) != null ? _b : null : null;
|
|
45
|
+
},
|
|
46
|
+
channelOfSandbox: (sandboxId2) => {
|
|
47
|
+
var _a2;
|
|
48
|
+
return ((_a2 = live.current.build) == null ? void 0 : _a2.sandboxId) === sandboxId2 ? live.current.channelId : null;
|
|
49
|
+
},
|
|
50
|
+
reloadPreview: () => live.current.onPreviewChanged(),
|
|
51
|
+
settingsChanged: () => setEpoch((n) => n + 1)
|
|
52
|
+
});
|
|
53
|
+
}, [services, run]);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
setSettings(null);
|
|
56
|
+
if (!services || !channelId) return void 0;
|
|
57
|
+
let current = true;
|
|
58
|
+
services.serverSettings(channelId).then((s) => {
|
|
59
|
+
var _a2;
|
|
60
|
+
if (!current) return;
|
|
61
|
+
const github = (_a2 = s == null ? void 0 : s.github) != null ? _a2 : null;
|
|
62
|
+
setSettings(github);
|
|
63
|
+
engine == null ? void 0 : engine.seed(channelId, github);
|
|
64
|
+
}).catch(() => void 0);
|
|
65
|
+
return () => {
|
|
66
|
+
current = false;
|
|
67
|
+
};
|
|
68
|
+
}, [services, engine, channelId, epoch]);
|
|
69
|
+
const sandboxId = (_a = build == null ? void 0 : build.sandboxId) != null ? _a : null;
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
if (engine && channelId && sandboxId) engine.openProject(channelId).catch(() => void 0);
|
|
72
|
+
}, [engine, channelId, sandboxId]);
|
|
73
|
+
const subscribe = useCallback((fn) => engine ? engine.subscribe(fn) : noop(), [engine]);
|
|
74
|
+
const status = useSyncExternalStore(subscribe, () => engine ? engine.status(channelId) : IDLE_STATUS);
|
|
75
|
+
const prompt = useSyncExternalStore(subscribe, () => engine ? engine.prompt() : null);
|
|
76
|
+
return {
|
|
77
|
+
engine,
|
|
78
|
+
settings,
|
|
79
|
+
status,
|
|
80
|
+
prompt,
|
|
81
|
+
reload
|
|
82
|
+
};
|
|
83
|
+
}export{useGithubAutoSync};//# sourceMappingURL=useGithubAutoSync.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useGithubAutoSync.js","sources":["../../../src/features/webbuilder/useGithubAutoSync.ts"],"sourcesContent":["/**\n * GitHub \"Keep in sync\" for the open project - the web's `GithubAutoSync` engine (W29), unchanged,\n * on this app's sandbox calls: it pulls when the project opens and before each AI turn (fast-forward\n * only), pushes after a turn that changed the code, and asks once when GitHub and the project both\n * changed. Also the project's GitHub settings, re-read after every sync, for the menu's status lines.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { GithubAutoSync, type DivergedPrompt } from './web/github/autoSyncEngine';\nimport { IDLE_STATUS, type SyncStatus } from './web/github/autoSync';\nimport type { ProjectGithubSettings } from './web/project/serverSettings';\nimport type { WebServices } from './web/webServices';\nimport type { WebBuilderActionResult, WebBuilderBuild } from './types';\n\nconst SYNC_TIMEOUT_MS = 300_000;\n\ntype RunAction = (\n build: WebBuilderBuild,\n action: string,\n params: Record<string, unknown>,\n timeoutMs?: number,\n) => Promise<WebBuilderActionResult>;\n\nexport interface GithubSyncState {\n engine: GithubAutoSync | null;\n settings: ProjectGithubSettings | null;\n status: SyncStatus;\n prompt: DivergedPrompt | null;\n /** Re-read the GitHub settings (after a push or a toggle). */\n reload: () => void;\n}\n\nconst noop = () => () => undefined;\n\nexport function useGithubAutoSync(opts: {\n services: WebServices | null;\n run?: RunAction;\n channelId: string | null;\n build: WebBuilderBuild | null;\n /** The preview reloads after a pull changed the code. */\n onPreviewChanged: () => void;\n}): GithubSyncState {\n const { services, run, channelId, build } = opts;\n const live = useRef(opts);\n live.current = opts;\n const [settings, setSettings] = useState<ProjectGithubSettings | null>(null);\n const [epoch, setEpoch] = useState(0);\n const reload = useCallback(() => setEpoch((n) => n + 1), []);\n\n const engine = useMemo(() => {\n if (!services || !run) return null;\n return new GithubAutoSync({\n run: async (channel, action, params) => {\n const { build: current, channelId: open, run: runNow } = live.current;\n if (!current || !runNow || channel !== open)\n return { successful: false, error: 'The project is not open.' };\n const r = await runNow(current, action, params, SYNC_TIMEOUT_MS);\n return { successful: r.successful, data: r.data, error: r.error ?? undefined };\n },\n settings: async (channel) => (await services.serverSettings(channel).catch(() => null))?.github ?? null,\n role: (channel) => services.sharing.myRole(channel).catch(() => null),\n sandboxOf: (channel) =>\n channel === live.current.channelId ? (live.current.build?.sandboxId ?? null) : null,\n channelOfSandbox: (sandboxId) =>\n live.current.build?.sandboxId === sandboxId ? live.current.channelId : null,\n reloadPreview: () => live.current.onPreviewChanged(),\n settingsChanged: () => setEpoch((n) => n + 1),\n });\n // One engine per services/runner: the open project and build are read live.\n }, [services, run]);\n\n // The project's GitHub settings: read on open and after each sync; they seed the status.\n useEffect(() => {\n setSettings(null);\n if (!services || !channelId) return undefined;\n let current = true;\n services\n .serverSettings(channelId)\n .then((s) => {\n if (!current) return;\n const github = s?.github ?? null;\n setSettings(github);\n engine?.seed(channelId, github);\n })\n .catch(() => undefined);\n return () => {\n current = false;\n };\n }, [services, engine, channelId, epoch]);\n\n // Opening a project pulls once (fast-forward only), when sync is on.\n const sandboxId = build?.sandboxId ?? null;\n useEffect(() => {\n if (engine && channelId && sandboxId) engine.openProject(channelId).catch(() => undefined);\n }, [engine, channelId, sandboxId]);\n\n const subscribe = useCallback((fn: () => void) => (engine ? engine.subscribe(fn) : noop()), [engine]);\n const status = useSyncExternalStore(subscribe, () => (engine ? engine.status(channelId) : IDLE_STATUS));\n const prompt = useSyncExternalStore(subscribe, () => (engine ? engine.prompt() : null));\n return { engine, settings, status, prompt, reload };\n}\n"],"names":["_a","sandboxId"],"mappings":"sMAYA,MAAM,eAAkB,GAAA,GAAA;AAUxB,MAAM,IAAA,GAAO,MAAM,MAAM,MAAA;AAClB,SAAS,kBAAkB,IAOd,EAAA;AA9BpB,EAAA,IAAA,EAAA;AA+BE,EAAM,MAAA;AAAA,IACJ,QAAA;AAAA,IACA,GAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACE,GAAA,IAAA;AACJ,EAAM,MAAA,IAAA,GAAO,OAAO,IAAI,CAAA;AACxB,EAAA,IAAA,CAAK,OAAU,GAAA,IAAA;AACf,EAAA,MAAM,CAAC,QAAA,EAAU,WAAW,CAAA,GAAI,SAAuC,IAAI,CAAA;AAC3E,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAI,SAAS,CAAC,CAAA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AA;AAAA,IACA,QAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {jsx}from'react/jsx-runtime';import {createContext,useContext,useState,useEffect,useMemo}from'react';import {Linking}from'react-native';const PreviewAccessContext = createContext({
|
|
2
|
+
access: null,
|
|
3
|
+
channelId: null
|
|
4
|
+
});
|
|
5
|
+
function PreviewAccessProvider({
|
|
6
|
+
access,
|
|
7
|
+
channelId,
|
|
8
|
+
children
|
|
9
|
+
}) {
|
|
10
|
+
const value = useMemo(() => ({
|
|
11
|
+
access: access != null ? access : null,
|
|
12
|
+
channelId
|
|
13
|
+
}), [access, channelId]);
|
|
14
|
+
return /* @__PURE__ */ jsx(PreviewAccessContext.Provider, { value, children });
|
|
15
|
+
}
|
|
16
|
+
function usePreviewAccess() {
|
|
17
|
+
return useContext(PreviewAccessContext);
|
|
18
|
+
}
|
|
19
|
+
function usePreviewSrc(rawUrl, opts) {
|
|
20
|
+
var _a, _b;
|
|
21
|
+
const ctx = usePreviewAccess();
|
|
22
|
+
const {
|
|
23
|
+
access
|
|
24
|
+
} = ctx;
|
|
25
|
+
const channelId = (opts == null ? void 0 : opts.channelId) !== void 0 ? opts.channelId : ctx.channelId;
|
|
26
|
+
const raw = rawUrl || void 0;
|
|
27
|
+
const gated = Boolean(access && raw && channelId && access.gated(raw));
|
|
28
|
+
const key = `${raw != null ? raw : ""}|${channelId != null ? channelId : ""}|${(_a = opts == null ? void 0 : opts.resetKey) != null ? _a : ""}`;
|
|
29
|
+
const [pinned, setPinned] = useState(null);
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!gated || !access || !raw) return void 0;
|
|
32
|
+
const ready = access.peek(raw, channelId);
|
|
33
|
+
if (ready !== null) {
|
|
34
|
+
setPinned((p) => (p == null ? void 0 : p.key) === key ? p : {
|
|
35
|
+
key,
|
|
36
|
+
url: ready
|
|
37
|
+
});
|
|
38
|
+
return void 0;
|
|
39
|
+
}
|
|
40
|
+
let live = true;
|
|
41
|
+
access.resolve(raw, channelId).then((url) => {
|
|
42
|
+
if (live) setPinned({
|
|
43
|
+
key,
|
|
44
|
+
url
|
|
45
|
+
});
|
|
46
|
+
}).catch(() => void 0);
|
|
47
|
+
return () => {
|
|
48
|
+
live = false;
|
|
49
|
+
};
|
|
50
|
+
}, [access, channelId, gated, key, raw]);
|
|
51
|
+
if (!raw || !gated || !access) return raw;
|
|
52
|
+
if ((pinned == null ? void 0 : pinned.key) === key) return pinned.url;
|
|
53
|
+
return (_b = access.peek(raw, channelId)) != null ? _b : void 0;
|
|
54
|
+
}
|
|
55
|
+
const OPEN_PREVIEW_MIN_VALID_MS = 5 * 6e4;
|
|
56
|
+
async function openPreviewInBrowser(access, rawUrl, channelId) {
|
|
57
|
+
const url = access ? await access.resolve(rawUrl, channelId, {
|
|
58
|
+
minValidMs: OPEN_PREVIEW_MIN_VALID_MS
|
|
59
|
+
}) : rawUrl;
|
|
60
|
+
await Linking.openURL(url);
|
|
61
|
+
}export{OPEN_PREVIEW_MIN_VALID_MS,PreviewAccessProvider,openPreviewInBrowser,usePreviewAccess,usePreviewSrc};//# sourceMappingURL=usePreviewAccess.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usePreviewAccess.js","sources":["../../../src/features/webbuilder/usePreviewAccess.tsx"],"sourcesContent":["/**\n * Private previews in React Native (see previewAccess.ts): the host's preview access and the open site in\n * context, the `uri` a preview WebView loads, and opening a preview in the browser. Without a host service\n * (an older host) every preview loads its raw URL, as before.\n */\nimport React, { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';\nimport { Linking } from 'react-native';\nimport type { PreviewAccess } from './previewAccess';\n\nexport interface PreviewAccessValue {\n access: PreviewAccess | null;\n /** The open site (its chat): the project a preview's token is asked for. */\n channelId: string | null;\n}\n\nconst PreviewAccessContext = createContext<PreviewAccessValue>({ access: null, channelId: null });\n\nexport function PreviewAccessProvider({\n access,\n channelId,\n children,\n}: {\n access: PreviewAccess | null | undefined;\n channelId: string | null;\n children: ReactNode;\n}) {\n const value = useMemo(() => ({ access: access ?? null, channelId }), [access, channelId]);\n return <PreviewAccessContext.Provider value={value}>{children}</PreviewAccessContext.Provider>;\n}\n\nexport function usePreviewAccess(): PreviewAccessValue {\n return useContext(PreviewAccessContext);\n}\n\n/**\n * The `uri` for a live preview WebView: `rawUrl`, with a preview token when the proxy gates its sandbox.\n * `undefined` while the first lookup for it runs (a few seconds at most, then the raw URL). Pinned per\n * `rawUrl` and `resetKey`: a token refreshed in the cache never reloads a page that is already open.\n * `channelId`: the site, when it is not the open one (a Projects row).\n */\nexport function usePreviewSrc(\n rawUrl: string | null | undefined,\n opts?: { channelId?: string | null; resetKey?: string | number },\n): string | undefined {\n const ctx = usePreviewAccess();\n const { access } = ctx;\n const channelId = opts?.channelId !== undefined ? opts.channelId : ctx.channelId;\n const raw = rawUrl || undefined;\n const gated = Boolean(access && raw && channelId && access.gated(raw));\n const key = `${raw ?? ''}|${channelId ?? ''}|${opts?.resetKey ?? ''}`;\n const [pinned, setPinned] = useState<{ key: string; url: string } | null>(null);\n useEffect(() => {\n if (!gated || !access || !raw) return undefined;\n const ready = access.peek(raw, channelId);\n if (ready !== null) {\n setPinned((p) => (p?.key === key ? p : { key, url: ready }));\n return undefined;\n }\n let live = true;\n access\n .resolve(raw, channelId)\n .then((url) => {\n if (live) setPinned({ key, url });\n })\n .catch(() => undefined);\n return () => {\n live = false;\n };\n }, [access, channelId, gated, key, raw]);\n if (!raw || !gated || !access) return raw;\n if (pinned?.key === key) return pinned.url;\n return access.peek(raw, channelId) ?? undefined;\n}\n\n/** A link opened in the browser is used at once: a token with this much left is plenty. */\nexport const OPEN_PREVIEW_MIN_VALID_MS = 5 * 60_000;\n\n/**\n * Open a site link in the browser, for this person: a gated preview first gets its token (minted now, or\n * a cached one with minutes left), so the browser is let in; a published site, or a failed lookup, opens\n * the raw link. The browser opens only once the link is ready.\n */\nexport async function openPreviewInBrowser(\n access: PreviewAccess | null,\n rawUrl: string,\n channelId: string | null | undefined,\n): Promise<void> {\n const url = access ? await access.resolve(rawUrl, channelId, { minValidMs: OPEN_PREVIEW_MIN_VALID_MS }) : rawUrl;\n await Linking.openURL(url);\n}\n"],"names":[],"mappings":"+IAaA,MAAM,uBAAuB,aAAkC,CAAA;AAAA,EAC7D,MAAQ,EAAA,IAAA;AAAA,EACR,SAAW,EAAA;AACb,CAAC,CAAA;AACM,SAAS,qBAAsB,CAAA;AAAA,EACpC,MAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAIG,EAAA;AACD,EAAM,MAAA,KAAA,GAAQ,QAAQ,OAAO;AAAA,IAC3B,QAAQ,MAAU,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA;AAAA,IAClB;AAAA,GACE,CAAA,EAAA,CAAC,MAAQ,EAAA,SAAS,CAAC,CAAA;AACvB,EAAA,uBAAQ,GAAA,CAAA,oBAAA,CAAqB,QAArB,EAAA,EAA8B,OAAe,QAAS,EAAA,CAAA;AAChE;AACO,SAAS,gBAAuC,GAAA;AACrD,EAAA,OAAO,WAAW,oBAAoB,CAAA;AACxC;AAQgB,SAAA,aAAA,CAAc,QAAmC,IAG1C,EAAA;AA7CvB,EAAA,IAAA,EAAA,EAAA,EAAA;AA8CE,EAAA,MAAM,MAAM,gBAAiB,EAAA;AAC7B,EAAM,MAAA;AAAA,IACJ;AAAA,GACE,GAAA,GAAA;AACJ,EAAA,MAAM,aAAY,IAAM,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAA,SAAA,MAAc,MAAY,GAAA,IAAA,CAAK,YAAY,GAAI,CAAA,SAAA;AACvE,EAAA,MAAM,MAAM,MAAU,IAAA,MAAA;AACtB,EAAM,MAAA,KAAA,GAAQ,QAAQ,MAAU,IAAA,GAAA,IAAO,aAAa,MAAO,CAAA,KAAA,CAAM,GAAG,CAAC,CAAA;AACrE,EAAM,MAAA,GAAA,GAAM,CAAG,EA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AAA,GAAA;AACtC,EAAA,IAAA,CAAI,MAAQ,IAAA,IAAA,GAAA,MAAA,GAAA,MAAA,CAAA,GAAA,MAAQ,GAAK,EAAA,OAAO,MAAO,CAAA,GAAA;AACvC,EAAA,OAAA,CAAO,EAAO,GAAA,MAAA,CAAA,IAAA,CAAK,GAAK,EAAA,SAAS,MAA1B,IAA+B,GAAA,EAAA,GAAA,MAAA;AACxC;AAGO,MAAM,4BAA4B,CAAI,GAAA;AAOvB,eAAA,oBAAA,CAAqB,MAA8B,EAAA,MAAA,EAAgB,SAAqD,EAAA;AAC5I,EAAA,MAAM,MAAM,MAAS,GAAA,MAAM,MAAO,CAAA,OAAA,CAAQ,QAAQ,SAAW,EAAA;AAAA,IAC3D,UAAY,EAAA;AAAA,GACb,CAAI,GAAA,MAAA;AACL,EAAM,MAAA,OAAA,CAAQ,QAAQ,GAAG,CAAA;AAC3B"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import {useRef,useMemo,useState,useCallback,useEffect}from'react';import {AppState}from'react-native';import {isOutOfCredits,turnCost,turnCostLine}from'./web/credits/credits.js';import {CreditsReader}from'./web/credits/creditsReader.js';const METERING_DELAY_MS = 4e3;
|
|
2
|
+
function runnerOf(run) {
|
|
3
|
+
return async (connectorId, action, params) => {
|
|
4
|
+
try {
|
|
5
|
+
const data = await run(connectorId, action, params);
|
|
6
|
+
return {
|
|
7
|
+
successful: true,
|
|
8
|
+
data
|
|
9
|
+
};
|
|
10
|
+
} catch (err) {
|
|
11
|
+
return {
|
|
12
|
+
successful: false,
|
|
13
|
+
error: err instanceof Error ? err.message : String(err)
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function useWebBuilderCredits(run, busy, channelId) {
|
|
19
|
+
const runRef = useRef(run);
|
|
20
|
+
runRef.current = run;
|
|
21
|
+
const enabled = Boolean(run);
|
|
22
|
+
const reader = useMemo(() => enabled ? new CreditsReader({
|
|
23
|
+
run: (connectorId, action, params) => {
|
|
24
|
+
const {
|
|
25
|
+
current
|
|
26
|
+
} = runRef;
|
|
27
|
+
return current ? runnerOf(current)(connectorId, action, params) : Promise.resolve({
|
|
28
|
+
successful: false,
|
|
29
|
+
error: "no runner"
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}) : null, [enabled]);
|
|
33
|
+
const [balance, setBalance] = useState(null);
|
|
34
|
+
const [cardOpen, setCardOpen] = useState(false);
|
|
35
|
+
const [costLine, setCostLine] = useState(null);
|
|
36
|
+
const refresh = useCallback(async (opts) => {
|
|
37
|
+
if (!reader) return null;
|
|
38
|
+
const b = await reader.read(opts);
|
|
39
|
+
setBalance(b);
|
|
40
|
+
if (b && !isOutOfCredits(b)) setCardOpen(false);
|
|
41
|
+
return b;
|
|
42
|
+
}, [reader]);
|
|
43
|
+
useEffect(() => {
|
|
44
|
+
if (!reader) return void 0;
|
|
45
|
+
refresh().catch(() => void 0);
|
|
46
|
+
const sub = AppState.addEventListener("change", (state) => {
|
|
47
|
+
if (state === "active") refresh().catch(() => void 0);
|
|
48
|
+
});
|
|
49
|
+
return () => sub.remove();
|
|
50
|
+
}, [reader, refresh]);
|
|
51
|
+
const before = useRef(null);
|
|
52
|
+
const wasBusy = useRef(false);
|
|
53
|
+
const channelRef = useRef(channelId);
|
|
54
|
+
channelRef.current = channelId;
|
|
55
|
+
useEffect(() => {
|
|
56
|
+
const was = wasBusy.current;
|
|
57
|
+
wasBusy.current = busy;
|
|
58
|
+
if (!reader) return void 0;
|
|
59
|
+
if (!was && busy) {
|
|
60
|
+
before.current = reader.read({
|
|
61
|
+
fresh: true
|
|
62
|
+
});
|
|
63
|
+
setCostLine(null);
|
|
64
|
+
return void 0;
|
|
65
|
+
}
|
|
66
|
+
if (!was || busy || !before.current) return void 0;
|
|
67
|
+
const started = before.current;
|
|
68
|
+
before.current = null;
|
|
69
|
+
const turnChannel = channelRef.current;
|
|
70
|
+
const timer = setTimeout(() => {
|
|
71
|
+
if (!turnChannel || channelRef.current !== turnChannel) return;
|
|
72
|
+
Promise.all([started, refresh({
|
|
73
|
+
fresh: true
|
|
74
|
+
})]).then(([b, after]) => {
|
|
75
|
+
const cost = turnCost(b, after);
|
|
76
|
+
if (cost !== null && channelRef.current === turnChannel) {
|
|
77
|
+
setCostLine({
|
|
78
|
+
channelId: turnChannel,
|
|
79
|
+
text: turnCostLine(cost)
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}).catch(() => void 0);
|
|
83
|
+
}, METERING_DELAY_MS);
|
|
84
|
+
return () => clearTimeout(timer);
|
|
85
|
+
}, [busy, reader, refresh]);
|
|
86
|
+
useEffect(() => setCostLine(null), [channelId]);
|
|
87
|
+
const showCard = useCallback(() => setCardOpen(true), []);
|
|
88
|
+
const dismissCard = useCallback(() => setCardOpen(false), []);
|
|
89
|
+
const out = isOutOfCredits(balance);
|
|
90
|
+
return useMemo(() => reader ? {
|
|
91
|
+
balance,
|
|
92
|
+
refresh,
|
|
93
|
+
out,
|
|
94
|
+
cardOpen,
|
|
95
|
+
showCard,
|
|
96
|
+
dismissCard,
|
|
97
|
+
costLine
|
|
98
|
+
} : void 0, [reader, balance, refresh, out, cardOpen, showCard, dismissCard, costLine]);
|
|
99
|
+
}export{useWebBuilderCredits};//# sourceMappingURL=useWebBuilderCredits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useWebBuilderCredits.js","sources":["../../../src/features/webbuilder/useWebBuilderCredits.ts"],"sourcesContent":["/**\n * AI credits for Web Builder - the web `useCreditsService` + `useTurnCost` (W30): the balance from\n * the `billing` connector's `getUsage` on the person's agent, read on open, when the app comes back\n * to the front and after a turn; \"Out of credits\" holds build and edit turns back (the card says\n * why); and \"This change used ~$0.12.\" under a finished build, from the balance before and a fresh\n * read a few seconds after (usage is metered a moment late). A balance that can't be read never\n * blocks anything.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { AppState } from 'react-native';\nimport type { RunMediaAction } from '../canvas/videoEditor/mediaActions';\nimport { isOutOfCredits, turnCost, turnCostLine, type CreditsBalance } from './web/credits/credits';\nimport { CreditsReader, type ConnectorRunner } from './web/credits/creditsReader';\n\n/** How long after a turn ends the balance is read again (web). */\nconst METERING_DELAY_MS = 4000;\n\nexport interface WebBuilderCredits {\n /** Null: unknown (not read yet, failed, or no billing here) - nothing is shown. */\n balance: CreditsBalance | null;\n refresh: (opts?: { fresh?: boolean }) => Promise<CreditsBalance | null>;\n /** Build and edit turns are held back: nothing left and pay as you go off. */\n out: boolean;\n cardOpen: boolean;\n showCard: () => void;\n dismissCard: () => void;\n /** \"This change used ~$0.12.\" for the project whose turn it was. */\n costLine: { channelId: string; text: string } | null;\n}\n\n/** The agent's connector call as the reader's runner: a thrown call is a failed read. */\nfunction runnerOf(run: RunMediaAction): ConnectorRunner {\n return async (connectorId, action, params) => {\n try {\n const data = await run(connectorId as never, action, params);\n return { successful: true, data };\n } catch (err) {\n return { successful: false, error: err instanceof Error ? err.message : String(err) };\n }\n };\n}\n\nexport function useWebBuilderCredits(\n run: RunMediaAction | undefined,\n busy: boolean,\n channelId: string | null,\n): WebBuilderCredits | undefined {\n const runRef = useRef(run);\n runRef.current = run;\n const enabled = Boolean(run);\n const reader = useMemo(\n () =>\n enabled\n ? new CreditsReader({\n run: (connectorId, action, params) => {\n const { current } = runRef;\n return current\n ? runnerOf(current)(connectorId, action, params)\n : Promise.resolve({ successful: false, error: 'no runner' });\n },\n })\n : null,\n [enabled],\n );\n const [balance, setBalance] = useState<CreditsBalance | null>(null);\n const [cardOpen, setCardOpen] = useState(false);\n const [costLine, setCostLine] = useState<{ channelId: string; text: string } | null>(null);\n\n const refresh = useCallback(\n async (opts?: { fresh?: boolean }) => {\n if (!reader) return null;\n const b = await reader.read(opts);\n setBalance(b);\n // Credits came back: the card has done its job.\n if (b && !isOutOfCredits(b)) setCardOpen(false);\n return b;\n },\n [reader],\n );\n\n // On open and whenever the app comes back to the front (the web reads on window focus).\n useEffect(() => {\n if (!reader) return undefined;\n refresh().catch(() => undefined);\n const sub = AppState.addEventListener('change', (state) => {\n if (state === 'active') refresh().catch(() => undefined);\n });\n return () => sub.remove();\n }, [reader, refresh]);\n\n // A turn's cost: the balance when it starts, against a fresh read once it has been metered.\n const before = useRef<Promise<CreditsBalance | null> | null>(null);\n const wasBusy = useRef(false);\n const channelRef = useRef(channelId);\n channelRef.current = channelId;\n useEffect(() => {\n const was = wasBusy.current;\n wasBusy.current = busy;\n if (!reader) return undefined;\n if (!was && busy) {\n before.current = reader.read({ fresh: true });\n setCostLine(null);\n return undefined;\n }\n if (!was || busy || !before.current) return undefined;\n const started = before.current;\n before.current = null;\n const turnChannel = channelRef.current;\n const timer = setTimeout(() => {\n if (!turnChannel || channelRef.current !== turnChannel) return;\n Promise.all([started, refresh({ fresh: true })])\n .then(([b, after]) => {\n const cost = turnCost(b, after);\n if (cost !== null && channelRef.current === turnChannel) {\n setCostLine({ channelId: turnChannel, text: turnCostLine(cost) });\n }\n })\n .catch(() => undefined);\n }, METERING_DELAY_MS);\n return () => clearTimeout(timer);\n }, [busy, reader, refresh]);\n\n useEffect(() => setCostLine(null), [channelId]);\n\n const showCard = useCallback(() => setCardOpen(true), []);\n const dismissCard = useCallback(() => setCardOpen(false), []);\n const out = isOutOfCredits(balance);\n return useMemo(\n () => (reader ? { balance, refresh, out, cardOpen, showCard, dismissCard, costLine } : undefined),\n [reader, balance, refresh, out, cardOpen, showCard, dismissCard, costLine],\n );\n}\n"],"names":[],"mappings":"6OAeA,MAAM,iBAAoB,GAAA,GAAA;AAoB1B,SAAS,SAAS,GAAsC,EAAA;AACtD,EAAO,OAAA,OAAO,WAAa,EAAA,MAAA,EAAQ,MAAW,KAAA;AAC5C,IAAI,IAAA;AACF,MAAA,MAAM,IAAO,GAAA,MAAM,GAAI,CAAA,WAAA,EAAsB,QAAQ,MAAM,CAAA;AAC3D,MAAO,OAAA;AAAA,QACL,UAAY,EAAA,IAAA;AAAA,QACZ;AAAA,OACF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A;AAAA,IACA,OAAA;AAAA,IACA,GAAA;AAAA,IACA,QAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAW,EAAA,CAAC,MAAQ,EAAA,OAAA,EAAS,OAAS,EAAA,GAAA,EAAK,QAAU,EAAA,QAAA,EAAU,WAAa,EAAA,QAAQ,CAAC,CAAA;AAC3F"}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
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 BILLING_CONNECTOR_ID = "billing";
|
|
18
|
+
const BILLING_GET_USAGE_ACTION = "getUsage";
|
|
19
|
+
const BILLING_GET_USAGE_PARAMS = Object.freeze({
|
|
20
|
+
sections: ["llm"]
|
|
21
|
+
});
|
|
22
|
+
function isRec(v) {
|
|
23
|
+
return Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
24
|
+
}
|
|
25
|
+
function num(v) {
|
|
26
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
27
|
+
if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) return Number(v);
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
function amount(v) {
|
|
31
|
+
if (v === "unlimited" || v === -1) return "unlimited";
|
|
32
|
+
return num(v);
|
|
33
|
+
}
|
|
34
|
+
function parsePayg(label) {
|
|
35
|
+
const text = typeof label === "string" ? label.trim().toLowerCase() : "";
|
|
36
|
+
if (!text || text === "unavailable") return {
|
|
37
|
+
available: false,
|
|
38
|
+
enabled: false,
|
|
39
|
+
unlimited: false
|
|
40
|
+
};
|
|
41
|
+
if (!text.startsWith("on")) return {
|
|
42
|
+
available: true,
|
|
43
|
+
enabled: false,
|
|
44
|
+
unlimited: false
|
|
45
|
+
};
|
|
46
|
+
if (text.includes("unlimited")) return {
|
|
47
|
+
available: true,
|
|
48
|
+
enabled: true,
|
|
49
|
+
unlimited: true
|
|
50
|
+
};
|
|
51
|
+
const m = /\$\s*(-?\d+(?:\.\d+)?)/.exec(text);
|
|
52
|
+
const left = m ? Number(m[1]) : null;
|
|
53
|
+
return __spreadValues({
|
|
54
|
+
available: true,
|
|
55
|
+
enabled: true,
|
|
56
|
+
unlimited: false
|
|
57
|
+
}, left !== null && Number.isFinite(left) ? {
|
|
58
|
+
leftUsd: left
|
|
59
|
+
} : {});
|
|
60
|
+
}
|
|
61
|
+
function parsePeriod(raw) {
|
|
62
|
+
if (typeof raw !== "string" || !raw.trim()) return void 0;
|
|
63
|
+
const [a, b] = raw.split(/\s*(?:→|->)\s*/);
|
|
64
|
+
const clean = (s) => {
|
|
65
|
+
const t = (s || "").trim();
|
|
66
|
+
return /^\d{4}-\d{2}-\d{2}/.test(t) ? t.slice(0, 10) : void 0;
|
|
67
|
+
};
|
|
68
|
+
const start = clean(a);
|
|
69
|
+
const end = clean(b);
|
|
70
|
+
if (!start && !end) return void 0;
|
|
71
|
+
return __spreadValues(__spreadValues({}, start ? {
|
|
72
|
+
start
|
|
73
|
+
} : {}), end ? {
|
|
74
|
+
end
|
|
75
|
+
} : {});
|
|
76
|
+
}
|
|
77
|
+
function parseUsage(raw, depth = 0) {
|
|
78
|
+
var _a, _b, _c;
|
|
79
|
+
if (depth > 3) return null;
|
|
80
|
+
let value = raw;
|
|
81
|
+
if (typeof value === "string") {
|
|
82
|
+
try {
|
|
83
|
+
value = JSON.parse(value);
|
|
84
|
+
} catch (e) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (!isRec(value)) return null;
|
|
89
|
+
if (!isRec(value.llm)) {
|
|
90
|
+
if (value.data !== void 0) return parseUsage(value.data, depth + 1);
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
const llm = value.llm;
|
|
94
|
+
const remainingUsd = amount(llm.remainingUsd);
|
|
95
|
+
const includedUsd = amount(llm.includedUsd);
|
|
96
|
+
if (remainingUsd === null || includedUsd === null) return null;
|
|
97
|
+
const period = parsePeriod((_a = value.period) != null ? _a : llm.period);
|
|
98
|
+
return __spreadValues(__spreadValues({
|
|
99
|
+
includedUsd,
|
|
100
|
+
usedUsd: Math.max(0, (_b = num(llm.usedUsd)) != null ? _b : 0),
|
|
101
|
+
remainingUsd,
|
|
102
|
+
overageUsd: Math.max(0, (_c = num(llm.overageUsd)) != null ? _c : 0),
|
|
103
|
+
payg: parsePayg(llm.payg)
|
|
104
|
+
}, period ? {
|
|
105
|
+
period
|
|
106
|
+
} : {}), typeof llm.status === "string" && llm.status.trim() ? {
|
|
107
|
+
status: llm.status.trim().slice(0, 200)
|
|
108
|
+
} : {});
|
|
109
|
+
}
|
|
110
|
+
function formatUsd(value) {
|
|
111
|
+
if (!Number.isFinite(value)) return "$0";
|
|
112
|
+
if (value > 0 && value < 0.01) return "<$0.01";
|
|
113
|
+
const fixed = Math.abs(value) >= 100 ? value.toFixed(0) : value.toFixed(2);
|
|
114
|
+
return `$${fixed}`;
|
|
115
|
+
}
|
|
116
|
+
function isOutOfCredits(balance) {
|
|
117
|
+
if (!balance) return false;
|
|
118
|
+
if (balance.remainingUsd === "unlimited") return false;
|
|
119
|
+
if (balance.payg.enabled) return false;
|
|
120
|
+
return balance.remainingUsd <= 0;
|
|
121
|
+
}
|
|
122
|
+
function chipLabel(balance) {
|
|
123
|
+
if (balance.remainingUsd === "unlimited") return "Unlimited credits";
|
|
124
|
+
if (balance.remainingUsd > 0) return `${formatUsd(balance.remainingUsd)} left`;
|
|
125
|
+
if (balance.payg.enabled) return "Pay as you go";
|
|
126
|
+
return "Out of credits";
|
|
127
|
+
}
|
|
128
|
+
function chipTone(balance) {
|
|
129
|
+
if (isOutOfCredits(balance)) return "out";
|
|
130
|
+
if (typeof balance.remainingUsd === "number" && typeof balance.includedUsd === "number" && balance.includedUsd > 0 && !balance.payg.enabled && balance.remainingUsd / balance.includedUsd < 0.1) {
|
|
131
|
+
return "low";
|
|
132
|
+
}
|
|
133
|
+
return "normal";
|
|
134
|
+
}
|
|
135
|
+
function periodLabel(period) {
|
|
136
|
+
if (!period) return null;
|
|
137
|
+
const fmt = (iso) => {
|
|
138
|
+
if (!iso) return "?";
|
|
139
|
+
const d = /* @__PURE__ */ new Date(`${iso}T00:00:00Z`);
|
|
140
|
+
if (Number.isNaN(d.getTime())) return iso;
|
|
141
|
+
return d.toLocaleDateString("en-US", {
|
|
142
|
+
month: "short",
|
|
143
|
+
day: "numeric",
|
|
144
|
+
timeZone: "UTC"
|
|
145
|
+
});
|
|
146
|
+
};
|
|
147
|
+
return `${fmt(period.start)} \u2013 ${fmt(period.end)}`;
|
|
148
|
+
}
|
|
149
|
+
function balanceDetails(balance) {
|
|
150
|
+
const rows = [];
|
|
151
|
+
rows.push({
|
|
152
|
+
label: "Included",
|
|
153
|
+
value: balance.includedUsd === "unlimited" ? "Unlimited" : formatUsd(balance.includedUsd)
|
|
154
|
+
});
|
|
155
|
+
rows.push({
|
|
156
|
+
label: "Used",
|
|
157
|
+
value: formatUsd(balance.usedUsd)
|
|
158
|
+
});
|
|
159
|
+
rows.push({
|
|
160
|
+
label: "Remaining",
|
|
161
|
+
value: balance.remainingUsd === "unlimited" ? "Unlimited" : formatUsd(Math.max(0, balance.remainingUsd))
|
|
162
|
+
});
|
|
163
|
+
if (balance.overageUsd > 0) rows.push({
|
|
164
|
+
label: "Pay as you go so far",
|
|
165
|
+
value: formatUsd(balance.overageUsd)
|
|
166
|
+
});
|
|
167
|
+
const period = periodLabel(balance.period);
|
|
168
|
+
if (period) rows.push({
|
|
169
|
+
label: "Period",
|
|
170
|
+
value: period
|
|
171
|
+
});
|
|
172
|
+
const limit = spendingLimitLine(balance);
|
|
173
|
+
if (limit) rows.push({
|
|
174
|
+
label: "Spending limit",
|
|
175
|
+
value: limit
|
|
176
|
+
});
|
|
177
|
+
return rows;
|
|
178
|
+
}
|
|
179
|
+
function spendingLimitLine(balance) {
|
|
180
|
+
const p = balance.payg;
|
|
181
|
+
if (!p.available) return null;
|
|
182
|
+
if (!p.enabled) return "Pay as you go is off";
|
|
183
|
+
if (p.unlimited) return "No limit";
|
|
184
|
+
if (typeof p.leftUsd === "number") return `${formatUsd(Math.max(0, p.leftUsd))} left this month`;
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
function turnCost(before, after) {
|
|
188
|
+
if (!before || !after) return null;
|
|
189
|
+
const spent = after.usedUsd + after.overageUsd - (before.usedUsd + before.overageUsd);
|
|
190
|
+
if (!Number.isFinite(spent) || spent <= 0) return null;
|
|
191
|
+
if (spent > 1e3) return null;
|
|
192
|
+
return spent;
|
|
193
|
+
}
|
|
194
|
+
function turnCostLine(cost) {
|
|
195
|
+
return `This change used ~${formatUsd(cost)}.`;
|
|
196
|
+
}
|
|
197
|
+
const OUT_OF_CREDITS_TITLE = "You're out of AI credits";
|
|
198
|
+
function outOfCreditsText(billingLink) {
|
|
199
|
+
return billingLink ? "Your builds and chat are kept. Change your plan or turn on pay as you go, then try again." : "Your builds and chat are kept. To continue, change your plan or turn on pay as you go under Billing in your Yantra account settings, then try again.";
|
|
200
|
+
}
|
|
201
|
+
function isMissingActionError(message) {
|
|
202
|
+
return /unknown (?:billing )?action|action .* not found|no such action|connector .*not (?:found|installed)|unknown connector/i.test(String(message || ""));
|
|
203
|
+
}export{BILLING_CONNECTOR_ID,BILLING_GET_USAGE_ACTION,BILLING_GET_USAGE_PARAMS,OUT_OF_CREDITS_TITLE,balanceDetails,chipLabel,chipTone,formatUsd,isMissingActionError,isOutOfCredits,outOfCreditsText,parsePayg,parsePeriod,parseUsage,periodLabel,spendingLimitLine,turnCost,turnCostLine};//# sourceMappingURL=credits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credits.js","sources":["../../../../../src/features/webbuilder/web/credits/credits.ts"],"sourcesContent":["/**\n * W30 credits (Phase 6 spec §1): read the AI-credit balance from the `billing`\n * connector and turn it into the toolbar chip, the details popover, the\n * \"Out of credits\" pause and the per-turn cost line. Pure: tested with node:test.\n *\n * Connector facts (local install of `billing` v1.0.4, `~/.cdecli/connectors/billing/package.json`):\n * - action id `getUsage` (title \"Get usage\", command `billing.usage.get`);\n * - input `{ sections?: ('llm' | 'metered' | 'addOns')[], orgName?: string }`;\n * - output `{ llm: { status, includedUsd, usedUsd, remainingUsd, overageUsd, payg },\n * period?: 'YYYY-MM-DD → YYYY-MM-DD', summary }`, where `includedUsd` is -1 for\n * an unlimited allowance, `remainingUsd` is a number or `'unlimited'`, and `payg`\n * is `'unavailable' | 'off' | 'on · unlimited' | 'on · $X/mo left'`.\n */\n\nexport const BILLING_CONNECTOR_ID = 'billing';\nexport const BILLING_GET_USAGE_ACTION = 'getUsage';\n/** Only the LLM slice: metered features and add-ons cost extra GraphQL calls we don't show. */\nexport const BILLING_GET_USAGE_PARAMS: Readonly<Record<string, unknown>> = Object.freeze({ sections: ['llm'] });\n\nexport type UsdAmount = number | 'unlimited';\n\nexport interface PaygState {\n /** The plan offers pay as you go at all. */\n available: boolean;\n /** Pay as you go is switched on: turns keep running past the included credits. */\n enabled: boolean;\n /** On, with no monthly cap. */\n unlimited: boolean;\n /** On, with a cap: what is left of it this month. */\n leftUsd?: number;\n}\n\nexport interface CreditsBalance {\n includedUsd: UsdAmount;\n usedUsd: number;\n remainingUsd: UsdAmount;\n overageUsd: number;\n payg: PaygState;\n /** The billing period, when the connector sent one. */\n period?: { start?: string; end?: string };\n /** The connector's own one-line status (\"ACTIVE · 40% of allowance used\"). */\n status?: string;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction num(v: unknown): number | null {\n if (typeof v === 'number' && Number.isFinite(v)) return v;\n if (typeof v === 'string' && v.trim() && Number.isFinite(Number(v))) return Number(v);\n return null;\n}\n\nfunction amount(v: unknown): UsdAmount | null {\n if (v === 'unlimited' || v === -1) return 'unlimited';\n return num(v);\n}\n\n/** `payg` label from the connector -> state. Unknown text counts as off. */\nexport function parsePayg(label: unknown): PaygState {\n const text = typeof label === 'string' ? label.trim().toLowerCase() : '';\n if (!text || text === 'unavailable') return { available: false, enabled: false, unlimited: false };\n if (!text.startsWith('on')) return { available: true, enabled: false, unlimited: false };\n if (text.includes('unlimited')) return { available: true, enabled: true, unlimited: true };\n const m = /\\$\\s*(-?\\d+(?:\\.\\d+)?)/.exec(text);\n const left = m ? Number(m[1]) : null;\n return {\n available: true,\n enabled: true,\n unlimited: false,\n ...(left !== null && Number.isFinite(left) ? { leftUsd: left } : {}),\n };\n}\n\n/** `'2026-10-01 → 2026-10-31'` -> `{ start, end }` ('?' parts dropped). */\nexport function parsePeriod(raw: unknown): { start?: string; end?: string } | undefined {\n if (typeof raw !== 'string' || !raw.trim()) return undefined;\n const [a, b] = raw.split(/\\s*(?:→|->)\\s*/);\n const clean = (s?: string) => {\n const t = (s || '').trim();\n return /^\\d{4}-\\d{2}-\\d{2}/.test(t) ? t.slice(0, 10) : undefined;\n };\n const start = clean(a);\n const end = clean(b);\n if (!start && !end) return undefined;\n return { ...(start ? { start } : {}), ...(end ? { end } : {}) };\n}\n\n/**\n * The connector result (`{ llm, period }`, possibly wrapped in `{ data }` or\n * sent as a JSON string) -> a balance. Null when there is no usable LLM slice:\n * the chip then stays hidden.\n */\nexport function parseUsage(raw: unknown, depth = 0): CreditsBalance | null {\n if (depth > 3) return null;\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return null;\n }\n }\n if (!isRec(value)) return null;\n if (!isRec(value.llm)) {\n if (value.data !== undefined) return parseUsage(value.data, depth + 1);\n return null;\n }\n const llm = value.llm;\n const remainingUsd = amount(llm.remainingUsd);\n const includedUsd = amount(llm.includedUsd);\n if (remainingUsd === null || includedUsd === null) return null;\n const period = parsePeriod(value.period ?? llm.period);\n return {\n includedUsd,\n usedUsd: Math.max(0, num(llm.usedUsd) ?? 0),\n remainingUsd,\n overageUsd: Math.max(0, num(llm.overageUsd) ?? 0),\n payg: parsePayg(llm.payg),\n ...(period ? { period } : {}),\n ...(typeof llm.status === 'string' && llm.status.trim() ? { status: llm.status.trim().slice(0, 200) } : {}),\n };\n}\n\n/** \"$12.50\", \"$0.12\", \"<$0.01\". */\nexport function formatUsd(value: number): string {\n if (!Number.isFinite(value)) return '$0';\n if (value > 0 && value < 0.01) return '<$0.01';\n const fixed = Math.abs(value) >= 100 ? value.toFixed(0) : value.toFixed(2);\n return `$${fixed}`;\n}\n\n/** Spec §1: don't send a build or edit turn when this is true. */\nexport function isOutOfCredits(balance: CreditsBalance | null | undefined): boolean {\n if (!balance) return false;\n if (balance.remainingUsd === 'unlimited') return false;\n if (balance.payg.enabled) return false;\n return balance.remainingUsd <= 0;\n}\n\n/** The toolbar chip text. */\nexport function chipLabel(balance: CreditsBalance): string {\n if (balance.remainingUsd === 'unlimited') return 'Unlimited credits';\n if (balance.remainingUsd > 0) return `${formatUsd(balance.remainingUsd)} left`;\n if (balance.payg.enabled) return 'Pay as you go';\n return 'Out of credits';\n}\n\nexport type ChipTone = 'normal' | 'low' | 'out';\n\n/** Amber under 10% of the included credits, red when turns are paused. */\nexport function chipTone(balance: CreditsBalance): ChipTone {\n if (isOutOfCredits(balance)) return 'out';\n if (\n typeof balance.remainingUsd === 'number' &&\n typeof balance.includedUsd === 'number' &&\n balance.includedUsd > 0 &&\n !balance.payg.enabled &&\n balance.remainingUsd / balance.includedUsd < 0.1\n ) {\n return 'low';\n }\n return 'normal';\n}\n\n/** \"Oct 1 – Oct 31\" (UTC dates, so the label never shifts a day). */\nexport function periodLabel(period: CreditsBalance['period']): string | null {\n if (!period) return null;\n const fmt = (iso?: string) => {\n if (!iso) return '?';\n const d = new Date(`${iso}T00:00:00Z`);\n if (Number.isNaN(d.getTime())) return iso;\n return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });\n };\n return `${fmt(period.start)} – ${fmt(period.end)}`;\n}\n\n/** The popover rows. */\nexport function balanceDetails(balance: CreditsBalance): Array<{ label: string; value: string }> {\n const rows: Array<{ label: string; value: string }> = [];\n rows.push({\n label: 'Included',\n value: balance.includedUsd === 'unlimited' ? 'Unlimited' : formatUsd(balance.includedUsd),\n });\n rows.push({ label: 'Used', value: formatUsd(balance.usedUsd) });\n rows.push({\n label: 'Remaining',\n value: balance.remainingUsd === 'unlimited' ? 'Unlimited' : formatUsd(Math.max(0, balance.remainingUsd)),\n });\n if (balance.overageUsd > 0) rows.push({ label: 'Pay as you go so far', value: formatUsd(balance.overageUsd) });\n const period = periodLabel(balance.period);\n if (period) rows.push({ label: 'Period', value: period });\n const limit = spendingLimitLine(balance);\n if (limit) rows.push({ label: 'Spending limit', value: limit });\n return rows;\n}\n\n/** Spec §1 \"Admins\": a read-out of the pay-as-you-go cap, when there is one. No editing here. */\nexport function spendingLimitLine(balance: CreditsBalance): string | null {\n const p = balance.payg;\n if (!p.available) return null;\n if (!p.enabled) return 'Pay as you go is off';\n if (p.unlimited) return 'No limit';\n if (typeof p.leftUsd === 'number') return `${formatUsd(Math.max(0, p.leftUsd))} left this month`;\n return null;\n}\n\n/**\n * Spec §1 \"Cost per turn\": what a turn spent, from balances read before and\n * after it. Null when either read is missing or the numbers didn't move\n * (usage can lag behind the turn; then we show nothing rather than \"$0\").\n */\nexport function turnCost(\n before: CreditsBalance | null | undefined,\n after: CreditsBalance | null | undefined,\n): number | null {\n if (!before || !after) return null;\n const spent = after.usedUsd + after.overageUsd - (before.usedUsd + before.overageUsd);\n if (!Number.isFinite(spent) || spent <= 0) return null;\n // A new billing period resets usage; a jump this large is not one turn.\n if (spent > 1000) return null;\n return spent;\n}\n\n/** The line added under a finished build. */\nexport function turnCostLine(cost: number): string {\n return `This change used ~${formatUsd(cost)}.`;\n}\n\nexport const OUT_OF_CREDITS_TITLE = \"You're out of AI credits\";\n\n/** The card text; no billing link means we tell the user where to go instead. */\nexport function outOfCreditsText(billingLink: string | boolean | null): string {\n return billingLink\n ? 'Your builds and chat are kept. Change your plan or turn on pay as you go, then try again.'\n : 'Your builds and chat are kept. To continue, change your plan or turn on pay as you go under Billing in your Yantra account settings, then try again.';\n}\n\n/** Only an absolute https URL (or http on localhost) is used as the plan/top-up link. */\nexport function safeBillingUrl(raw: unknown): string | null {\n if (typeof raw !== 'string' || !raw.trim()) return null;\n try {\n const u = new URL(raw.trim());\n if (u.protocol === 'https:') return u.toString();\n if (u.protocol === 'http:' && /^(localhost|127\\.0\\.0\\.1)$/.test(u.hostname)) return u.toString();\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * The reply to an action the installed agent doesn't know: hide the chip\n * instead of retrying on every refresh.\n */\nexport function isMissingActionError(message: string | null | undefined): boolean {\n return /unknown (?:billing )?action|action .* not found|no such action|connector .*not (?:found|installed)|unknown connector/i.test(\n String(message || ''),\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAcO,MAAM,oBAAuB,GAAA;AAC7B,MAAM,wBAA2B,GAAA;AAE3B,MAAA,wBAAA,GAA8D,OAAO,MAAO,CAAA;AAAA,EACvF,QAAA,EAAU,CAAC,KAAK;AAClB,CAAC;AA2BD,SAAS,MAAM,CAAsB,EAAA;AACnC,EAAO,OAAA,OAAA,CAAQ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AAA,IAAI,OAAO,CAAA,CAAE,OAAY,KAAA,QAAA,EAAiB,OAAA,CAAA,EAAG,SAAU,CAAA,IAAA,CAAK,GAAI,CAAA,CAAA,EAAG,CAAE,CAAA,OAAO,CAAC,CAAC,CAAA,gBAAA,CAAA;AAC9E,EAAO,OAAA,IAAA;AACT;AAOgB,SAAA,QAAA,CAAS,QAA2C,KAAyD,EAAA;AAC3H,EAAA,IAAI,CAAC,MAAA,IAAU,CAAC,KAAA,EAAc,OAAA,IAAA;AAC9B,EAAA,MAAM,QAAQ,KAAM,CAAA,OAAA,GAAU,MAAM,UAAc,IAAA,MAAA,CAAO,UAAU,MAAO,CAAA,UAAA,CAAA;AAC1E,EAAA,IAAI,CAAC,MAAO,CAAA,QAAA,CAAS,KAAK,CAAK,IAAA,KAAA,IAAS,GAAU,OAAA,IAAA;AAElD,EAAI,IAAA,KAAA,GAAQ,KAAa,OAAA,IAAA;AACzB,EAAO,OAAA,KAAA;AACT;AAGO,SAAS,aAAa,IAAsB,EAAA;AACjD,EAAO,OAAA,CAAA,kBAAA,EAAqB,SAAU,CAAA,IAAI,CAAC,CAAA,CAAA,CAAA;AAC7C;AACO,MAAM,oBAAuB,GAAA;AAG7B,SAAS,iBAAiB,WAA8C,EAAA;AAC7E,EAAA,OAAO,cAAc,2FAA8F,GAAA,sJAAA;AACrH;AAmBO,SAAS,qBAAqB,OAA6C,EAAA;AAChF,EAAA,OAAO,uHAAwH,CAAA,IAAA,CAAK,MAAO,CAAA,OAAA,IAAW,EAAE,CAAC,CAAA;AAC3J"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import {BILLING_CONNECTOR_ID,BILLING_GET_USAGE_ACTION,BILLING_GET_USAGE_PARAMS,parseUsage,isMissingActionError}from'./credits.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
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
18
|
+
class CreditsReader {
|
|
19
|
+
constructor(opts) {
|
|
20
|
+
__publicField(this, "run");
|
|
21
|
+
__publicField(this, "ttlMs");
|
|
22
|
+
__publicField(this, "now");
|
|
23
|
+
__publicField(this, "cached", null);
|
|
24
|
+
__publicField(this, "inflight", null);
|
|
25
|
+
/** The agent doesn't have the action: stop asking. */
|
|
26
|
+
__publicField(this, "unsupported", false);
|
|
27
|
+
var _a, _b;
|
|
28
|
+
this.run = opts.run;
|
|
29
|
+
this.ttlMs = (_a = opts.ttlMs) != null ? _a : 3e4;
|
|
30
|
+
this.now = (_b = opts.now) != null ? _b : (() => Date.now());
|
|
31
|
+
}
|
|
32
|
+
get isUnsupported() {
|
|
33
|
+
return this.unsupported;
|
|
34
|
+
}
|
|
35
|
+
/** The last value read (null before the first read or after a failure). */
|
|
36
|
+
get last() {
|
|
37
|
+
var _a, _b;
|
|
38
|
+
return (_b = (_a = this.cached) == null ? void 0 : _a.value) != null ? _b : null;
|
|
39
|
+
}
|
|
40
|
+
async read(opts) {
|
|
41
|
+
if (this.unsupported) return null;
|
|
42
|
+
if (!(opts == null ? void 0 : opts.fresh) && this.cached && this.now() - this.cached.at < this.ttlMs) return this.cached.value;
|
|
43
|
+
if (this.inflight) return this.inflight;
|
|
44
|
+
this.inflight = this.fetchOnce().finally(() => {
|
|
45
|
+
this.inflight = null;
|
|
46
|
+
});
|
|
47
|
+
return this.inflight;
|
|
48
|
+
}
|
|
49
|
+
async fetchOnce() {
|
|
50
|
+
let value = null;
|
|
51
|
+
try {
|
|
52
|
+
const r = await this.run(BILLING_CONNECTOR_ID, BILLING_GET_USAGE_ACTION, __spreadValues({}, BILLING_GET_USAGE_PARAMS));
|
|
53
|
+
if (r.successful) value = parseUsage(r.data);
|
|
54
|
+
else if (isMissingActionError(r.error)) this.unsupported = true;
|
|
55
|
+
} catch (e) {
|
|
56
|
+
if (isMissingActionError(e instanceof Error ? e.message : String(e))) this.unsupported = true;
|
|
57
|
+
value = null;
|
|
58
|
+
}
|
|
59
|
+
this.cached = {
|
|
60
|
+
at: this.now(),
|
|
61
|
+
value
|
|
62
|
+
};
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
}export{CreditsReader};//# sourceMappingURL=creditsReader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"creditsReader.js","sources":["../../../../../src/features/webbuilder/web/credits/creditsReader.ts"],"sourcesContent":["/**\n * W30: reads the balance through an injected connector runner (the standalone\n * host runs `billing/getUsage` on the cdecli agent with the user's JWT) and\n * caches it briefly. Every failure resolves to null: a balance we can't read\n * never blocks anything (spec §1). Pure: tested with node:test.\n */\n\nimport {\n BILLING_CONNECTOR_ID,\n BILLING_GET_USAGE_ACTION,\n BILLING_GET_USAGE_PARAMS,\n isMissingActionError,\n parseUsage,\n type CreditsBalance,\n} from './credits';\n\nexport interface ConnectorRunResult {\n successful: boolean;\n data?: unknown;\n error?: string;\n}\n\nexport type ConnectorRunner = (\n connectorId: string,\n action: string,\n params: Record<string, unknown>,\n) => Promise<ConnectorRunResult>;\n\nexport interface CreditsReaderOptions {\n run: ConnectorRunner;\n /** Reuse a read for this long (default 30 s). */\n ttlMs?: number;\n now?: () => number;\n}\n\nexport class CreditsReader {\n private readonly run: ConnectorRunner;\n private readonly ttlMs: number;\n private readonly now: () => number;\n private cached: { at: number; value: CreditsBalance | null } | null = null;\n private inflight: Promise<CreditsBalance | null> | null = null;\n /** The agent doesn't have the action: stop asking. */\n private unsupported = false;\n\n constructor(opts: CreditsReaderOptions) {\n this.run = opts.run;\n this.ttlMs = opts.ttlMs ?? 30_000;\n this.now = opts.now ?? (() => Date.now());\n }\n\n get isUnsupported(): boolean {\n return this.unsupported;\n }\n\n /** The last value read (null before the first read or after a failure). */\n get last(): CreditsBalance | null {\n return this.cached?.value ?? null;\n }\n\n async read(opts?: { fresh?: boolean }): Promise<CreditsBalance | null> {\n if (this.unsupported) return null;\n if (!opts?.fresh && this.cached && this.now() - this.cached.at < this.ttlMs) return this.cached.value;\n if (this.inflight) return this.inflight;\n this.inflight = this.fetchOnce().finally(() => {\n this.inflight = null;\n });\n return this.inflight;\n }\n\n private async fetchOnce(): Promise<CreditsBalance | null> {\n let value: CreditsBalance | null = null;\n try {\n const r = await this.run(BILLING_CONNECTOR_ID, BILLING_GET_USAGE_ACTION, { ...BILLING_GET_USAGE_PARAMS });\n if (r.successful) value = parseUsage(r.data);\n else if (isMissingActionError(r.error)) this.unsupported = true;\n } catch (e) {\n if (isMissingActionError(e instanceof Error ? e.message : String(e))) this.unsupported = true;\n value = null;\n }\n this.cached = { at: this.now(), value };\n return value;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAoBO,MAAM,aAAc,CAAA;AAAA,EAWzB,YAAY,IAA4B,EAAA;AAVxC,IAAiB,aAAA,CAAA,IAAA,EAAA,KAAA,CAAA;AACjB,IAAiB,aAAA,CAAA,IAAA,EAAA,OAAA,CAAA;AACjB,IAAiB,aAAA,CAAA,IAAA,EAAA,KAAA,CAAA;AACjB,IAAA,aAAA,CAAA,IAAA,EAAQ,QAGG,EAAA,IAAA,CAAA;AACX,IAAA,aAAA,CAAA,IAAA,EA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IAAA;AAAA,KACjB,CAAA;AACD,IAAA,OAAO,IAAK,CAAA,QAAA;AAAA;AACd,EACA,MAAc,SAA4C,GAAA;AACxD,IAAA,IAAI,KAA+B,GAAA,IAAA;AACnC,IAAI,IAAA;AACF,MAAA,MAAM,IAAI,MAAM,IAAA,CAAK,IAAI,oBAAsB,EAAA,wBAAA,EAA0B,mBACpE,wBACJ,CAAA,CAAA;AACD,MAAA,IAAI,CAAE,CAAA,UAAA,EAAoB,KAAA,GAAA,UAAA,CAAW,EAAE,IAAI,CAAA;AAAA,WAAA,IAAW,oBAAqB,CAAA,CAAA,CAAE,KAAK,CAAA,OAAQ,WAAc,GAAA,IAAA;AAAA,aACjG,CAAG,EAAA;AACV,MAAI,IAAA,oBAAA,CAAqB,CAAa,YAAA,KAAA,GAAQ,CAAE,CAAA,OAAA,GAAU,OAAO,CAAC,CAAC,CAAG,EAAA,IAAA,CAAK,WAAc,GAAA,IAAA;AACzF,MAAQ,KAAA,GAAA,IAAA;AAAA;AAEV,IAAA,IAAA,CAAK,MAAS,GAAA;AAAA,MACZ,EAAA,EAAI,KAAK,GAAI,EAAA;AAAA,MACb;AAAA,KACF;AACA,IAAO,OAAA,KAAA;AAAA;AAEX"}
|
|
@@ -41,9 +41,9 @@ const CLOUD_TAB_LABELS = {
|
|
|
41
41
|
};
|
|
42
42
|
function cloudTabs(role, opts = {}) {
|
|
43
43
|
const tabs = [];
|
|
44
|
-
if (roleCan()) tabs.push("data");
|
|
45
|
-
if (!opts.shared && roleCan()) tabs.push("sql");
|
|
46
|
-
if (!opts.shared && roleCan()) tabs.push("health", "users", "storage");
|
|
44
|
+
if (roleCan(role, "database")) tabs.push("data");
|
|
45
|
+
if (!opts.shared && roleCan(role, "databaseSql")) tabs.push("sql");
|
|
46
|
+
if (!opts.shared && roleCan(role, "database")) tabs.push("health", "users", "storage");
|
|
47
47
|
tabs.push("settings");
|
|
48
48
|
return tabs;
|
|
49
49
|
}
|