Skip to content

Commit

Permalink
fix(sponsor): fix sponsor syncing
Browse files Browse the repository at this point in the history
  • Loading branch information
johnlindquist committed Dec 20, 2024
1 parent 79b140c commit f805b6c
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 77 deletions.
8 changes: 3 additions & 5 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1025,11 +1025,8 @@ const checkKit = async () => {
});

if (!isKenvInstalled) {
log.info('Cloning sponsors...');
optionalSetupScript(kitPath('setup', 'clone-sponsors.js')).then(() => {
log.info('Cloning examples...');
optionalSetupScript(kitPath('setup', 'clone-examples.js'));
});
log.info('Cloning examples...');
optionalSetupScript(kitPath('setup', 'clone-examples.js'));
}

// await installLoaderTools();
Expand Down Expand Up @@ -1168,6 +1165,7 @@ app
});

app?.on('will-quit', (e) => {
destroyPtyPool();
log.info('🚪 will-quit');
});

Expand Down
21 changes: 18 additions & 3 deletions src/main/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1088,13 +1088,21 @@ export const cacheMainMenu = ({

// Initialize static properties for cacheMainScripts
// Initialize static properties for cacheMainScripts
export type CacheMainScriptsMessage = {
channel: Channel;
value: any;
id: string;
state?: {
isSponsor: boolean;
};
};
interface CacheMainScripts {
(reason: string, params?: { channel: Channel; value: any }): Promise<boolean>;
pendingResolvers?: Array<{
resolve: (value: boolean) => void;
reject: (reason?: any) => void;
}>;
postMessage?: (message: any) => void;
postMessage?: (message: CacheMainScriptsMessage) => void;
}

// Helper function to resolve all pending promises at once
Expand Down Expand Up @@ -1268,7 +1276,7 @@ export const cacheMainScripts: CacheMainScripts = async (
// Initialize postMessage if not already defined
if (!cacheMainScripts.postMessage) {
cacheMainScripts.postMessage = debounce(
(message) => {
(message: CacheMainScriptsMessage) => {
const body = message ? { ...message, id: uuid } : { id: uuid };
log.info(`🏆 ${uuid}: Posting message to worker`);
if (workers.cacheScripts) {
Expand All @@ -1287,7 +1295,14 @@ export const cacheMainScripts: CacheMainScripts = async (

// Send the message to the worker to start the caching process
log.info('Sending stamp to worker', stamp);
cacheMainScripts.postMessage({ channel, value, id: uuid });
if (cacheMainScripts.postMessage) {
const state = {
isSponsor: kitState.isSponsor,
};
cacheMainScripts.postMessage({ channel, value, id: uuid, state });
} else {
log.error('cacheMainScripts.postMessage is not defined');
}
} catch (error) {
// If something goes wrong at any point, reject all pending resolvers
log.warn('Failed to cache main scripts at startup', error);
Expand Down
9 changes: 5 additions & 4 deletions src/main/kit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { TrackEvent, trackEvent } from './track';
import { createLogger } from '../shared/log-utils';
import { createForkOptions } from './fork.options';
import { mainLogPath } from './logs';
import { refreshScripts } from '@johnlindquist/kit/core/db';

const log = createLogger('kit.ts');

Expand Down Expand Up @@ -364,12 +365,12 @@ export const runScript = (...args: string[]) => {
subscribeKey(kitState, 'isSponsor', (isSponsor) => {
log.info('🎨 Sponsor changed:', isSponsor);

// runScript(
// kitPath('config', 'toggle-sponsor.js'),
// isSponsor ? 'true' : 'false'
// );
// Sets the env var for when scripts parse to exclude main sponsor script
runScript(kitPath('config', 'toggle-sponsor.js'), isSponsor ? 'true' : 'false');

kitStore.set('sponsor', isSponsor);

refreshScripts();
});

emitter.on(KitEvent.OpenLog, async (scriptPath) => {
Expand Down
5 changes: 5 additions & 0 deletions src/main/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,12 @@ const subEmoji = subscribeKey(
),
);

let _isSponsor = false;
const subIsSponsor = subscribeKey(kitState, 'isSponsor', (isSponsor) => {
if (_isSponsor === isSponsor) {
return;
}
_isSponsor = isSponsor;
log.info('🎨 Sponsor changed:', isSponsor);
setKitStateAtom({ isSponsor });
});
Expand Down
123 changes: 77 additions & 46 deletions src/main/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,14 @@ import { type WatchEvent, startWatching } from './chokidar';
import { isInDirectory } from './helpers';
import { runScript } from './kit';
import { getFileImports } from './npm';
import { clearIdleProcesses, ensureIdleProcess, processes, sendToAllActiveChildren, spawnShebang, updateTheme } from './process';
import {
clearIdleProcesses,
ensureIdleProcess,
processes,
sendToAllActiveChildren,
spawnShebang,
updateTheme,
} from './process';
import { clearPromptCache, clearPromptCacheFor, setKitStateAtom } from './prompt';
import { setCSSVariable } from './theme';
import { addSnippet, addTextSnippet, removeSnippet } from './tick';
Expand Down Expand Up @@ -355,7 +362,7 @@ export const onScriptChanged = async (event: WatchEvent, script: Script, rebuilt
firstBatch: firstBatch,
},
);
return
return;
}

log.info('Shortcut script changed', script.filePath);
Expand All @@ -375,7 +382,7 @@ export const onScriptChanged = async (event: WatchEvent, script: Script, rebuilt
}

if (event === 'add' || event === 'unlink') {
debounceCacheMainScripts("Script added or unlinked");
debounceCacheMainScripts('Script added or unlinked');
}
};

Expand Down Expand Up @@ -403,33 +410,27 @@ export const checkUserDb = debounce(async (eventName: string) => {
// Only run set-login if login value changed
const prevLogin = kitState.user?.login;
const newLogin = currentUser?.login;
log.info(`Login status`, {
prevLogin: prevLogin || 'undefined',
newLogin: newLogin || 'undefined',
});
if (prevLogin !== newLogin) {
log.info('🔍 Running set-login', newLogin || Env.REMOVE);
await runScript(kitPath('config', 'set-login'), newLogin || Env.REMOVE);
}

// Only check sponsor status if login changed
if (prevLogin !== newLogin) {
if (newLogin) {
const isSponsor = await sponsorCheck('Login', false);
kitState.isSponsor = isSponsor;
} else {
kitState.isSponsor = false;
}
}

const user = snapshot(kitState.user);
log.info('Send user.json to prompt', {
login: user?.login,
name: user?.name,
});

sendToAllPrompts(AppChannel.USER_CHANGED, user);
},
1000,
{
leading: true,
});

const isSponsor = await sponsorCheck('Login', false);
log.info(`🔍 Sponsor check result: ${isSponsor ? '✅' : '❌'}`);
kitState.isSponsor = isSponsor;
}, 500);

const triggerRunText = debounce(
async (eventName: WatchEvent) => {
Expand Down Expand Up @@ -492,7 +493,7 @@ const handleScriptletsChanged = debounce(async (eventName: WatchEvent, filePath:
const beforeScriptlets = structuredClone(kitState.scriptlets);
scriptLog.info('🎬 Starting cacheMainScripts...');
try {
await cacheMainScripts("File change detected");
await cacheMainScripts('File change detected');
} catch (error) {
log.error(error);
}
Expand Down Expand Up @@ -524,12 +525,34 @@ const handleScriptletsChanged = debounce(async (eventName: WatchEvent, filePath:
export const parseEnvFile = debounce(async () => {
const envData = loadKenvEnvironment();

if(envData?.KIT_API_KEY) {
if (envData?.KIT_LOGIN) {
log.info(`Detected KIT_LOGIN in .env. Setting kitState.kenvEnv.KIT_LOGIN`);
kitState.kenvEnv.KIT_LOGIN = envData?.KIT_LOGIN;
} else if (kitState.kenvEnv.KIT_LOGIN) {
log.info(`Removing KIT_LOGIN from kitState.kenvEnv`);
delete kitState.kenvEnv.KIT_LOGIN;
kitState.isSponsor = false;
}

if (envData?.GITHUB_SCRIPTKIT_TOKEN) {
log.info(`Detected GITHUB_SCRIPTKIT_TOKEN in .env. Setting kitState.kenvEnv.GITHUB_SCRIPTKIT_TOKEN`);
kitState.kenvEnv.GITHUB_SCRIPTKIT_TOKEN = envData?.GITHUB_SCRIPTKIT_TOKEN;
} else if (kitState.kenvEnv.GITHUB_SCRIPTKIT_TOKEN) {
log.info(`Removing GITHUB_SCRIPTKIT_TOKEN from kitState.kenvEnv`);
delete kitState.kenvEnv.GITHUB_SCRIPTKIT_TOKEN;
kitState.isSponsor = false;

checkUserDb();
}

if (envData?.KIT_API_KEY) {
log.info(`Detected KIT_API_KEY in .env. Setting kitState.kenvEnv.KIT_API_KEY`);
kitState.kenvEnv.KIT_API_KEY = envData?.KIT_API_KEY;
}else if(kitState.kenvEnv.KIT_API_KEY){
} else if (kitState.kenvEnv.KIT_API_KEY) {
log.info(`Removing KIT_API_KEY from kitState.kenvEnv`);
delete kitState.kenvEnv.KIT_API_KEY;

checkUserDb();
}

if (envData?.KIT_DOCK) {
Expand Down Expand Up @@ -680,30 +703,30 @@ export const restartWatchers = debounce(
{ leading: false },
);

export function watchKenvDirectory(){
export function watchKenvDirectory() {
const kenvFolderWatcher = chokidar.watch(kenvChokidarPath(), {
ignoreInitial: kitState.ignoreInitial,
followSymlinks: true,
depth: 0,
ignored: (checkPath) => {
return path.normalize(checkPath) !== path.normalize(kenvChokidarPath());
}
},
});

const watcherHandler = (eventName:WatchEvent, filePath:string) => {
const watcherHandler = (eventName: WatchEvent, filePath: string) => {
log.info(`🔄 ${eventName} ${filePath} from kenv folder watcher`);
if(eventName === 'addDir'){
if (eventName === 'addDir') {
setTimeout(() => {
if(watchers.length === 0){
if (watchers.length === 0) {
log.warn(`🔄 ${filePath} added. Setting up watchers...`);
setupWatchers('addDir');
}else{
} else {
log.info(`🔄 ${filePath} added, but watchers already exist. No need to setup watchers...`);
}
}, 2000);
}

if(eventName === 'unlinkDir'){
if (eventName === 'unlinkDir') {
log.warn(`🔄 ${filePath} unlinked. Tearing down watchers...`);
teardownWatchers('unlinkDir');
}
Expand All @@ -715,7 +738,7 @@ export function watchKenvDirectory(){
depth: 0,
ignored: (checkPath) => {
return path.normalize(checkPath) !== path.normalize(kitChokidarPath());
}
},
});

kenvFolderWatcher.on('all', watcherHandler);
Expand Down Expand Up @@ -787,25 +810,33 @@ let pingInterval: NodeJS.Timeout | null = null;
let watchers: FSWatcher[] = [];
let suspendingWatchers: boolean;

export const teardownWatchers = debounce((reason: string) => {
logActionReason('Teardown', reason);
stopPingInterval();
clearAllWatchers(watchers);
}, 250, { leading: true });
export const teardownWatchers = debounce(
(reason: string) => {
logActionReason('Teardown', reason);
stopPingInterval();
clearAllWatchers(watchers);
},
250,
{ leading: true },
);

export const setupWatchers = debounce((reason: string) => {
if (settingUpWatchers) return;
settingUpWatchers = true;
export const setupWatchers = debounce(
(reason: string) => {
if (settingUpWatchers) return;
settingUpWatchers = true;

logActionReason('Setup', reason);
logActionReason('Setup', reason);

teardownWatchers('setupWatchers');
refreshScriptsIfNeeded();
startPingInterval();
watchers = startCoreWatchers();
teardownWatchers('setupWatchers');
refreshScriptsIfNeeded();
startPingInterval();
watchers = startCoreWatchers();

settingUpWatchers = false;
}, 1000, { leading: true });
settingUpWatchers = false;
},
1000,
{ leading: true },
);

subscribeKey(kitState, 'suspendWatchers', (suspendWatchers) => {
if (suspendingWatchers === suspendWatchers) return;
Expand Down Expand Up @@ -860,7 +891,7 @@ async function handleFileChangeEvent(eventName: WatchEvent, filePath: string, so
return;
}

if (base === "globals.ts") {
if (base === 'globals.ts') {
log.info(`globals.ts ${eventName}`);
clearIdleProcesses();
ensureIdleProcess();
Expand Down Expand Up @@ -893,7 +924,7 @@ async function handleFileChangeEvent(eventName: WatchEvent, filePath: string, so

if (dir.endsWith('snippets')) {
if (eventName === 'add' || eventName === 'change') {
await cacheMainScripts("Snippet added or changed");
await cacheMainScripts('Snippet added or changed');
log.info('Snippet added/changed', filePath);
addTextSnippet(filePath);
} else {
Expand Down
3 changes: 1 addition & 2 deletions src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export default function App() {
const setMouseEnabled = useSetAtom(mouseEnabledAtom);
const setTopRef = useSetAtom(topRefAtom);
const setProcesses = useSetAtom(processesAtom);
const setUser = useSetAtom(userAtom);
const [user, setUser] = useAtom(userAtom);
const setIsMouseDown = useSetAtom(isMouseDownAtom);

const [kitState] = useAtom(kitStateAtom);
Expand Down Expand Up @@ -684,7 +684,6 @@ text-text-base
{pid}
{shortcodes}
</span> */}

<main id="main" className="min-h-[1px] w-full flex-1 overflow-y-hidden">
{flagValue && <ActionsList key="ActionsList" />}
<PanelGroup
Expand Down
Loading

0 comments on commit f805b6c

Please sign in to comment.