repo_id
stringclasses
563 values
file_path
stringlengths
40
166
content
stringlengths
1
2.94M
__index_level_0__
int64
0
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/constants/emoji.ts
export enum Emoji { CROSS = "❌ ", CHECKMARK = "βœ… ", LOOKING_GLASS = "πŸ” ", CANDY = "🍬 ", COMPUTER = "πŸ–₯ ", PAPER = "πŸ“ ", CONFETTI = "πŸŽ‰ ", PAYMENT = "πŸ’΅ ", UPLOAD = "πŸ“€ ", WITHDRAW = "🏧 ", ASSETS = "πŸ—‚ ", LAUNCH = "πŸš€ ", COLLECTION = "πŸ“¦ ", ERROR = "πŸ›‘ ", WARNING = "⚠️ ", SIGNING = "✍️ ", ICE_CUBE = "🧊 ", FIRE = "πŸ”₯ ", RIGHT_ARROW = "➑️ ", MONEY_BAG = "πŸ’° ", SOL = "β—Ž", GUARD = "πŸ›‘ ", WRAP = "πŸ“¦ ", UNWRAP = "πŸ”© ", }
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/constants/index.ts
export * from "./connection"; export * from "./dom"; export * from "./emoji"; export * from "./errors"; export * from "./event"; export * from "./project";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/constants/event.ts
export enum EventName { // Editor EDITOR_FOCUS = "editorfocus", EDITOR_FORMAT = "editorformat", // Modal MODAL_SET = "modalset", // Playnet PLAYNET_ON_DID_INIT = "playnetondidinit", // Router ROUTER_NAVIGATE = "routernavigate", ROUTER_ON_DID_CHANGE_PATH = "routerondidchangepath", // Terminal TERMINAL_STATIC = "terminalstatic", TERMINAL_PROGRESS_SET = "terminalprogressset", // Theme THEME_SET = "themeset", THEME_FONT_SET = "fontset", // Toast TOAST_SET = "toastset", TOAST_CLOSE = "toastclose", // View VIEW_MAIN_PRIMARY_STATIC = "viewmainprimarystatic", VIEW_MAIN_SECONDARY_HEIGHT_SET = "viewmainsecondaryheightset", VIEW_MAIN_SECONDARY_FOCUS = "viewmainsecondaryfocus", VIEW_MAIN_SECONDARY_PAGE_SET = "viewmainsecondarypageset", VIEW_NEW_ITEM_PORTAL_SET = "viewnewitemportalset", VIEW_SIDEBAR_PAGE_NAME_SET = "viewsidebarpagenameset", VIEW_SIDEBAR_LOADING_SET = "viewsidebarloadingset", VIEW_ON_DID_CHANGE_SIDEBAR_PAGE = "viewondidchangesidebarpage", VIEW_ON_DID_CHANGE_MAIN_SECONDARY_PAGE = "viewondidchangemainsecondarypage", }
0
solana_public_repos/solana-playground/solana-playground/client/src/providers
solana_public_repos/solana-playground/solana-playground/client/src/providers/solana/index.ts
export { SolanaProvider } from "./SolanaProvider";
0
solana_public_repos/solana-playground/solana-playground/client/src/providers
solana_public_repos/solana-playground/solana-playground/client/src/providers/solana/SolanaProvider.tsx
import { FC, useEffect, useMemo } from "react"; import { useWallet, WalletProvider } from "@solana/wallet-adapter-react"; import { PgWallet } from "../../utils/pg"; export const SolanaProvider: FC = ({ children }) => { const wallets = useMemo(() => [], []); return ( <WalletProvider wallets={wallets}> <PgWalletProvider>{children}</PgWalletProvider> </WalletProvider> ); }; const PgWalletProvider: FC = ({ children }) => { const { wallets, publicKey } = useWallet(); // Handle the connection of Solana wallets to Playground Wallet useEffect(() => { // Add timeout because `PgWallet` listeners are not available on mount const id = setTimeout(() => { PgWallet.standardWallets = wallets; }); return () => clearTimeout(id); }, [wallets, publicKey]); return <>{children}</>; };
0
solana_public_repos/solana-playground/solana-playground/client/src/providers
solana_public_repos/solana-playground/solana-playground/client/src/providers/theme/ThemeProvider.tsx
import { FC, useEffect, useState } from "react"; import styled, { css, ThemeProvider as StyledThemeProvider, } from "styled-components"; import { FONTS, THEMES } from "../../theme"; import { Font, PgTheme, ThemeReady } from "../../utils/pg/theme"; import { EventName } from "../../constants/event"; import { useSetStatic } from "../../hooks/useSetStatic"; export const ThemeProvider: FC = ({ children }) => { const [theme, setTheme] = useState<ThemeReady>(); const [font, setFont] = useState<Font>(); useSetStatic(setTheme, EventName.THEME_SET); useSetStatic(setFont, EventName.THEME_FONT_SET); // Create initial theme useEffect(() => { PgTheme.create(THEMES, FONTS); }, []); // Update `theme.font` when theme or font changes useEffect(() => { if (theme && font) { const fontFamily = PgTheme.addFallbackFont(font.family); if (theme.font.code.family !== fontFamily) { setTheme((t) => { return ( t && { ...t, font: { code: { ...font, family: fontFamily }, other: t.font.other, }, } ); }); } } }, [theme, font]); if (!theme || !font) return null; return ( <StyledThemeProvider theme={theme}> <Wrapper>{children}</Wrapper> </StyledThemeProvider> ); }; // Set default theme values const Wrapper = styled.div` ${({ theme }) => css` background: ${theme.colors.default.bgPrimary}; color: ${theme.colors.default.textPrimary}; font-family: ${theme.font.code.family}; font-size: ${theme.font.code.size.medium}; & svg { transition: color ${theme.default.transition.duration.short} ${theme.default.transition.type}; } & ::selection { background: ${theme.colors.default.primary + theme.default.transparency.medium}; } `} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/providers
solana_public_repos/solana-playground/solana-playground/client/src/providers/theme/index.ts
export { ThemeProvider } from "./ThemeProvider";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/bpf-upgradeable-browser/instruction.ts
import { Buffer } from "buffer"; import * as BufferLayout from "@solana/buffer-layout"; import * as Layout from "./layout"; /** * @internal */ export type InstructionType = { /** The Instruction index (from solana upstream program) */ index: number; /** The BufferLayout to use to build data */ layout: BufferLayout.Layout<any>; }; /** * Populate a buffer of instruction data using an InstructionType * @internal */ export function encodeData(type: InstructionType, fields?: any): Buffer { const allocLength = type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields); const data = Buffer.alloc(allocLength); const layoutFields = Object.assign({ instruction: type.index }, fields); type.layout.encode(layoutFields, data); return data; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/bpf-upgradeable-browser/layout.ts
import { Buffer } from "buffer"; import * as BufferLayout from "@solana/buffer-layout"; /** * Layout for a Rust Vec<u8> type */ export const rustVecBytes = (property: string = "string") => { const rvbl = BufferLayout.struct<any>( [ BufferLayout.u32("length"), BufferLayout.u32("lengthPadding"), BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), "bytes"), ], property ); const _decode = rvbl.decode.bind(rvbl); const _encode = rvbl.encode.bind(rvbl); rvbl.decode = (buffer: any, offset: any) => { const data = _decode(buffer, offset); return data["bytes"]; }; rvbl.encode = (bytes: Buffer, buffer: any, offset: any) => { const data = { bytes, }; return _encode(data, buffer, offset); }; (rvbl as any).alloc = (bytes: Buffer) => { return BufferLayout.u32().span + BufferLayout.u32().span + bytes.length; }; return rvbl; }; export function getAlloc(type: any, fields: any): number { let alloc = 0; type.layout.fields.forEach((item: any) => { if (item.span >= 0) { alloc += item.span; } else if (typeof item.alloc === "function") { alloc += item.alloc(fields[item.property]); } }); return alloc; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/bpf-upgradeable-browser/index.ts
export * from "./bpf-upgradeable-browser";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/bpf-upgradeable-browser/bpf-upgradeable-browser.ts
// Thanks to @fanatid import { Buffer } from "buffer"; import * as BufferLayout from "@solana/buffer-layout"; import { PACKET_DATA_SIZE, PublicKey, SYSVAR_CLOCK_PUBKEY, SYSVAR_RENT_PUBKEY, SystemProgram, Transaction, TransactionInstruction, Signer, } from "@solana/web3.js"; import { encodeData, InstructionType } from "./instruction"; import * as Layout from "./layout"; import { ConnectionOption, PgCommon, PgConnection, PgTx, PgWallet, WalletOption, } from "../pg"; const BPF_LOADER_UPGRADEABLE_PROGRAM_ID = new PublicKey( "BPFLoaderUpgradeab1e11111111111111111111111" ); /** An enumeration of valid BpfUpgradeableLoaderInstructionType's */ type BpfUpgradeableLoaderInstructionType = | "InitializeBuffer" | "Write" | "DeployWithMaxDataLen" | "Upgrade" | "SetAuthority" | "Close"; /** * An enumeration of valid system InstructionType's * @internal */ const BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS: { [type in BpfUpgradeableLoaderInstructionType]: InstructionType; } = Object.freeze({ InitializeBuffer: { index: 0, layout: BufferLayout.struct<BufferLayout.UInt>([ BufferLayout.u32("instruction"), ]), }, Write: { index: 1, layout: BufferLayout.struct<BufferLayout.UInt>([ BufferLayout.u32("instruction"), BufferLayout.u32("offset"), Layout.rustVecBytes("bytes"), ]), }, DeployWithMaxDataLen: { index: 2, layout: BufferLayout.struct<BufferLayout.UInt>([ BufferLayout.u32("instruction"), BufferLayout.u32("maxDataLen"), BufferLayout.u32("maxDataLenPadding"), ]), }, Upgrade: { index: 3, layout: BufferLayout.struct<BufferLayout.UInt>([ BufferLayout.u32("instruction"), ]), }, SetAuthority: { index: 4, layout: BufferLayout.struct<BufferLayout.UInt>([ BufferLayout.u32("instruction"), ]), }, Close: { index: 5, layout: BufferLayout.struct<BufferLayout.UInt>([ BufferLayout.u32("instruction"), ]), }, }); /** Initialize buffer tx params */ type InitializeBufferParams = { /** Public key of the buffer account */ bufferPk: PublicKey; /** Public key to set as authority of the initialized buffer */ authorityPk: PublicKey; }; /** Write tx params */ type WriteParams = { /** Offset at which to write the given bytes. */ offset: number; /** Chunk of program data */ bytes: Buffer; /** Public key of the buffer account */ bufferPk: PublicKey; /** Public key to set as authority of the initialized buffer */ authorityPk: PublicKey; }; /** Deploy program tx params */ type DeployWithMaxProgramLenParams = { /** Maximum length that the program can be upgraded to. */ maxDataLen: number; /** The uninitialized Program account */ programPk: PublicKey; /** The buffer account where the program data has been written. The buffer account’s authority must match the program’s authority */ bufferPk: PublicKey; /** The program’s authority */ upgradeAuthorityPk: PublicKey; /** The payer account that will pay to create the ProgramData account */ payerPk: PublicKey; }; /** Upgrade tx params */ type UpgradeParams = { /** The program account */ programPk: PublicKey; /** The buffer account where the program data has been written. The buffer account’s authority must match the program’s authority */ bufferPk: PublicKey; /** The spill account */ spillPk: PublicKey; /** The program’s authority */ authorityPk: PublicKey; }; /** Update buffer authority tx params */ type SetBufferAuthorityParams = { /** The buffer account where the program data has been written */ bufferPk: PublicKey; /** The buffer's authority */ authorityPk: PublicKey; /** New buffer's authority */ newAuthorityPk: PublicKey; }; /** Update program authority tx params */ type SetUpgradeAuthorityParams = { /** The program account */ programPk: PublicKey; /** The current authority */ authorityPk: PublicKey; /** The new authority, optional, if omitted then the program will not be upgradable */ newAuthorityPk: PublicKey | undefined; }; /** Close account tx params */ type CloseParams = { /** The account to close */ closePk: PublicKey; /** The account to deposit the closed account’s lamports */ recipientPk: PublicKey; /** The account’s authority, Optional, required for initialized accounts */ authorityPk: PublicKey | undefined; /** The associated Program account if the account to close is a ProgramData account */ programPk: PublicKey | undefined; }; /** * Factory class for txs to interact with the BpfLoaderUpgradeable program */ class BpfLoaderUpgradeableProgram { /** Public key that identifies the BpfLoaderUpgradeable program */ static programId = BPF_LOADER_UPGRADEABLE_PROGRAM_ID; /** Derive programData address from program. */ static async getProgramDataAddress(programPk: PublicKey): Promise<PublicKey> { return ( await PublicKey.findProgramAddress([programPk.toBuffer()], this.programId) )[0]; } /** Generate a tx instruction that initialize buffer account. */ static initializeBuffer( params: InitializeBufferParams ): TransactionInstruction { const type = BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS.InitializeBuffer; const data = encodeData(type, {}); return new TransactionInstruction({ keys: [ { pubkey: params.bufferPk, isSigner: false, isWritable: true }, { pubkey: params.authorityPk, isSigner: false, isWritable: false }, ], programId: this.programId, data, }); } /** * Generate a tx instruction that write a chunk of program data to a buffer * account. */ static write(params: WriteParams): TransactionInstruction { const type = BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS.Write; const data = encodeData(type, { offset: params.offset, bytes: params.bytes, }); return new TransactionInstruction({ keys: [ { pubkey: params.bufferPk, isSigner: false, isWritable: true }, { pubkey: params.authorityPk, isSigner: true, isWritable: false }, ], programId: this.programId, data, }); } /** * Generate a tx instruction that deploy a program with a specified maximum * program length. */ static async deployWithMaxProgramLen( params: DeployWithMaxProgramLenParams ): Promise<TransactionInstruction> { const type = BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS.DeployWithMaxDataLen; const data = encodeData(type, { maxDataLen: params.maxDataLen, maxDataLenPadding: 0, }); const programDataPk = await this.getProgramDataAddress(params.programPk); return new TransactionInstruction({ keys: [ { pubkey: params.payerPk, isSigner: true, isWritable: true }, { pubkey: programDataPk, isSigner: false, isWritable: true }, { pubkey: params.programPk, isSigner: false, isWritable: true }, { pubkey: params.bufferPk, isSigner: false, isWritable: true }, { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false }, { pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false }, { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, { pubkey: params.upgradeAuthorityPk, isSigner: true, isWritable: false, }, ], programId: this.programId, data, }); } /** Generate a tx instruction that upgrade a program. */ static async upgrade(params: UpgradeParams): Promise<TransactionInstruction> { const type = BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS.Upgrade; const data = encodeData(type, {}); const programDataPk = await this.getProgramDataAddress(params.programPk); return new TransactionInstruction({ keys: [ { pubkey: programDataPk, isSigner: false, isWritable: true }, { pubkey: params.programPk, isSigner: false, isWritable: true }, { pubkey: params.bufferPk, isSigner: false, isWritable: true }, { pubkey: params.spillPk, isSigner: true, isWritable: true }, { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false }, { pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false }, { pubkey: params.authorityPk, isSigner: true, isWritable: false, }, ], programId: this.programId, data, }); } /** Generate a tx instruction that set a new buffer authority. */ static setBufferAuthority( params: SetBufferAuthorityParams ): TransactionInstruction { const type = BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS.SetAuthority; const data = encodeData(type, {}); return new TransactionInstruction({ keys: [ { pubkey: params.bufferPk, isSigner: false, isWritable: true }, { pubkey: params.authorityPk, isSigner: true, isWritable: false, }, { pubkey: params.newAuthorityPk, isSigner: false, isWritable: false, }, ], programId: this.programId, data, }); } /** Generate a tx instruction that set a new program authority. */ static async setUpgradeAuthority( params: SetUpgradeAuthorityParams ): Promise<TransactionInstruction> { const type = BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS.SetAuthority; const data = encodeData(type, {}); const programDataPk = await this.getProgramDataAddress(params.programPk); const keys = [ { pubkey: programDataPk, isSigner: false, isWritable: true }, { pubkey: params.authorityPk, isSigner: true, isWritable: false, }, ]; if (params.newAuthorityPk) { keys.push({ pubkey: params.newAuthorityPk, isSigner: false, isWritable: false, }); } return new TransactionInstruction({ keys, programId: this.programId, data, }); } /** * Generate a tx instruction that close a program, a buffer, or an * uninitialized account. */ static close(params: CloseParams): TransactionInstruction { const type = BPF_UPGRADEABLE_LOADER_INSTRUCTION_LAYOUTS.Close; const data = encodeData(type, {}); const keys = [ { pubkey: params.closePk, isSigner: false, isWritable: true }, { pubkey: params.recipientPk, isSigner: false, isWritable: true, }, ]; if (params.authorityPk) { keys.push({ pubkey: params.authorityPk, isSigner: true, isWritable: false, }); } if (params.programPk) { keys.push({ pubkey: params.programPk, isSigner: false, isWritable: true, }); } return new TransactionInstruction({ keys, programId: this.programId, data, }); } } /** BpfLoaderUpgradeable program interface */ export class BpfLoaderUpgradeable { /** Buffer account size without data */ static BUFFER_HEADER_SIZE: number = 37; // Option<Pk> /** Program account size */ static BUFFER_PROGRAM_SIZE: number = 36; // Pk /** ProgramData account size without data */ static BUFFER_PROGRAM_DATA_HEADER_SIZE: number = 45; // usize + Option<Pk> /** Maximal chunk of the data per tx */ static WRITE_CHUNK_SIZE: number = PACKET_DATA_SIZE - // Maximum transaction size 220 - // Data with 1 signature 44; // Priority fee instruction size /** Get buffer account size. */ static getBufferAccountSize(programLen: number) { return this.BUFFER_HEADER_SIZE + programLen; } /** Create and initialize a buffer account. */ static async createBuffer( buffer: Signer, lamports: number, programLen: number, opts?: WalletOption ) { const { wallet } = this._getOptions(opts); const tx = new Transaction(); tx.add( SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: buffer.publicKey, lamports, space: this.getBufferAccountSize(programLen), programId: BPF_LOADER_UPGRADEABLE_PROGRAM_ID, }) ); tx.add( BpfLoaderUpgradeableProgram.initializeBuffer({ bufferPk: buffer.publicKey, authorityPk: wallet.publicKey, }) ); return await PgTx.send(tx, { keypairSigners: [buffer], wallet, }); } /** Update the buffer authority. */ static async setBufferAuthority( bufferPk: PublicKey, newAuthorityPk: PublicKey, opts?: WalletOption ) { const { wallet } = this._getOptions(opts); const tx = new Transaction(); tx.add( BpfLoaderUpgradeableProgram.setBufferAuthority({ bufferPk, authorityPk: wallet.publicKey, newAuthorityPk, }) ); return await PgTx.send(tx, { wallet }); } /** Load programData to the initialized buffer account. */ static async loadBuffer( bufferPk: PublicKey, programData: Buffer, opts?: { loadConcurrency?: number; abortController?: AbortController; onWrite?: (offset: number) => void; onMissing?: (missingCount: number) => void; } & ConnectionOption & WalletOption ) { const { connection, wallet } = this._getOptions(opts); const { loadConcurrency } = PgCommon.setDefault(opts, { loadConcurrency: 8, }); const loadBuffer = async (indices: number[], isMissing?: boolean) => { if (isMissing) opts?.onMissing?.(indices.length); let i = 0; await Promise.all( new Array(loadConcurrency).fill(null).map(async () => { while (1) { if (opts?.abortController?.signal.aborted) return; const offset = indices[i] * BpfLoaderUpgradeable.WRITE_CHUNK_SIZE; i++; const endOffset = offset + BpfLoaderUpgradeable.WRITE_CHUNK_SIZE; const bytes = programData.slice(offset, endOffset); if (bytes.length === 0) break; const tx = new Transaction(); tx.add( BpfLoaderUpgradeableProgram.write({ offset, bytes, bufferPk, authorityPk: wallet.publicKey, }) ); try { await PgTx.send(tx, { connection, wallet }); if (!isMissing) opts?.onWrite?.(endOffset); } catch (e: any) { console.log("Buffer write error:", e.message); } } }) ); }; const txCount = Math.ceil( programData.length / BpfLoaderUpgradeable.WRITE_CHUNK_SIZE ); const indices = new Array(txCount).fill(null).map((_, i) => i); let isMissing = false; // Retry until all bytes are written while (1) { if (opts?.abortController?.signal.aborted) return; // Wait for last transaction to confirm await PgCommon.sleep(500); // Even though we only get to this function after buffer account creation // gets confirmed, the RPC can still return `null` here if it's behind. const bufferAccount = await PgCommon.tryUntilSuccess(async () => { const acc = await connection.getAccountInfo(bufferPk); if (!acc) throw new Error(); return acc; }, 2000); const onChainProgramData = bufferAccount.data.slice( BpfLoaderUpgradeable.BUFFER_HEADER_SIZE, BpfLoaderUpgradeable.BUFFER_HEADER_SIZE + programData.length ); if (onChainProgramData.equals(programData)) break; const missingIndices = indices .map((i) => { const start = i * BpfLoaderUpgradeable.WRITE_CHUNK_SIZE; const end = start + BpfLoaderUpgradeable.WRITE_CHUNK_SIZE; const actualSlice = programData.slice(start, end); const onChainSlice = onChainProgramData.slice(start, end); if (!actualSlice.equals(onChainSlice)) return i; return null; }) .filter((i) => i !== null) as number[]; await loadBuffer(missingIndices, isMissing); isMissing = true; } } /** Close the buffer account and withdraw funds. */ static async closeBuffer(bufferPk: PublicKey, opts?: WalletOption) { const { wallet } = this._getOptions(opts); const tx = new Transaction(); tx.add( BpfLoaderUpgradeableProgram.close({ closePk: bufferPk, recipientPk: wallet.publicKey, authorityPk: wallet.publicKey, programPk: undefined, }) ); return await PgTx.send(tx, { wallet }); } /** Create a program account from initialized buffer. */ static async deployProgram( program: Signer, bufferPk: PublicKey, programLamports: number, maxDataLen: number, opts?: WalletOption ) { const { wallet } = this._getOptions(opts); const tx = new Transaction(); tx.add( SystemProgram.createAccount({ fromPubkey: wallet.publicKey, newAccountPubkey: program.publicKey, lamports: programLamports, space: this.BUFFER_PROGRAM_SIZE, programId: BPF_LOADER_UPGRADEABLE_PROGRAM_ID, }) ); tx.add( await BpfLoaderUpgradeableProgram.deployWithMaxProgramLen({ programPk: program.publicKey, bufferPk, upgradeAuthorityPk: wallet.publicKey, payerPk: wallet.publicKey, maxDataLen, }) ); return await PgTx.send(tx, { wallet, keypairSigners: [program], }); } /** Update the program authority. */ static async setProgramAuthority( programPk: PublicKey, newAuthorityPk: PublicKey | undefined, opts?: WalletOption ) { const { wallet } = this._getOptions(opts); const tx = new Transaction(); tx.add( await BpfLoaderUpgradeableProgram.setUpgradeAuthority({ programPk, authorityPk: wallet.publicKey, newAuthorityPk, }) ); return await PgTx.send(tx, { wallet }); } /** Upgrade a program. */ static async upgradeProgram( programPk: PublicKey, bufferPk: PublicKey, opts?: WalletOption ) { const { wallet } = this._getOptions(opts); const tx = new Transaction(); tx.add( await BpfLoaderUpgradeableProgram.upgrade({ programPk, bufferPk, authorityPk: wallet.publicKey, spillPk: wallet.publicKey, }) ); return await PgTx.send(tx, { wallet }); } /** Close the program account and withdraw funds. */ static async closeProgram(programPk: PublicKey, opts?: WalletOption) { const { wallet } = this._getOptions(opts); const tx = new Transaction(); tx.add( BpfLoaderUpgradeableProgram.close({ closePk: await BpfLoaderUpgradeableProgram.getProgramDataAddress( programPk ), recipientPk: wallet.publicKey, authorityPk: wallet.publicKey, programPk, }) ); return await PgTx.send(tx, { wallet }); } /** Get the connection and wallet instance. */ private static _getOptions(opts?: ConnectionOption & WalletOption) { const connection = opts?.connection ?? PgConnection.current; const wallet = opts?.wallet ?? PgWallet.current; if (!wallet) throw new Error("Wallet is not connected"); return { connection, wallet }; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/block-explorer.ts
import { PgConnection } from "./connection"; import { createDerivable, declareDerivable, derivable } from "./decorators"; import { PgSettings } from "./settings"; interface BlockExplorerImpl { /** Name of the block explorer */ name: string; /** Base URL of the explorer website */ url: string; /** * Get the cluster URL parameter to add to the explorer URLs. * * @returns the cluster URL parameter */ getClusterParam(): string; /** * Get the common URL i.e. a URL that follows simple enough `path` and * `value` in order to be able to derive the full URLs. * * @param path URL path * @param value last path value */ getCommonUrl?(path: string, value: string): string; /** * Get address URL for the configured explorer. * * @param address public key * @returns the address URL */ getAddressUrl?(address: string): string; /** * Get transaction URL for the configured explorer. * * @param txHash transaction signature * @returns the transaction URL */ getTxUrl?(txHash: string): string; } type BlockExplorer = Omit< Required<BlockExplorerImpl>, "getClusterParam" | "getCommonUrl" >; const derive = () => ({ /** The current block explorer based on user's block explorer setting */ current: createDerivable({ derive: () => { return _PgBlockExplorer.all.find( (be) => be.name === PgSettings.other.blockExplorer )!; }, onChange: [ PgSettings.onDidChangeOtherBlockExplorer, PgConnection.onDidChangeCluster, ], }), }); @derivable(derive) class _PgBlockExplorer { /** All block explorers */ static all: BlockExplorer[]; /** * Create a block explorer. * * @param b block explorer implementation * @returns the created block explorer */ static create(b: BlockExplorerImpl): BlockExplorer { b.getCommonUrl ??= (p, v) => b.url + "/" + p + "/" + v + b.getClusterParam(); b.getAddressUrl ??= (address) => b.getCommonUrl!("address", address); b.getTxUrl ??= (txHash) => b.getCommonUrl!("tx", txHash); return b as BlockExplorer; } } export const PgBlockExplorer = declareDerivable(_PgBlockExplorer, derive);
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-info.ts
import { decodeIdlAccount, idlAddress } from "@coral-xyz/anchor/dist/cjs/idl"; import type { Idl } from "@coral-xyz/anchor"; import { PgBytes } from "./bytes"; import { PgCommand } from "./command"; import { PgConnection } from "./connection"; import { createDerivable, declareDerivable, declareUpdatable, derivable, migratable, updatable, } from "./decorators"; import { PgExplorer } from "./explorer"; import { PgWeb3 } from "./web3"; import type { Nullable } from "./types"; /** Program info state */ type ProgramInfo = Nullable<{ /** Program's build server uuid */ uuid: string; /** Program's keypair */ kp: PgWeb3.Keypair; /** Program's custom public key */ customPk: PgWeb3.PublicKey; /** Program's Anchor IDL */ idl: Idl; /** Imported program binary file */ importedProgram: { buffer: Buffer; fileName: string; }; }>; /** Serialized program info that's used in storage */ type SerializedProgramInfo = Nullable<{ uuid: string; kp: Array<number>; customPk: string; idl: Idl; }>; const defaultState: ProgramInfo = { uuid: null, kp: null, customPk: null, idl: null, importedProgram: null, }; const storage = { /** Relative path to program info */ PATH: ".workspace/program-info.json", /** Read from storage and deserialize the data. */ async read(): Promise<ProgramInfo> { if (!PgExplorer.currentWorkspaceName) return defaultState; let serializedState: SerializedProgramInfo; try { serializedState = await PgExplorer.fs.readToJSON(this.PATH); } catch { return defaultState; } return { ...serializedState, kp: serializedState.kp ? PgWeb3.Keypair.fromSecretKey(Uint8Array.from(serializedState.kp)) : null, customPk: serializedState.customPk ? new PgWeb3.PublicKey(serializedState.customPk) : null, importedProgram: defaultState.importedProgram, }; }, /** Serialize the data and write to storage. */ async write(state: ProgramInfo) { if (!PgExplorer.currentWorkspaceName) return; // Don't use spread operator(...) because of the extra derived state const serializedState: SerializedProgramInfo = { uuid: state.uuid, idl: state.idl, kp: state.kp ? Array.from(state.kp.secretKey) : null, customPk: state.customPk?.toBase58() ?? null, }; await PgExplorer.fs.writeFile(this.PATH, JSON.stringify(serializedState)); }, }; const derive = () => ({ /** * Get the program's public key. * * Custom public key has priority if it's specified. */ pk: createDerivable({ derive: (): PgWeb3.PublicKey | null => { if (PgProgramInfo.customPk) return PgProgramInfo.customPk; if (PgProgramInfo.kp) return PgProgramInfo.kp.publicKey; return null; }, onChange: ["kp", "customPk"], }), /** On-chain data of the program */ onChain: createDerivable({ derive: async () => { try { return await _PgProgramInfo.fetch(); } catch {} }, onChange: ["pk", PgConnection.onDidChange, PgCommand.deploy.onDidRunFinish], }), }); // TODO: Remove in 2024 const migrate = () => { // Removing the `program-info` key is enough for migration because the data // is already stored in `indexedDB` localStorage.removeItem("programInfo"); }; @migratable(migrate) @derivable(derive) @updatable({ defaultState, storage }) class _PgProgramInfo { /** Get the current program's pubkey as base58 string. */ static getPkStr() { return PgProgramInfo.pk?.toBase58() ?? null; } /** Get the JSON.stringified IDL from state. */ static getIdlStr() { if (PgProgramInfo.idl) return JSON.stringify(PgProgramInfo.idl); return null; } /** * Fetch the program from chain. * * @param programId optional program id * @returns program's authority and whether the program is upgradable */ static async fetch(programId: PgWeb3.PublicKey | null = PgProgramInfo.pk) { if (!programId) throw new Error("Program id doesn't exist"); const conn = PgConnection.current; if (!PgConnection.isReady(conn)) throw new Error("Connection is not ready"); const programAccountInfo = await conn.getAccountInfo(programId); const deployed = !!programAccountInfo; if (!programAccountInfo) return { deployed, upgradable: true }; const programDataPkBuffer = programAccountInfo.data.slice(4); const programDataPk = new PgWeb3.PublicKey(programDataPkBuffer); const programDataAccountInfo = await conn.getAccountInfo(programDataPk); // Check if program authority exists const authorityExists = programDataAccountInfo?.data.at(12); if (!authorityExists) return { deployed, upgradable: false }; const upgradeAuthorityPkBuffer = programDataAccountInfo?.data.slice(13, 45); const upgradeAuthorityPk = new PgWeb3.PublicKey(upgradeAuthorityPkBuffer!); return { deployed, authority: upgradeAuthorityPk, upgradable: true }; } /** * Fetch the Anchor IDL from chain. * * NOTE: This is a reimplementation of `anchor.Program.fetchIdl` because that * function only returns the IDL without the IDL authority. * * @param programId optional program id * @returns the IDL and the authority of the IDL or `null` if IDL doesn't exist */ static async fetchIdl(programId = PgProgramInfo.pk) { if (!programId) throw new Error("Program id doesn't exist"); const idlPk = await idlAddress(programId); const accountInfo = await PgConnection.current.getAccountInfo(idlPk); if (!accountInfo) return null; // Chop off account discriminator const idlAccount = decodeIdlAccount(accountInfo.data.slice(8)); const { inflate } = await import("pako"); const inflatedIdl = inflate(idlAccount.data); const idl: Idl = JSON.parse(PgBytes.toUtf8(Buffer.from(inflatedIdl))); return { idl, authority: idlAccount.authority }; } } export const PgProgramInfo = declareDerivable( declareUpdatable(_PgProgramInfo, { defaultState }), derive );
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/bytes.ts
import { utils } from "@coral-xyz/anchor"; export class PgBytes { /** Convert the given hex string to `Buffer`. */ static fromHex(str: string) { return utils.bytes.hex.decode(str); } /** Convert the given buffer to hex string. */ static toHex(buf: Buffer) { return utils.bytes.hex.encode(buf); } /** Convert the given base58 string to `Buffer`. */ static fromBase58(str: string) { return utils.bytes.bs58.decode(str); } /** Convert the given buffer to base58 string. */ static toBase58(buf: Buffer) { return utils.bytes.bs58.encode(buf); } /** Convert the given base64 string to `Buffer`. */ static fromBase64(str: string) { return utils.bytes.base64.decode(str); } /** Convert the given buffer to base64 string. */ static toBase64(buf: Buffer) { return utils.bytes.base64.encode(buf); } /** Convert the given UTF-8 string to `Buffer`. */ static fromUtf8(str: string) { return Buffer.from(utils.bytes.utf8.encode(str)); } /** Convert the given buffer to UTF-8 string. */ static toUtf8(buf: Buffer) { return utils.bytes.utf8.decode(buf); } /** Hash the given string with SHA-256 hashing algorithm. */ static hashSha256(str: string) { return utils.sha256.hash(str); } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/editor.ts
import { EventName } from "../../constants"; import { PgCommon } from "./common"; export class PgEditor { /** Focus the editor. */ static focus() { PgCommon.createAndDispatchCustomEvent(EventName.EDITOR_FOCUS); } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/github.ts
import { PgCommon } from "./common"; import { PgExplorer, TupleFiles } from "./explorer"; import { PgFramework } from "./framework"; import { PgLanguage } from "./language"; import { GithubError } from "../../constants"; import type { Arrayable } from "./types"; type GithubRepositoryData = { name: string; path: string; sha: string; size: number; url: string; html_url: string; git_url: string; } & ( | { type: "file"; download_url: string; } | { type: "dir"; download_url: null; } ); export class PgGithub { /** * Get whether the given URL is a GitHub URL. * * @param url URL to check * @returns whether the URL is a GitHub URL */ static isValidUrl(url: string) { return /^(https:\/\/)?(www\.)?github\.com\/.+?\/.+/.test(url); } /** * Parse the given URL to get owner, repository name, ref, and path. * * @param url GitHub URL * @returns the parsed URL */ static parseUrl(url: string) { // https://github.com/solana-labs/solana-program-library/tree/master/token/program const regex = /(https:\/\/)?(github\.com\/)([\w-]+)\/([\w-]+)(\/)?((tree|blob)\/([\w-.]+))?(\/)?([\w-/.]*)/; const res = regex.exec(url); if (!res) throw new Error(GithubError.INVALID_URL); const owner = res[3]; // solana-labs const repo = res[4]; // solana-program-library const ref = res.at(8); // master or `undefined` on root e.g. https://github.com/coral-xyz/xnft const path = res[10]; // token/program return { owner, repo, ref, path }; } /** * Create a new workspace from the given GitHub URL. * * @param url GitHub URL */ static async import(url: string) { // Check whether the repository already exists in user's workspaces const { owner, repo, path } = this.parseUrl(url); const githubWorkspaceName = `github-${owner}/${repo}/${path}`; if (PgExplorer.allWorkspaceNames?.includes(githubWorkspaceName)) { // Switch to the existing workspace await PgExplorer.switchWorkspace(githubWorkspaceName); } else { // Create a new workspace const convertedFiles = await this.getFiles(url); await PgExplorer.newWorkspace(githubWorkspaceName, { files: convertedFiles, skipNameValidation: true, }); } } /** * Get the files from the given repository and map them to `TupleFiles`. * * @param url GitHub URL * @returns explorer files */ static async getFiles(url: string) { const { files } = await this._getRepository(url); const convertedFiles = await PgFramework.convertToPlaygroundLayout(files); return convertedFiles; } /** * Get Github repository data and map the files to `TupleFiles`. * * @param url Github link to the program's folder in the repository * @returns files, owner, repo, path */ private static async _getRepository(url: string) { const { data, owner, repo, path } = await this._getRepositoryData(url); const files: TupleFiles = []; const recursivelyGetFiles = async ( dirData: GithubRepositoryData[], currentUrl: string ) => { // TODO: Filter `dirData` to only include the files we could need // Fetching all files one by one and just returning them without dealing // with any of the framework related checks is great here but it comes // with the cost of using excessive amounts of network requests to fetch // bigger repositories. This is especially a problem if the repository we // are fetching have unrelated files in their program workspace folder. for (const itemData of dirData) { if (itemData.type === "file") { // Skip fetching the content if the language is not supported if (!PgLanguage.getFromPath(itemData.path)) continue; const content = await PgCommon.fetchText(itemData.download_url!); files.push([itemData.path, content]); } else if (itemData.type === "dir") { const insideDirUrl = PgCommon.joinPaths(currentUrl, itemData.name); const { data: insideDirData } = await this._getRepositoryData( insideDirUrl ); await recursivelyGetFiles(insideDirData, insideDirUrl); } } }; await recursivelyGetFiles(data, url); return { files, owner, repo, path }; } /** * Get GitHub repository data. * * @param url GitHub link to the program's folder in the repository * @returns GitHub repository data, owner, repo, path */ private static async _getRepositoryData(url: string) { const { owner, repo, ref, path } = this.parseUrl(url); const refParam = ref ? `?ref=${ref}` : ""; // If it's a single file fetch request, Github returns an object instead of an array const data: Arrayable<GithubRepositoryData> = await PgCommon.fetchJSON( `https://api.github.com/repos/${owner}/${repo}/contents/${path}${refParam}` ); return { data: PgCommon.toArray(data), owner, repo, path }; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/router.ts
import { PgCommon } from "./common"; import { EventName } from "../../constants"; import type { Disposable, OrString, SyncOrAsync } from "./types"; /** Opening delimiter for path variables */ const OPEN = "{"; /** Closing delimiter for path variables */ const CLOSE = "}"; /** Custom route */ type Route<P extends string> = { /** Route pathname, always starts with `/` */ path: P; /** Handler method for the route */ handle: (params: PathParameter<P>) => SyncOrAsync<Disposable | void>; /** Check whether the path is valid */ validate?: (params: PathParameter<P>) => boolean; }; /** Utility type to get the variable names from the given path */ type PathVariable<T extends string> = T extends `${string}${typeof OPEN}${infer V}${typeof CLOSE}${infer R}` ? R extends "" ? PathVariable<V> : PathVariable<V> | PathVariable<R> : T; /** Map the variables to an object with `string` values */ type PathParameter<T extends string> = { [K in PathVariable<T>]: string }; export class PgRouter { /** URL information about the page */ static location = window.location; /** * Initialize the router. * * @param routes all available routes * @returns a dispose function to clear the event */ static init<P extends string>(routes: Route<P>[]) { let disposable: Disposable | undefined; return this.onDidChangePath(async (path) => { // Dispose disposable?.dispose(); let params: PathParameter<P>; const route = routes.find((route) => { try { params = this._getParamsFromPath(path, route.path); if (route.validate) return route.validate(params); return true; } catch { return false; } }); try { disposable = (await route?.handle(params!))!; } catch (e: any) { console.log("ROUTE ERROR:", e.message); this.navigate(); } }); } /** * Create a route with inferred types. * * @param route route to create * @returns the same route with inferred types */ static create<P extends string>(route: Route<P>) { return route; } /** * Navigate to the given path. * * This method will only navigate if the given path is different than the * current path. * * @param path pathname to navigate to */ static navigate(path: OrString<RoutePath> = "/") { const { pathname, search } = this.location; if (!this.isPathsEqual(pathname + search, path)) { PgCommon.createAndDispatchCustomEvent(EventName.ROUTER_NAVIGATE, path); } } /** * Compare pathnames to each other. * * @param pathOne first path * @param pathTwo second path * @returns whether the paths are equal */ static isPathsEqual( pathOne: OrString<RoutePath>, pathTwo: OrString<RoutePath> ) { return PgCommon.isPathsEqual(pathOne, pathTwo); } /** * Runs after path change. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidChangePath(cb: (path: RoutePath) => unknown) { return PgCommon.onDidChange({ cb, eventName: EventName.ROUTER_ON_DID_CHANGE_PATH, }); } /** * Get the custom parameters from the given path. * * ### Example: * * ```ts * const params = _getParamsFromPath("/tutorials/hello-anchor", "/tutorials/{tutorialName}"); * console.log(params); // { tutorialName: "hello-anchor" } * ``` * * @param path current path * @param routePath playground route * @returns the parameters as key-value */ private static _getParamsFromPath<P extends string>( path: string, routePath: P ): PathParameter<P> { const result: Record<string, string> = {}; const recursivelyMapValues = (subPath: string, index = 0) => { const templatePath = routePath.substring(index); if (!templatePath) return; // Get the matching parts const startIndex = templatePath.indexOf(OPEN); if (startIndex === -1) { if (this.isPathsEqual(templatePath, subPath)) return {}; throw new Error("Doesn't match"); } // Remove matching parts if (subPath.slice(0, startIndex) === templatePath.slice(0, startIndex)) { subPath = subPath.slice(startIndex); } const relativeEndIndex = templatePath .substring(startIndex) .indexOf(CLOSE); if (relativeEndIndex === -1) throw new Error("No closing curly"); const endIndex = startIndex + relativeEndIndex; const prop = templatePath.substring(startIndex + 1, endIndex); // Check whether the closing index is the last index if (endIndex === templatePath.length - 1) { if (!subPath.startsWith("/")) { result[prop] = subPath; return; } throw new Error("Doesn't match"); } // Get the next template character const nextTemplateCharacter = templatePath.at(endIndex + 1); if (nextTemplateCharacter) { const newVal = (result[prop] = subPath.substring( 0, subPath.indexOf(nextTemplateCharacter) )); recursivelyMapValues( subPath.substring(newVal.length), index + endIndex + 1 ); } }; recursivelyMapValues(path); return result as PathParameter<P>; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/settings.ts
// Settings are getting loaded at the start of the application, so any non-type // import should be avoided. import { Endpoint } from "../../constants"; import { declareUpdatable, migratable, updatable } from "./decorators"; import type { OrString } from "./types"; interface Settings { /** Connection settings */ connection: { /** Connection RPC URL */ endpoint: OrString<Endpoint>; /** Connection commitment */ commitment: "processed" | "confirmed" | "finalized"; /** Whether to enable preflight checks */ preflightChecks: boolean; /** Priority fee calculcation method, or `number` for custom */ priorityFee: "average" | "median" | "min" | "max" | number; }; /** Build settings */ // TODO: Re-evalute whether build settings should be stored in `PgProgramInfo` // to allow the ability to set program specific settings instead of global? build: { flags: { /** Whether to enable Anchor `seeds` feature */ seedsFeature: boolean; /** Whether to remove docs from the Anchor IDL */ noDocs: boolean; /** Whether to enable Anchor safety checks */ safetyChecks: boolean; }; /** Whether to improve build error logs */ improveErrors: boolean; }; /** Test UI settings */ testUi: { /** Whether to show transaction details in terminal */ showTxDetailsInTerminal: boolean; }; /** Notification settings */ notification: { /** Whether to show transaction toast notification */ showTx: boolean; }; /** Other settings */ other: { /** Block explorer to use */ blockExplorer: string; }; /** Wallet settings */ wallet: { /** Whether to airdrop automatically */ automaticAirdrop: boolean; }; } const defaultState: Settings = { connection: { endpoint: Endpoint.DEVNET, commitment: "confirmed", preflightChecks: true, priorityFee: "median", }, build: { flags: { seedsFeature: false, noDocs: true, safetyChecks: false, }, improveErrors: true, }, testUi: { showTxDetailsInTerminal: false, }, notification: { showTx: true, }, other: { blockExplorer: "Solana Explorer", }, wallet: { automaticAirdrop: true, }, }; const storage = { /** `localStorage` key */ KEY: "settings", /** Read from storage and deserialize the data. */ read() { const stateStr = localStorage.getItem(this.KEY); if (!stateStr) return defaultState; return JSON.parse(stateStr) as Settings; }, /** Serialize the data and write to storage. */ write(state: Settings) { localStorage.setItem(this.KEY, JSON.stringify(state)); }, }; const recursive = true; // TODO: Remove in 2024 const migrate = () => { const migrateFromLocalStorage = <R>(oldKey: string) => { const valueStr = localStorage.getItem(oldKey); if (!valueStr) return; // Remove the old key localStorage.removeItem(oldKey); return JSON.parse(valueStr) as R; }; // Old settings(preferences) interface OldSettings { showTxDetailsInTerminal: boolean; } const oldSettings = migrateFromLocalStorage<OldSettings>("preferences"); // Old connection, layout hasn't changed const oldConnectionConfig = migrateFromLocalStorage<Settings["connection"]>("connection"); const needsMigration = !!(oldSettings && oldConnectionConfig); if (!needsMigration) return; const newValue: Settings = { ...defaultState, connection: oldConnectionConfig, testUi: { showTxDetailsInTerminal: oldSettings.showTxDetailsInTerminal, }, }; localStorage.setItem(storage.KEY, JSON.stringify(newValue)); }; @migratable(migrate) @updatable({ defaultState, storage, recursive }) class _PgSettings {} export const PgSettings = declareUpdatable(_PgSettings, { defaultState, recursive, });
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/language.ts
import { PgCommon } from "./common"; import type { Arrayable } from "./types"; /** Programing language implementation */ type LanguageImpl<N extends string> = { /** Language name */ name: N; /** Valid file extension(s) for the language */ extension: Arrayable<Extension>; }; /** Programming language */ type Language<N extends string> = LanguageImpl<N> & { extension: Array<Extension>; }; /** File extension to match */ type Extension = string; export class PgLanguage { /** All supported programming languages */ static all: Language<LanguageName>[]; /** * Create a programming language. * * @param lang language implementation * @returns the language with correct types */ static create<N extends string>(lang: LanguageImpl<N>) { lang.extension = PgCommon.toArray(lang.extension); return lang as Language<N>; } /** * Get the langugage from the given path's extension. * * @param path item path * @returns the language */ static getFromPath(path: string) { const givenExt = path.split(".").slice(1).join("."); return this.all.find((lang) => lang.extension.some((ext) => givenExt.endsWith(ext)) ); } /** * Get whether the given path is a regular JS/TS or test JS/TS file. * * @path file path * @returns whether the given file is a JavaScript-like file */ static getIsPathJsLike(path: string) { const lang = this.getFromPath(path); switch (lang?.name) { case "JavaScript": case "TypeScript": return true; default: return false; } } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/share.ts
import { PgCommon } from "./common"; import { ExplorerFiles, PgExplorer } from "./explorer"; import { PgServer } from "./server"; export class PgShare { /** * Get the shared project files from the given path. * * @param id shared project id * @returns shared project files */ static async get(id: string) { const shareData = await PgServer.shareGet(id); // Convert `Share` to `ExplorerFiles` to make shares backwards // compatible with the old shares const files: ExplorerFiles = {}; for (const path in shareData.files) { files[path] = { content: shareData.files[path].content }; } return files; } /** * Share a new project. * * @param filePaths file paths to include in the shared project * @returns the share object id */ static async new(filePaths: string[]) { const files = Object.entries(PgExplorer.files).reduce( (acc, [path, item]) => { if (filePaths.includes(path)) acc[path] = item; return acc; }, {} as ExplorerFiles ); // Temporary files are already in a valid form to re-share if (PgExplorer.isTemporary) return await this._new(files); const shareFiles: ExplorerFiles = {}; for (const path in files) { const itemInfo = files[path]; // Remove workspace from path because share only needs /src const sharePath = PgCommon.joinPaths( PgExplorer.PATHS.ROOT_DIR_PATH, PgExplorer.getRelativePath(path) ); shareFiles[sharePath] = itemInfo; } return await this._new(shareFiles); } /** * Get whether the given id is in a valid format. * * @param id share id * @returns whether the given id is in a valid format */ static isValidId(id: string) { return PgCommon.isHex(id); } /** * Share a new project. * * @param files share files * @returns the share object id */ private static async _new(files: ExplorerFiles) { if (!Object.keys(files).length) throw new Error("Empty share"); const shareFiles = Object.entries(files).reduce((acc, [path, data]) => { if (data.content) acc[path] = { content: data.content }; return acc; }, {} as Record<string, { content?: string }>); return await PgServer.shareNew({ explorer: { files: shareFiles } }); } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/common.ts
import type { ChangeEvent } from "react"; import { Endpoint, EventName } from "../../constants"; import type { AllPartial, Disposable, Promisable, SyncOrAsync, Arrayable, OrString, ValueOf, } from "./types"; export class PgCommon { /** * @param ms amount of time to sleep in ms * @returns a promise that will resolve after specified ms */ static async sleep(ms: number) { return new Promise((res) => setTimeout(res, ms)); } /** * Wait at least `ms` amount of miliseconds before resolving. * * @param promisable either `Promise` or a function that returns a `Promise` * @returns the result of the promise parameter */ static async transition<R>(promisable: Promisable<R>, ms: number = 300) { if ((promisable as () => SyncOrAsync<R>)?.call) { promisable = (promisable as () => SyncOrAsync<R>)(); } const result = (await Promise.allSettled([this.sleep(ms), promisable]))[1]; if (result.status === "fulfilled") { return result.value as Promise<Awaited<R>>; } throw new Error(result.reason?.message); } /** * Wait at least `ms` amount of miliseconds before timing out. * * @param promisable either `Promise` or a function that returns a `Promise` * @throws on timeout * @returns the result of the promise parameter */ static async timeout<R>(promisable: Promisable<R>, ms: number) { if ((promisable as () => SyncOrAsync<R>)?.call) { promisable = (promisable as () => SyncOrAsync<R>)(); } return (await Promise.race([ new Promise((_, rej) => this.sleep(ms).then(() => rej("Timed out"))), promisable, ])) as Awaited<R>; } /** * Try the given callback until success. * * @param cb callback function to try * @param tryInterval try interval in miliseconds * @returns the return value of the callback */ static async tryUntilSuccess<T>( cb: () => SyncOrAsync<T>, tryInterval: number ): Promise<T> { let returnValue: T; while (1) { const start = performance.now(); try { returnValue = await this.timeout(cb, tryInterval); break; } catch { const remaining = tryInterval - (performance.now() - start); if (remaining > 0) await this.sleep(remaining); } } return returnValue!; } /** * Debounce the given callback. * * @param cb callback to debounce * @param options - * - delay: how long to wait before running the callback * - sharedTimeout: shared timeout object */ static debounce( cb: () => void, options?: { delay?: number; sharedTimeout?: { id?: NodeJS.Timeout } } ) { const delay = options?.delay ?? 100; const sharedTimeout = options?.sharedTimeout ?? {}; return () => { sharedTimeout.id && clearTimeout(sharedTimeout.id); sharedTimeout.id = setTimeout(cb, delay); }; } /** * Throttle the given callback. * * @param cb callback function to run * @param ms amount of delay in miliseconds * @returns the wrapped callback function */ static throttle<T extends unknown[]>( cb: (...args: T) => void, ms: number = 100 ) { let timeoutId: NodeJS.Timeout; let last = Date.now(); let isInitial = true; return (...args: T) => { const now = Date.now(); if (isInitial) { cb(...args); isInitial = false; return; } if (now < last + ms) { clearTimeout(timeoutId); timeoutId = setTimeout(() => cb(...args), ms); } else { cb(...args); last = now; } }; } /** * Execute the given callback in order. * * This is particularly useful when the desired behavior of an `onChange` * event is to execute its callback in order. * * @param cb callback to run * @returns the wrapped callback function */ static executeInOrder<T>(cb: (...args: [T]) => SyncOrAsync) { type Callback = typeof cb; type CallbackWithArgs = [Callback, Parameters<Callback>]; const queue: CallbackWithArgs[] = []; let isExecuting = false; const execute = async () => { isExecuting = true; while (queue.length !== 0) { for (const index in queue) { const [cb, args] = queue[index]; try { await cb(...args); } catch (e) { throw e; } finally { queue.splice(+index, 1); } } } isExecuting = false; }; const pushQueue = (item: CallbackWithArgs) => { queue.push(item); if (!isExecuting) execute(); }; return async (...args: Parameters<Callback>) => { pushQueue([cb, args]); }; } /** * Call the value and return it if the input is a function or simply return * the given value. * * @param maybeFunction value to check * @returns either the given value or the called value if it's a function */ static callIfNeeded<T>(maybeFunction: T): T extends () => infer R ? R : T { if (typeof maybeFunction === "function") return maybeFunction(); return maybeFunction as T extends () => infer R ? R : T; } /** * Fetch the response from the given URL and return the text response. * * @param url URL * @returns the text response */ static async fetchText(url: string) { const response = await fetch(url); return await response.text(); } /** * Fetch the response from the given URL and return the JSON response. * * @param url URL * @returns the JSON response */ static async fetchJSON(url: string) { const response = await fetch(url); return await response.json(); } /** * @returns the decoded string */ static decodeBytes( b: ArrayBuffer | Buffer | Uint8Array, type: string = "utf-8" ) { const decoder = new TextDecoder(type); const decodedString = decoder.decode(b); return decodedString; } /** * @returns lamports amount to equivalent Sol */ static lamportsToSol(lamports: number) { return lamports / PgCommon._LAMPORTS_PER_SOL; } /** * @returns Sol amount to equivalent lamports */ static solToLamports(sol: number) { return sol * PgCommon._LAMPORTS_PER_SOL; } /** * @returns whether the given values are equal */ static isEqual(value1: any, value2: any) { if (typeof value1 !== typeof value2) return false; switch (typeof value1) { // Default comparison case "boolean": case "number": case "string": case "undefined": return value1 === value2; // String comparison case "bigint": case "function": case "symbol": return value1.toString() === value2.toString(); // Object keys comparison case "object": // `typeof null === "object"` -> true if (value1 === value2) return true; // Compare key lengths if (Object.keys(value1).length !== Object.keys(value2).length) { return false; } // Compare key values for (const key in value1) { if (!PgCommon.isEqual(value1[key], value2[key])) return false; } return true; } } /** * Get whether the colors are the same. Useful when comparing colors with different * color formats(rgb, hex...). * * @returns whether the given colors are equal */ static isColorsEqual(color1: string, color2: string) { // Won't be reading frequently, but it gives a warning on the 2nd read. // Warning: Canvas2D: Multiple readback operations using getImageData are // faster with the willReadFrequently attribute set to true. const ctx = document .createElement("canvas") .getContext("2d", { willReadFrequently: true })!; // Fill color1 ctx.fillStyle = color1; const bg1Args: [number, number, number, number] = [0, 0, 1, 1]; ctx.fillRect(...bg1Args); // Fill color2 ctx.fillStyle = color2; const bg2Args: [number, number, number, number] = [1, 1, 1, 1]; ctx.fillRect(...bg2Args); return PgCommon.isEqual( ctx.getImageData(...bg1Args).data, ctx.getImageData(...bg2Args).data ); } /** * Set the default value for the given object. * * NOTE: This method mutates the given object in place. */ static setDefault<T, D extends AllPartial<T>>(value: T, defaultValue: D) { value ??= {} as T; for (const property in defaultValue) { const result = defaultValue[property] as AllPartial<T[keyof T]>; value[property as keyof T] ??= result as T[keyof T]; } return value as NonNullable<T & D>; } /** * Convert the given input to an array when the input is not an array. * * @param arrayable input to convert to array to * @returns the array result */ static toArray<T>(arrayable: Arrayable<T>) { return Array.isArray(arrayable) ? arrayable : [arrayable]; } /** * Convert the given array to an array with unique elements(set). * * This method doesn't mutate the given array and returns a new array instead. * * @param array array to convert * @returns an array with only the unique elements */ static toUniqueArray<A extends unknown[]>(array: A) { return [...new Set(array)] as A; } /** * Split the given array at the given index. * * # Ranges * * - First array: `[0, index)` * - Second array: `[index, len)` * * # Example * * ```ts * const result = PgCommon.splitAtIndex(["a", "b", "c"], 1); * // [["a"], ["b", "c"]] * ``` * * @param array array to split * @param index split index * @returns the splitted 2 arrays */ static splitAtIndex<A extends unknown[]>(array: A, index: number) { return [array.slice(0, index), array.slice(index)] as [A, A]; } /** * Filter the array but also return the remaining array. * * @param array array to filter * @param predicate callback function for each of the array elements * @returns a tuple of `[filtered, remaining]` */ static filterWithRemaining<T>( array: T[], predicate: (value: T, index: number) => unknown ) { return array.reduce( (acc, cur, i) => { const filterIndex = predicate(cur, i) ? 0 : 1; acc[filterIndex].push(cur); return acc; }, [[], []] as [T[], T[]] ); } /** * Split the array to chunks based on the given length. * * @param array array to split to chunks * @param len chunk length * @returns the array chunks */ static chunks<T>(array: T[], len: number) { return array.reduce((acc, el, i) => { const chunkIndex = Math.floor(i / len); acc[chunkIndex] ??= []; acc[chunkIndex].push(el); return acc; }, [] as T[][]); } /** * Access the property value from `.` seperated input. * * @param obj object to get property from * @param property `.` seperated property input */ static getProperty(obj: any, property: string | string[]) { if (Array.isArray(property)) property = property.join("."); return property.split(".").reduce((acc, cur) => acc[cur], obj); } /** * Get the keys of an object with better types rather than `string[]`. * * @param obj object * @returns the object keys as an array */ static keys<T extends Record<string, unknown>>(obj: T) { return Object.keys(obj) as Array<keyof T>; } /** * Get the entries of an object with better types rather than `Array<[string, T]`. * * @param obj object * @returns the object entries as an array of [key, value] tuples */ static entries<T extends Record<string, unknown>>(obj: T) { return Object.entries(obj) as Array<[keyof T, ValueOf<T>]>; } /** * @returns the JS number(only use it if you are certain this won't overflow) */ static bigintToInt<T extends bigint | undefined>(bigint: T) { return ( bigint?.toString() ? +bigint.toString() : undefined ) as T extends bigint ? number : undefined; } /** * Convert seconds into human readable string format */ static secondsToTime(secs: number) { const d = Math.floor(secs / (60 * 60 * 24)), h = Math.floor((secs % (60 * 60 * 24)) / (60 * 60)), m = Math.floor((secs % (60 * 60)) / 60), s = Math.floor(secs % 60); if (d) return `${d}d`; if (h) return `${h}h`; if (m) return `${m}m`; if (s) return `${s}s`; return ""; } /** * @returns the current UNIX timestamp(sec) */ static getUnixTimstamp() { return Math.floor(Date.now() / 1000); } /** * Get the current origin URL with the given `path` appended. * * @param path URL path * @returns the URL based on the current origin */ static getPathUrl(path: string) { return PgCommon.joinPaths(window.location.origin, path); } /** * Encode the given content to data URL. * * @param content content to encode * @returns the encoded data URL */ static getDataUrl(content: string | object) { if (content instanceof Buffer) { return `data:text/plain;base64,${content.toString("base64")}`; } if (content instanceof Blob) { return URL.createObjectURL(content); } if (typeof content !== "string") { content = JSON.stringify(content); } return "data:text/json;charset=utf-8," + encodeURIComponent(content); } /** * Get the operating system of the user. * * @returns the operating system of the user */ static getOS() { const userAgent = navigator.userAgent.toLowerCase(); if (userAgent.includes("win")) return "Windows"; if (userAgent.includes("mac")) return "MacOS"; if (userAgent.includes("linux")) return "Linux"; } /** * Change `Ctrl` to `Cmd` if the OS is Mac. * * @param keybind keybind text * @returns the correct text based on OS */ static getKeybindTextOS(keybind: string) { if (this.getOS() === "MacOS") { keybind = keybind.replace("Ctrl", "Cmd"); } return keybind; } /** * Get the user's browser name. * * @returns the browser name */ static getBrowser() { if ((navigator as any).brave) return "Brave"; if (navigator.userAgent.includes("Chrome")) return "Chrome"; if (navigator.userAgent.includes("Firefox")) return "Firefox"; } /** * @returns true if the pressed key is `Ctrl` or `Cmd` */ static isKeyCtrlOrCmd(ev: KeyboardEvent) { return ev.ctrlKey || ev.metaKey; } /** * @returns whether the given string is parsable to an integer */ static isInt(str: string) { const intRegex = /^-?\d+$/; if (!intRegex.test(str)) return false; const int = parseInt(str, 10); return parseFloat(str) === int && !isNaN(int); } /** * @returns whether the given string is parsable to a float */ static isFloat(str: string) { const floatRegex = /^-?\d+(?:[.,]\d*?)?$/; if (!floatRegex.test(str)) return false; const float = parseFloat(str); if (isNaN(float)) return false; return true; } /** * @returns whether the given string is parsable to a hexadecimal */ static isHex(str: string) { const hexRegex = /(0x)?[\da-f]+/i; const result = hexRegex.exec(str); if (!result) return false; return result[0] === str; } /** * @returns whether the given string is parsable to a public key */ static isPk(str: string) { // Intentionally not using `web3.PublicKey` to not load `web3.js` at the // start of the app // Public key length is 43 or 44 if (!(str.length === 43 || str.length === 44)) return false; // Exclude 0, l, I, O const base58Regex = /[1-9a-km-zA-HJ-PQ-Z]+/; const result = base58Regex.exec(str); if (!result) return false; return result[0] === str; } /** * @returns whether the given string is parsable to a URL */ static isUrl(str: string) { try { new URL(str); return true; } catch { return false; } } /** * Get whether the given value is non-nullish i.e. **not** `null` or * `undefined`. * * @param value value to check * @returns whether the given value is non-nullish */ static isNonNullish<T>(value: T): value is NonNullable<T> { return value !== null && value !== undefined; } /** * Get whether the given value is an asynchronous function. * * @param value value to check * @returns whether the given value is an asynchronous function */ static isAsyncFunction(value: any): value is () => Promise<unknown> { return value?.constructor?.name === "AsyncFunction"; } /** * Generate a random integer in the range of [`min`, `max`]. * * @param min minimum(inclusive) * @param max maximum(inclusive) * @returns a random integer between the specified range */ static generateRandomInt(min: number, max: number) { return Math.floor(Math.random() * (max - min + 1) + min); } /** * Generate a random bigint in the range of [`min`, `max`]. * * @param min minimum(inclusive) * @param max maximum(inclusive) * @returns a random bigint between the specified range */ static generateRandomBigInt(min: bigint, max: bigint) { return ( new Uint8Array(new BigUint64Array([max - min]).buffer).reduce( (acc, cur, i) => { if (!cur) return acc; return ( acc + BigInt(PgCommon.generateRandomInt(0, cur)) * BigInt(2) ** BigInt(8 * i) ); }, 0n ) + min ); } /** * @returns camelCase converted version of the string input */ static toCamelCase(str: string) { return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match, index) => { if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces return index === 0 ? match.toLowerCase() : match.toUpperCase(); }); } /** * @returns camelCase converted version of the PascalCase string */ static toCamelFromPascal(str: string) { return str[0].toLowerCase() + str.slice(1); } /** * @returns camelCase converted version of the snake_case string */ static toCamelFromSnake(str: string) { return PgCommon.toCamelFromPascal(PgCommon.toPascalFromSnake(str)); } /** * Convert the given string to snake_case. * * @returns snake_case converted version of the string */ static toSnakeCase(str: string) { return PgCommon.toKebabFromTitle(str).replaceAll("-", "_"); } /** * @returns kebab-case converted version of the Title Case string */ static toKebabFromTitle(str: string) { return str .split(" ") .map((w) => w.toLowerCase()) .join("-"); } /** * @returns kebab-case converted version of the camelCase string */ static toKebabFromCamel(str: string) { const kebab = []; for (const letter of str) { if (letter === letter.toUpperCase()) { kebab.push("-" + letter.toLowerCase()); } else { kebab.push(letter); } } return kebab.reduce((acc, letter) => acc + letter); } /** * @returns kebab-case converted version of the snake_case string */ static toKebabFromSnake(str: string) { return str.replaceAll("_", "-"); } /** * @returns Title Case converted version of the kebab-case string */ static toTitleFromKebab(str: string) { return ( str[0].toUpperCase() + str.slice(1).replace(/-\w/, (match) => " " + match[1].toUpperCase()) ); } /** * @returns Title Case converted version of the camelCase string */ static toTitleFromCamel(str: string) { return PgCommon.toTitleFromKebab(PgCommon.toKebabFromCamel(str)); } /** * @returns Title Case converted version of the snake_case string */ static toTitleFromSnake(str: string) { return PgCommon.toTitleFromKebab(PgCommon.toKebabFromSnake(str)); } /** * @returns PascalCase converted version of the Title Case string */ static toPascalFromTitle(str: string) { return str.replaceAll(" ", ""); } /** * @returns PascalCase converted version of the kebab-case string */ static toPascalFromKebab(str: string) { return PgCommon.capitalize(str).replace(/-\w/g, (match) => { return match[1].toUpperCase(); }); } /** * @returns PascalCase converted version of the snake_case string */ static toPascalFromSnake(str: string) { return PgCommon.toPascalFromKebab(PgCommon.toKebabFromSnake(str)); } /** * @returns the string with its first letter uppercased */ static capitalize(str: string) { return str[0].toUpperCase() + str.slice(1); } /** * @returns automatic airdrop amount */ static getAirdropAmount(endpoint: string) { switch (endpoint) { case Endpoint.PLAYNET: return 1000; case Endpoint.LOCALHOST: return 100; case Endpoint.DEVNET: return 5; case Endpoint.TESTNET: return 1; default: return null; } } /** * Get send and receive event names * * @param eventName name of the custom event * @returns names of the send and receive */ static getSendAndReceiveEventNames(eventName: string) { const send = eventName + "send"; const receive = eventName + "receive"; return { send, receive }; } /** * Get static get and run event names * * @param eventName name of the custom event * @returns names of the get and run */ static getStaticEventNames(eventName: string) { const get = eventName + "get"; const run = eventName + "run"; return { get, run }; } /** * Get static get and set event names * * @param eventName name of the custom event * @returns names of the get and set */ static getStaticStateEventNames(eventName: string) { const get = eventName + "get"; const set = eventName + "set"; return { get, set }; } /** * Dispatch a custom DOM event * * @param name custom event name * @param detail data to send with the custom event */ static createAndDispatchCustomEvent<T>(name: string, detail?: T) { const customEvent = new CustomEvent(name, { detail }); document.dispatchEvent(customEvent); } /** * Dispatch a custom event and wait for receiver to resolve. * * @param eventName name of the custom event * @param data data to send * @returns the resolved data */ static async sendAndReceiveCustomEvent<R, D = unknown>( eventName: string, data?: D ): Promise<R> { const eventNames = this.getSendAndReceiveEventNames(eventName); // Send data this.createAndDispatchCustomEvent(eventNames.send, data); // Wait for data return new Promise((res, rej) => { const handleReceive = ( ev: UIEvent & { detail: { data: R; error?: string } } ) => { document.removeEventListener( eventNames.receive, handleReceive as EventListener ); if (ev.detail.error) { rej({ message: ev.detail.error }); } else { res(ev.detail.data); } }; document.addEventListener( eventNames.receive, handleReceive as EventListener ); }); } /** * Handle change event. * * If `params.initialRun` is specified, the callback will run immediately with * the given `params.initialRun.value`. Any subsequent runs are only possible * through the custom event listener. * * @returns a dispose function to clear the event */ static onDidChange<T>(params: { cb: (value: T) => any; eventName: OrString<EventName>; // TODO: make it run by default initialRun?: { value: T }; }): Disposable { type Event = UIEvent & { detail: T }; const handle = (ev: Event) => { params.cb(ev.detail); }; if (params.initialRun) handle({ detail: params.initialRun.value } as Event); document.addEventListener(params.eventName, handle as EventListener); return { dispose: () => { document.removeEventListener(params.eventName, handle as EventListener); }, }; } /** * Batch changes together. * * @param cb callback to run * @param onChanges onChange methods * @returns a dispose function to clear all events */ static batchChanges( cb: (value?: unknown) => void, onChanges: Array<(value: any) => Disposable>, opts?: { delay?: number } ): Disposable { // Intentionally initializing outside of the closure to share `sharedTimeout` const debounceOptions = { delay: opts?.delay ?? 0, sharedTimeout: {} }; const disposables = onChanges.map((onChange) => { return onChange(PgCommon.debounce(cb, debounceOptions)); }); return { dispose: () => disposables.forEach((disposable) => disposable.dispose()), }; } /** * Execute the given callback initially and on change. * * This is useful when an on change method doesn't fire an initial change event * but the use case requires to run the callback at start. * * @param onChange on change method * @param cb callback to run initially and on change * @param args callback arguments * @returns a dispose function to clear all events */ static async executeInitial<A extends unknown[]>( onChange: (cb: (...args: A) => SyncOrAsync<void>) => Disposable, cb: (...args: A) => SyncOrAsync<void>, ...args: A ) { await cb(...args); return onChange(cb); } /** * Runs `setInterval` callback function only when the document has focus * * @param cb callback to run on interval * @param ms interval time amount in miliseconds * @returns a cleanup timer that should be called with `clearInterval` */ static setIntervalOnFocus(cb: () => void, ms?: number) { return setInterval(() => { if (document.hasFocus()) cb(); }, ms); } /** * Import file(s) from the user's file system * * @param onChange callback function to run when file input has changed * @param opts options * - `accept`: file extensions to accept * - `dir`: whether to accept directories */ static async import<T>( onChange: (ev: ChangeEvent<HTMLInputElement>) => Promise<T>, opts?: { accept?: string; dir?: boolean } ): Promise<T> { return new Promise((res, rej) => { const el = document.createElement("input"); el.type = "file"; if (opts?.accept) el.accept = opts.accept; const dirProps = opts?.dir ? { webkitdirectory: "", mozdirectory: "", directory: "", multiple: true, } : {}; for (const key in dirProps) { // @ts-ignore el[key] = dirProps[key]; } el.onchange = async (ev) => { // @ts-ignore const result = await onChange(ev); res(result); }; el.oncancel = () => { rej({ message: "User cancelled the request" }); }; el.click(); }); } /** * Export the given content as a file. * * @param name name of the exported file * @param content content of the exported file */ static export(name: string, content: string | object) { const el = document.createElement("a"); el.download = name; el.href = PgCommon.getDataUrl(content); el.click(); } /** * Change the given input's value and dispatch `change` event correctly. * * @param inputEl input element * @param value input value to set */ static changeInputValue(inputEl: HTMLInputElement, value: string) { // `input.value = value` does not trigger `Input` component's `onChange` Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype, "value" )?.set?.call(inputEl, value); // `bubbles: true` is required in order to trigger `onChange` inputEl.dispatchEvent(new Event("change", { bubbles: true })); } /** * Make a noun plural * * @param noun name of the noun * @param length item length that will decide whether to make the noun plural * @param plural plural version of the name for irregular suffixes * @returns plural version of the noun */ static makePlural(noun: string, length: number, plural?: string) { if (length > 1) return plural ?? noun + "s"; return noun; } /** * Convert objects into pretty JSON strings * * @param obj json object * @returns prettified string output */ static prettyJSON(obj: object) { return JSON.stringify(obj, null, 2); } /** * Get human readable date time from unix timestamp * * @param unixTs unix timestamp in seconds * @param opts date format options * @returns formatted date string */ static getFormattedDateFromUnixTimestamp( unixTs: number, opts?: { locale: string; } & Pick<Intl.DateTimeFormatOptions, "dateStyle" | "timeStyle" | "timeZone"> ) { return new Intl.DateTimeFormat(opts?.locale ?? "en-US", { dateStyle: opts?.dateStyle ?? "full", timeStyle: opts?.timeStyle ?? "long", timeZone: opts?.timeZone ?? "UTC", }).format(unixTs * 1e3); } /** * Append '/' to the end of the string * * @param str string to append slash to * @returns the slash appended string */ static appendSlash(str: string) { if (!str) return ""; return str + (str.endsWith("/") ? "" : "/"); } /** * Get the string without '/' prefix * * @param str string input * @returns the string without slash prefix */ static withoutPreSlash(str: string) { return str[0] === "/" ? str.substring(1) : str; } /** * Join the paths without caring about incorrect '/' inside paths. * * @param paths paths to join * @returns the joined path */ static joinPaths(...paths: string[]) { return paths.reduce( (acc, cur) => this.appendSlash(acc) + this.withoutPreSlash(cur) ); } /** * Compare paths to each other. * * @param pathOne first path * @param pathTwo second path * @returns whether the paths are equal */ static isPathsEqual(pathOne: string, pathTwo: string) { return PgCommon.appendSlash(pathOne) === PgCommon.appendSlash(pathTwo); } /** * Get all of the matches of the `given` value from the `content`. * * @param content content to match all from * @param value value to match * @returns the match result */ static matchAll(content: string, value: string | RegExp) { return [...content.matchAll(new RegExp(value, "g"))]; } /** * Adds space before the string, mainly used for terminal output * * @param str string to prepend spaces to * @param opts - * - addSpace: add space before or after the string * - repeat: repeat the string `repeat.amount` times * @returns the space prepended string */ static string( str: string, opts: { addSpace?: { amount: number; type?: "total" | "additional"; position?: "left" | "right"; }; repeat?: { amount: number }; } ) { if (opts.addSpace) { const space = this._repeatPattern( " ", opts.addSpace.amount - (opts.addSpace.type === "additional" ? 0 : str.length) ); return opts.addSpace.position === "right" ? str + space : space + str; } if (opts.repeat) { return this._repeatPattern(str, opts.repeat.amount); } } /** * Append "..." to the given `str` after `maxLength` bytes. * * @param str string to check the max length * @param maxLength maximum allowed byte length * @returns the original string or the part of the string until the `maxLength` */ static withMaxLength(str: string, maxLength: number) { const FILLER = "..."; if (str.length > maxLength) { return str.slice(0, maxLength - FILLER.length) + FILLER; } return str; } /** * Shorten the given string by only showing the first and last `chars` character. * * @param str string to shorten * @param amount amount of chars to show from beginning and end * @returns first and last (default: 3) chars of the given string and '...' in between */ static shorten(str: string, amount: number = 3) { return str.slice(0, amount) + "..." + str.slice(-amount); } /** * Intentionally not using web3.js.LAMPORTS_PER_SOL to not increase main * bundle size since `PgCommon` is getting loaded at the start of the app. */ private static _LAMPORTS_PER_SOL = 1000000000; /** * Repeat a `pattern` `amount` times * * @param pattern pattern to repeat * @param amount amount of times to repeat * @returns the output */ private static _repeatPattern(pattern: string, amount: number) { return new Array(amount >= 0 ? amount : 0) .fill(null) .reduce((acc) => acc + pattern, ""); } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/view.ts
import type { FC, ReactNode } from "react"; import type { ToastOptions } from "react-toastify"; import { PgCommon } from "./common"; import { EventName } from "../../constants"; import type { SetState, SetElementAsync, Disposable, CallableJSX, RequiredKey, } from "./types"; /** Sidebar page param */ export type SidebarPageParam<N extends string> = { /** Name of the page */ name: N; /** `src` of the image */ icon: string; /** Title of the page, defaults to `name` */ title?: string; /** Keybind for the page */ keybind?: string; /** Route to navigate to */ route?: RoutePath; /** Handle the page logic */ handle?: () => Disposable | void; /** Lazy loader for the element */ importElement?: () => Promise<{ default: CallableJSX }>; /** Loading element to until the element is ready to show */ LoadingElement?: CallableJSX; }; /** Created sidebar page */ export type SidebarPage<N extends string = string> = RequiredKey< SidebarPageParam<N>, "title" | "importElement" >; export class PgView { /** All sidebar pages */ static sidebar: SidebarPage<SidebarPageName>[]; /** * Set the current sidebar page. * * @param page sidebar page to set */ static getSidebarPage(name: SidebarPageName) { return this.sidebar.find((s) => s.name === name)!; } /** * Set the current sidebar page. * * @param page sidebar page to set */ static setSidebarPage(page: SetState<SidebarPageName> = "Explorer") { PgCommon.createAndDispatchCustomEvent( EventName.VIEW_SIDEBAR_PAGE_NAME_SET, page ); } /** * Set sidebar right component's loading state. * * **NOTE:** The boolean values are used to either increment or decrement the * ongoing process count. Setting the `loading` to `false` only decrements * the process count and the loading state is only disabled if there is no * other ongoing process. * * @param loading set loading state */ static setSidebarLoading(loading: SetState<boolean>) { PgCommon.createAndDispatchCustomEvent( EventName.VIEW_SIDEBAR_LOADING_SET, loading ); } /** * Set the primary main view (next to the sidebar and above the terminal). * * @param SetEl element to set the main view to */ static async setMainPrimary(SetEl: SetElementAsync) { await PgCommon.tryUntilSuccess(async () => { const eventNames = PgCommon.getStaticStateEventNames( EventName.VIEW_MAIN_PRIMARY_STATIC ); const result = await PgCommon.timeout( PgCommon.sendAndReceiveCustomEvent(eventNames.get), 100 ); if (result === undefined) throw new Error(); PgCommon.createAndDispatchCustomEvent(eventNames.set, SetEl); }, 1000); } /** * Set the current secondary main view page. * * @param page secondary main view page to set */ static setMainSecondaryPage( page: SetState<MainSecondaryPageName> = "Terminal" ) { PgCommon.createAndDispatchCustomEvent( EventName.VIEW_MAIN_SECONDARY_PAGE_SET, page ); } /** * Set the secondary main view's height. * * @param height height to set in px */ static setMainSecondaryHeight(height: SetState<number>) { PgCommon.createAndDispatchCustomEvent( EventName.VIEW_MAIN_SECONDARY_HEIGHT_SET, height ); } static focusMainSecondary() { PgCommon.createAndDispatchCustomEvent(EventName.VIEW_MAIN_SECONDARY_FOCUS); } /** * Set the current modal and wait until close. * * @param Component component to set as the modal * @param props component props * @returns the data from `close` method of the modal */ static async setModal<R, P extends Record<string, any> = {}>( Component: ReactNode | FC<P>, props?: P ): Promise<R | null> { return await PgCommon.sendAndReceiveCustomEvent(EventName.MODAL_SET, { Component, props, }); } /** * Close the current modal. * * @param data data to be resolved from the modal */ static closeModal(data?: any) { // `data` will be a `ClickEvent` if the modal has been closed with the // default Cancel button if (data?.target) data = null; PgCommon.createAndDispatchCustomEvent( PgCommon.getSendAndReceiveEventNames(EventName.MODAL_SET).receive, { data } ); PgView.setModal(null); } /** * Show a notification toast. * * @param Component component to show * @param props component props and toast options */ static setToast<P>( Component: ReactNode | FC<P>, props?: { componentProps?: P; options?: ToastOptions } ) { return PgCommon.createAndDispatchCustomEvent(EventName.TOAST_SET, { Component, props, }); } /** * Close either the given toast or, all toasts if `id` is not given. * * @param id toast id */ static closeToast(id?: number) { return PgCommon.createAndDispatchCustomEvent(EventName.TOAST_CLOSE, id); } /** * Set the new item portal container. * * New item input will be shown if an element is given. * * @param Element element to set the portal container to */ static setNewItemPortal(Element: Element | null) { return PgCommon.createAndDispatchCustomEvent( EventName.VIEW_NEW_ITEM_PORTAL_SET, Element ); } /** * Runs after changing sidebar page. * * @param cb callback function to run after changing sidebar page * @returns a dispose function to clear the event */ static onDidChangeSidebarPage(cb: (page: SidebarPage) => unknown) { return PgCommon.onDidChange({ cb, eventName: EventName.VIEW_ON_DID_CHANGE_SIDEBAR_PAGE, }); } /** * Runs after changing the secondary main view page. * * @param cb callback function to run after changing the secondary main view page * @returns a dispose function to clear the event */ static onDidChangeMainSecondaryPage( cb: (page: MainSecondaryPageName) => unknown ) { return PgCommon.onDidChange({ cb, eventName: EventName.VIEW_ON_DID_CHANGE_MAIN_SECONDARY_PAGE, }); } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/web3.ts
export * as PgWeb3 from "@solana/web3.js";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/connection.ts
import { PgCommon } from "./common"; import { createDerivable, declareDerivable, derivable } from "./decorators"; import { OverridableConnection, PgPlaynet } from "./playnet"; import { PgSettings } from "./settings"; import { PgWeb3 } from "./web3"; /** Optional `connection` prop */ export interface ConnectionOption { connection?: typeof PgConnection["current"]; } /** Solana public clusters or "localnet" */ export type Cluster = "localnet" | PgWeb3.Cluster; const derive = () => ({ /** Globally sycned connection instance */ current: createDerivable({ // It's important that this method returns immediately because connection // instance is used throughout the app. For this reason, the connection for // Playnet will be returned without awaiting the initialization. After the // initialization, `PgPlaynet.onDidInit` will be triggered and this method // will run again to return the overridden connection instance. derive: () => { // Check whether the endpoint is Playnet if (PgPlaynet.isUrlPlaynet(PgSettings.connection.endpoint)) { // Return the connection instance if it has been overridden if (PgPlaynet.connection?.overridden) { return PgPlaynet.connection; } // Initialize Playnet PgPlaynet.init(); } else { // Destroy Playnet PgPlaynet.destroy(); } return _PgConnection.create(); }, onChange: [ PgSettings.onDidChangeConnectionEndpoint, PgSettings.onDidChangeConnectionCommitment, PgPlaynet.onDidInit, ], }), /** Whether there is a successful connection */ isConnected: createDerivable({ derive: _PgConnection.getIsConnected, onChange: (cb) => { // Keep track of `isConnected` and only run the `cb` when the value // actually changes. This is because the decorators such as `derivable` // and `updatable` trigger a change event each time the value is set // independent of whether the value has changed unlike React which only // re-renders when the memory location of the value changes. // // TODO: Allow specifying whether the value should be compared with the // previous value and trigger the change event **only if** there is a // difference in comparison. let isConnected = false; // Refresh every 60 seconds on success const successId = setInterval(async () => { if (!isConnected) return; isConnected = await PgConnection.getIsConnected(); if (!isConnected) cb(); }, 60000); // Refresh every 5 seconds on error const errorId = setInterval(async () => { if (isConnected) return; isConnected = await PgConnection.getIsConnected(); if (isConnected) cb(); }, 5000); return { dispose: () => { clearInterval(successId); clearInterval(errorId); }, }; }, }), /** Current cluster name based on the current endpoint */ cluster: createDerivable({ derive: _PgConnection.getCluster, onChange: PgSettings.onDidChangeConnectionEndpoint, }), /** Whether the cluster is down. `null` indicates potential connection error. */ isClusterDown: createDerivable({ derive: _PgConnection.getIsClusterDown, onChange: "cluster", }), }); @derivable(derive) class _PgConnection { /** * Get the cluster name from the given `endpoint`. * * @param endpoint RPC endpoint * @returns the cluster name */ static async getCluster( endpoint: string = PgConnection.current.rpcEndpoint ): Promise<Cluster> { // Local if (endpoint.includes("localhost") || endpoint.includes("127.0.0.1")) { return "localnet"; } // Public switch (endpoint) { case PgWeb3.clusterApiUrl("devnet"): return "devnet"; case PgWeb3.clusterApiUrl("testnet"): return "testnet"; case PgWeb3.clusterApiUrl("mainnet-beta"): return "mainnet-beta"; } // Decide custom endpoints from the genesis hash of the cluster const genesisHash = await PgConnection.create({ endpoint, }).getGenesisHash(); switch (genesisHash) { case "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG": return "devnet"; case "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY": return "testnet"; case "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d": return "mainnet-beta"; default: throw new Error( `Genesis hash ${genesisHash} did not match any cluster` ); } } /** * Create a connection with the given options or defaults from settings. * * @param opts connection options * @returns a new `Connection` instance */ static create(opts?: { endpoint?: string } & PgWeb3.ConnectionConfig) { return new PgWeb3.Connection( opts?.endpoint ?? PgSettings.connection.endpoint, opts ?? PgSettings.connection.commitment ); } /** * Get whether the connection is ready to be used. * * If the endpoint is `Endpoint.PLAYNET` this will return `false` until the * connection gets overridden. This helps avoid sending unnecessary RPC requests * at start before the `connection` and `fetch` is overridden. * * This will always return `true` if the endpoint is not `Endpoint.PLAYNET`. * * @param conn overridable web3.js `Connection` * @returns whether the connection is ready to be used */ static isReady(conn: OverridableConnection) { if (PgPlaynet.isUrlPlaynet(conn.rpcEndpoint)) { return conn.overridden; } return true; } /** * Get whether there is a successful connection to the current endpoint. * * @returns whether there is a successful connection */ static async getIsConnected() { try { await PgConnection.current.getSlot(); return true; } catch { return false; } } /** * Get whether the current cluster is down by comparing the latest slot * numbers between a certain time period. * * @returns whether the current cluster is down */ static async getIsClusterDown() { let prevSlot: number; try { prevSlot = await PgConnection.current.getSlot(); } catch { return null; } // Sleep to give time for the RPC to advance slots await PgCommon.sleep(1000); let nextSlot: number; try { nextSlot = await PgConnection.current.getSlot(); } catch { return null; } return prevSlot === nextSlot; } } export const PgConnection = declareDerivable(_PgConnection, derive);
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/types.ts
/** Get value of the given object */ export type ValueOf<T extends object> = T[keyof T]; /** Methods of the given object */ export type Methods<T> = { [U in keyof T]?: T[U] extends (...args: any[]) => any ? Parameters<T[U]> : []; }; /** Convert the return types of the methods of the object to `Promise` */ export type AsyncMethods<T> = { [K in keyof T]: T[K] extends (...args: any[]) => infer R ? (...args: Parameters<T[K]>) => Promise<Awaited<R>> : never; }; /** Return type of the methods of an object */ export type ClassReturnType<T, U> = U extends keyof T ? T[U] extends (...args: any[]) => any ? Awaited<ReturnType<T[U]>> : T[U] : never; /** Create tuples with the same element type */ export type Tuple< T, L extends number, R extends unknown[] = [] > = R["length"] extends L ? R : Tuple<T, L, [T, ...R]>; /** Tuple double string */ export type TupleString = Tuple<string, 2>; /** Map union to tuple */ export type UnionToTuple<U> = MergeUnion< U extends never ? never : (union: U) => U > extends (_: never) => infer R ? [...UnionToTuple<Exclude<U, R>>, R] : []; /** Merge union */ export type MergeUnion<U> = ( U extends never ? never : (union: U) => never ) extends (ret: infer R) => never ? R : never; export type Disposable = { /** Clear registered events */ dispose: () => void; }; /** Nullable JSX Element */ export type NullableJSX = JSX.Element | null; /** <Callable /> JSX Element */ export type CallableJSX = () => NullableJSX; /** Set state type */ export type SetState<T> = T | ((cur: T) => T); /** Set element asynchronously */ export type SetElementAsync = SetState<SyncOrAsync<NullableJSX | CallableJSX>>; /** Make the given keys required */ export type RequiredKey<T, R extends keyof T> = Omit<T, R> & { [K in R]-?: NonNullable<T[K]>; }; /** Make properties required for depth 1 and 2 */ export type NestedRequired<T> = { [K in keyof T]-?: Required<T[K]>; }; /** Make properties required for depth 2 */ export type ChildRequired< T, K extends keyof T = keyof T, K2 extends keyof NonNullable<T[K]> = NonNullable<keyof T[K]> > = { [P in K]: { [P2 in K2]-?: NonNullable<T[K]>[K2]; }; }; /** Makes every prop required until `U` */ export type RequiredUntil<T, U> = T extends U ? { [K in keyof T]: T[K] } : { [K in keyof T]-?: RequiredUntil<T[K], U>; }; /** Make all properties required recursively */ export type AllRequired<T> = { [K in keyof T]-?: AllRequired<T[K]>; }; /** Make all properties readonly recursively */ export type AllReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? AllReadonly<T[K]> : T[K]; }; /** Make all properties partial recursively */ export type AllPartial<T> = { [K in keyof T]?: T[K] extends object ? AllPartial<T[K]> : T[K]; }; /** Get object with only optional key-values */ export type OnlyOptional<T> = { [K in OptionalKeys<T>]?: OnlyOptional<NonNullable<T[K]>>; }; /** Get optional property keys */ type OptionalKeys<T> = Exclude< { [K in keyof T]: T extends Record<K, T[K]> ? never : K; }[keyof T], undefined >; /** Noop function type */ export type Fn = () => void; /** Normal or `Promise` version of the type */ export type SyncOrAsync<T = unknown> = T | Promise<T>; /** A `Promise` or a callback that returns a `Promise` */ export type Promisable<T> = Getable<SyncOrAsync<T>>; /** Make every property (... | null) */ export type Nullable<T> = { [K in keyof T]: T[K] | null; }; /** Single type, or array of the same type */ export type Arrayable<T> = T | T[]; /** Property or a function to get the property */ export type Getable<T> = T | (() => T); /** Given type `T` or `string` with intellisense for the initial type */ export type OrString<T> = T | (string & {}); /** Add optional `React.DependencyList` for parameters */ export type WithOptionalDependencyList<T extends unknown[]> = | T | [...T, React.DependencyList];
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/framework.ts
import { PgCommon } from "./common"; import { PgExplorer, TupleFiles } from "./explorer"; import type { RequiredKey, SyncOrAsync } from "./types"; /** Custom framework parameter */ export type FrameworkImpl<N extends string> = { /** Framework name */ name: N; /** Framework program language */ language: LanguageName; /** Image icon src */ icon: string; /** Example GitHub project */ githubExample: { /** Project name */ name: string; /** Project GitHub URL */ url: string; }; /** Default file to open after loading the default framework files */ defaultOpenFile?: string; /** Whether to make the image circular */ circleImage?: boolean; /** * Get whether the given files have this framework's layout. * * @param files files with either playground's layout or framework's layout * @returns whether the given files belong to this framework */ getIsCurrent: (files: TupleFiles) => SyncOrAsync<boolean>; /** Lazy load default framework files, defaults to `./files` */ importFiles?: () => Promise<{ /** Default framework files to create on a new project */ files: TupleFiles; }>; /** Lazy load the **from** playground conversion module, defaults to `./from` */ importFromPlayground?: () => Promise<{ /** * Convert the given playground layout files to the framework's original * layout files. * * @param files playground layout files * @returns the frameworks' original layout files */ convertFromPlayground: (files: TupleFiles) => SyncOrAsync<TupleFiles>; /** Markdown text to show after conversion */ readme: string; }>; /** Lazy load the **to** playground conversion module, defaults to `./to` */ importToPlayground?: () => Promise<{ /** * Convert the given framework layout files to playground layout files. * * @param files framework layout files * @returns the playground layout files */ convertToPlayground: (files: TupleFiles) => SyncOrAsync<TupleFiles>; }>; }; /** Created framework */ export type Framework<N extends string = string> = RequiredKey< FrameworkImpl<N>, "getIsCurrent" | "importFiles" | "importFromPlayground" | "importToPlayground" >; export class PgFramework { /** All frameworks */ static all: Framework<FrameworkName>[]; /** * Get the framework from its name. * * @param name framework name * @returns the framework */ static get(name: FrameworkName) { return this.all.find((f) => f.name === name)!; } /** * Get the framework from the given files. * * @param files files to check, defaults to current project files * @returns the framework */ static async getFromFiles(files: TupleFiles = PgExplorer.getAllFiles()) { for (const framework of this.all) { const isCurrent = await framework.getIsCurrent(files); if (isCurrent) return framework; } } /** * Convert files with the framework layout to the playground layout. * * @param files framework files * @returns the playground layout converted files */ static async convertToPlaygroundLayout(files: TupleFiles) { const framework = await this.getFromFiles(files); if (!framework) throw new Error("Could not identify framework"); const { convertToPlayground } = await framework.importToPlayground(); const convertedFiles = await convertToPlayground(files); if (!convertedFiles.length) throw new Error("Could not convert files"); return convertedFiles; } /** * Export the current workspace as a zip file based on the current framework * layout. * * @param opts options * - `convert`: whether to convert the playground layout to the framework's layout * @returns README Markdown text if `opts.convert` is true */ static async exportWorkspace(opts?: { convert?: boolean }) { let files: TupleFiles = []; const recursivelyGetItems = async (path: string) => { const itemNames = await PgExplorer.fs.readDir(path); const subItemPaths = itemNames .filter((itemName) => !itemName.startsWith(".")) .map((itemName) => PgCommon.appendSlash(path) + itemName); for (const subItemPath of subItemPaths) { const metadata = await PgExplorer.fs.getMetadata(subItemPath); if (metadata.isFile()) { const relativePath = PgExplorer.getRelativePath(subItemPath); const content = await PgExplorer.fs.readToString(subItemPath); files.push([relativePath, content]); } else { await recursivelyGetItems(subItemPath); } } }; await recursivelyGetItems(PgExplorer.currentWorkspacePath); // Convert from playground layout to framework layout let readme: string | undefined; if (opts?.convert) { const framework = await this.getFromFiles(files); if (!framework) throw new Error("Could not identify framework"); const frameworkFrom = await framework.importFromPlayground(); readme = frameworkFrom.readme; files = await frameworkFrom.convertFromPlayground(files); } // Compress Zip const { default: JSZip } = await import("jszip"); const zip = new JSZip(); files.forEach(([path, content]) => { const isFile = PgExplorer.getItemTypeFromName(path).file; if (isFile) zip.file(path, content); else zip.folder(path); }); const blob = await zip.generateAsync({ type: "blob" }); PgCommon.export(PgExplorer.currentWorkspaceName + ".zip", blob); return { readme }; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/global.ts
import { declareUpdatable, updatable } from "./decorators"; interface GlobalState { buildLoading: boolean; deployState: "ready" | "loading" | "paused" | "cancelled"; } const defaultState: GlobalState = { buildLoading: false, deployState: "ready", }; /** Nothing to persist. */ const storage = { read() { return defaultState; }, write(state: GlobalState) {}, }; @updatable({ defaultState, storage }) class _PgGlobal {} export const PgGlobal = declareUpdatable(_PgGlobal, { defaultState });
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/index.ts
export * from "./block-explorer"; export * from "./bytes"; export * from "./client/"; export * from "./common"; export * from "./command"; export * from "./connection"; export * from "./editor"; export * from "./explorer/"; export * from "./framework"; export * from "./github"; export * from "./global"; export * from "./keybind"; export * from "./language"; export * from "./package"; export * from "./playnet/"; export * from "./program-info"; export * from "./router"; export * from "./server"; export * from "./settings"; export * from "./share"; export * from "./terminal/"; export * from "./theme/"; export * from "./tutorial/"; export * from "./tx/"; export * from "./types"; export * from "./view"; export * from "./wallet/"; export * from "./web3";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/command.ts
import { PgCommon } from "./common"; import { PgTerminal } from "./terminal"; import type { Arrayable, Disposable, Getable, SyncOrAsync, ValueOf, } from "./types"; /** Terminal command implementation */ export type CommandImpl< N extends string, A extends Arg[], O extends Option[], S, R > = { /** Name of the command that will be used in terminal */ name: N; /** Description that will be seen in the `help` command */ description: string; /* Only process the command if the condition passes */ preCheck?: Arrayable<() => SyncOrAsync<void>>; } & (WithSubcommands<S> | WithRun<A, O, R>); type WithSubcommands<S> = { /** Command arguments */ args?: never; /** Command options */ options?: never; /** Function to run when the command is called */ run?: never; /** Subcommands */ subcommands?: S; }; type WithRun<A, O, R> = { /** Command arguments */ args?: A; /** Command options */ options?: O; /** Function to run when the command is called */ run: (input: ParsedInput<A, O>) => R; /** Subcommands */ subcommands?: never; }; type ParsedInput<A, O> = { /** Raw input */ raw: string; /** Parsed arguments */ args: ParsedArgs<A>; /** Parsed options */ options: ParsedOptions<O>; }; /** Recursively map argument types */ type ParsedArgs<A> = A extends [infer Head, ...infer Tail] ? Head extends Arg<infer N, infer V> ? (Head["optional"] extends true ? { [K in N]?: Head["multiple"] extends true ? V[] : V } : { [K in N]: Head["multiple"] extends true ? V[] : V }) & ParsedArgs<Tail> : never : {}; /** Recursively map option types */ type ParsedOptions<O> = O extends [infer Head, ...infer Tail] ? Head extends Option<infer N, infer V> ? (Head["takeValue"] extends true ? { [K in N]?: V } : Head["values"] extends Getable<V[]> ? { [K in N]?: V } : { [K in N]?: boolean }) & ParsedOptions<Tail> : never : {}; /** Command argument */ export type Arg<N extends string = string, V extends string = string> = { /** Name of the argument */ name: N; /** Description of the argument */ description?: string; /** Whether the argument can be omitted */ optional?: boolean; /** Whether to take multiple values */ multiple?: boolean; /** Accepted values */ values?: Getable<V[]>; }; /** Command option */ export type Option<N extends string = string, V extends string = string> = { /** Name of the option */ name: N; /** Description of the option */ description?: string; /** Short form of the option passed with a single dash (`-`) */ short?: boolean | string; /** Whether to take value for the option */ takeValue?: boolean; /** Accepted values */ values?: Getable<V[]>; }; /** Terminal command inferred implementation */ export type CommandInferredImpl< N extends string, A extends Arg[], O extends Option[], S, R > = Omit<CommandImpl<N, A, O, S, R>, "subcommands"> & { subcommands?: S extends CommandInferredImpl< infer N2, infer A2, infer O2, infer S2, infer R2 > ? CommandInferredImpl<N2, A2, O2, S2, R2> : any[]; }; /** Command type for external usage */ type Command< N extends string, A extends Arg[], O extends Option[], S, R > = Pick<CommandInferredImpl<N, A, O, S, R>, "name"> & { /** Process the command. */ run(...args: string[]): Promise<Awaited<R>>; /** * @param cb callback function to run when the command starts running * @returns a dispose function to clear the event */ onDidRunStart(cb: (input: string | null) => void): Disposable; /** * @param cb callback function to run when the command finishes running * @returns a dispose function to clear the event */ onDidRunFinish(cb: (result: Awaited<R>) => void): Disposable; }; /** Name of all the available commands (only code) */ type CommandCodeName = keyof InternalCommands; /** Ready to be used commands */ type Commands = { [N in keyof InternalCommands]: InternalCommands[N] extends CommandInferredImpl< infer N, infer A, infer O, infer S, infer R > ? Command<N, A, O, S, R> : never; }; /** All commands */ export const PgCommand: Commands = new Proxy( {}, { get: ( target: any, cmdCodeName: CommandCodeName ): Command<string, Arg[], Option[], unknown, unknown> => { if (!target[cmdCodeName]) { const cmdUiName = PgCommandManager.all[cmdCodeName].name; target[cmdCodeName] = { name: cmdUiName, run: (...args: string[]) => { return PgCommandManager.execute([cmdUiName, ...args]); }, onDidRunStart: (cb: (input: string | null) => void) => { return PgCommon.onDidChange({ cb, eventName: getEventName(cmdCodeName, "start"), }); }, onDidRunFinish: (cb: (result: unknown) => void) => { return PgCommon.onDidChange({ cb, eventName: getEventName(cmdCodeName, "finish"), }); }, }; } return target[cmdCodeName]; }, } ); /** * Terminal command manager. * * This is intended for internal usage. Running commands should be done with * `PgCommand` instead. */ export class PgCommandManager { /** All internal commands */ static all: InternalCommands; /** * Get the available command names. * * @returns the command names */ static getNames() { return Object.values(this.all).map((cmd) => cmd.name); } /** * Get the available command completions. * * @returns the command completions */ static getCompletions() { type CompletionArg = { values?: Getable<string[]>; multiple?: boolean }; type CompletionOption = { takeValue?: boolean; other?: string }; interface Completions { [key: string]: Completions | CompletionArg | CompletionOption; } const recursivelyGetCompletions = ( commands: ValueOf<InternalCommands>[], completions: Completions = {} ) => { for (const cmd of commands) { completions[cmd.name] = {}; const completion = completions[cmd.name] as Completions; if (cmd.subcommands) { recursivelyGetCompletions(cmd.subcommands, completion); } if (cmd.args) { for (const [i, arg] of Object.entries(cmd.args)) { completion[i] = { values: arg.values, multiple: arg.multiple }; } } if (cmd.options) { for (const opt of cmd.options) { const long = `--${opt.name}`; completion[long] = { takeValue: opt.takeValue, values: opt.values }; if (opt.short) { const short = `-${opt.short}`; completion[long] = { ...completion[long], other: short }; completion[short] = { ...completion[long], other: long, }; } } } } return completions; }; return recursivelyGetCompletions(Object.values(PgCommandManager.all)); } /** * Execute from the given tokens. * * All command processing logic happens in this method. * * @param tokens parsed input tokens * @returns the return value of the command */ static async execute(tokens: string[]) { return await PgTerminal.process(async () => { const inputCmdName = tokens.at(0); if (!inputCmdName) return; const topCmd = Object.values(PgCommandManager.all).find( (cmd) => cmd.name === inputCmdName ); if (!topCmd) { throw new Error( `Command \`${PgTerminal.italic(inputCmdName)}\` not found.` ); } // Dispatch start event const input = tokens.join(" "); PgCommon.createAndDispatchCustomEvent( getEventName(topCmd.name, "start"), input ); let cmd: CommandInferredImpl<string, Arg[], Option[], any[], any> = topCmd; const args = []; const opts = []; for (const i in tokens) { const token = tokens[i]; const nextIndex = +i + 1; const nextToken = tokens.at(nextIndex); const subcmd = cmd.subcommands?.find((cmd) => cmd.name === token); if (subcmd) cmd = subcmd; // Handle checks if (cmd.preCheck) { const preChecks = PgCommon.toArray(cmd.preCheck); for (const preCheck of preChecks) await preCheck(); } // Early continue if it's not the end of the command const isLast = +i === tokens.length - 1; const isNextTokenSubcmd = cmd.subcommands?.some( (cmd) => cmd.name === nextToken ); if (!isLast && isNextTokenSubcmd) continue; // Check missing command processor if (!cmd.run) { PgTerminal.log(` ${cmd.description} Usage: ${[...tokens.slice(0, +i), cmd.name].join(" ")} <COMMAND> Commands: ${formatList(cmd.subcommands!)}`); break; } const hasArgsOrOpts = cmd.args?.length || cmd.options!.length > 1; if (hasArgsOrOpts) { // Handle `help` option if (nextToken === "--help" || nextToken === "-h") { const usagePrefix = `Usage: ${[ ...tokens.slice(0, +i), cmd.name, ].join(" ")} [OPTIONS]`; const lines = [cmd.description]; if (cmd.subcommands) { lines.push( `${usagePrefix} <COMMAND>`, "Commands:", formatList(cmd.subcommands) ); } if (cmd.args) { const toArgStr = (arg: Arg) => { const name = arg.name.toUpperCase(); return arg.multiple ? `[${name}]` : `<${name}>`; }; const usageArgs = cmd.args.reduce( (acc, arg) => acc + toArgStr(arg) + " ", "" ); const argList = cmd.args.map((arg) => [ toArgStr(arg), (arg.description ?? "") + (arg.values ? ` (possible values: ${PgCommon.callIfNeeded( arg.values ).join(", ")})` : ""), ]); lines.push( `${usagePrefix} ${usageArgs}`, "Arguments:", formatList(argList, { align: "y" }) ); } if (cmd.options) { const optList = cmd.options.map((opt) => [ `${opt.short ? `-${opt.short}, ` : " "}--${opt.name} ${ opt.takeValue ? `<${opt.name.toUpperCase()}>` : "" }`, opt.description ?? "", ]); lines.push("Options:", formatList(optList, { align: "y" })); } PgTerminal.log(lines.join("\n\n")); return; } // Get subcommands, args and options if (nextToken && !isNextTokenSubcmd) { let takeValue = false; for (const argOrOpt of tokens.slice(nextIndex)) { if (takeValue) { opts.push(argOrOpt); takeValue = false; continue; } const isOpt = argOrOpt.startsWith("-"); if (isOpt && cmd.options) { const opt = cmd.options.find( (o) => "--" + o.name === argOrOpt || "-" + o.short === argOrOpt ); if (!opt) throw new Error(`Unexpected option: \`${argOrOpt}\``); opts.push(argOrOpt); if (opt.takeValue) takeValue = true; } else if (cmd.args) { args.push(argOrOpt); } } if (!cmd.args && cmd.subcommands) { if (nextToken.startsWith("-")) { throw new Error(`Unexpected option: \`${nextToken}\``); } throw new Error( `Subcommand doesn't exist: \`${nextToken}\` Available subcommands: ${cmd.subcommands.map((cmd) => cmd.name).join(", ")}` ); } if ( args.length > (cmd.args?.length ?? 0) && !cmd.args?.at(-1)?.multiple ) { throw new Error( `Provided argument count is higher than expected: ${args.length}` ); } } } // Parse args const parsedArgs: Record<string, Arrayable<string>> = {}; if (cmd.args) { for (const i in cmd.args) { const arg = cmd.args[i]; const inputArgs = arg.multiple ? args.slice(+i) : args[i] ? [args[i]] : []; if (!inputArgs.length && !arg.optional) { throw new Error(`Argument not specified: \`${arg.name}\``); } // Validate values if specified if (inputArgs.length && arg.values) { const values = PgCommon.callIfNeeded(arg.values); const invalidValue = inputArgs.find( (inputArg) => !values.includes(inputArg) ); if (invalidValue) { throw new Error( [ `Incorrect argument value given: \`${invalidValue}\``, `(possible values: ${values.join(", ")})`, ].join(" ") ); } } parsedArgs[arg.name] = arg.multiple ? inputArgs : inputArgs[0]; } } // Parse options const parsedOpts: Record<string, string | boolean> = {}; if (cmd.options) { for (const opt of cmd.options) { const i = opts.findIndex( (o) => o === "--" + opt.name || o === "-" + opt.short ); if (i === -1) continue; if (opt.takeValue) { const val = opts.at(i + 1); if (!val) { throw new Error(`Option value not given: \`${opt.name}\``); } // Validate values if specified if (opt.values) { const values = PgCommon.callIfNeeded(opt.values); if (!values.includes(val)) { throw new Error( [ `Incorrect option value given: \`${val}\``, `(possible values: ${values.join(", ")})`, ].join(" ") ); } } parsedOpts[opt.name] = val; } else { parsedOpts[opt.name] = true; } } } // Run the command processor const result = await cmd.run({ raw: input, args: parsedArgs, options: parsedOpts, }); // Dispatch finish event PgCommon.createAndDispatchCustomEvent( getEventName(topCmd.name, "finish"), result ); return result; } }); } } /** * Format the given list for terminal view. * * @param list list to format * @returns the formatted list */ export const formatList = ( list: Array<string[] | { name: string; description?: string }>, opts?: { align?: "x" | "y" } ) => { const { align } = PgCommon.setDefault(opts, { align: "x" }); return list .map((item) => Array.isArray(item) ? item : [item.name, item.description ?? ""] ) .sort((a, b) => { const allowedRegex = /^[a-zA-Z-]+$/; if (!allowedRegex.test(a[0])) return 1; if (!allowedRegex.test(b[0])) return -1; return a[0].localeCompare(b[0]); }) .reduce((acc, items) => { const output = items.reduce((acc, col, i) => { const MAX_CHARS = 80; const chunks: string[][] = []; const words = col.split(" "); let j = 0; for (let i = 0; i < words.length; i++) { while ( words[j] && [...(chunks[i] ?? []), words[j]].join(" ").length <= MAX_CHARS ) { chunks[i] ??= []; chunks[i].push(words[j]); j++; } } if (align === "x") { const WHITESPACE_LEN = 24; return ( acc + chunks.reduce( (acc, row, i) => acc + (i ? "\n\t" + " ".repeat(WHITESPACE_LEN) : "") + row.join(" "), "" ) + " ".repeat(Math.max(WHITESPACE_LEN - col.length, 0)) ); } return ( acc + (i ? "\n\t" : "") + chunks.reduce( (acc, row, i) => acc + (i ? "\n\t" : "") + row.join(" "), "" ) ); }, ""); return acc + "\t" + output + "\n"; }, ""); }; /** Get custom event name for the given command. */ const getEventName = (name: string, kind: "start" | "finish") => { switch (kind) { case "start": return "ondidrunstart" + name; case "finish": return "ondidrunfinish" + name; } };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/server.ts
import type { Idl } from "@coral-xyz/anchor"; import type { TupleFiles } from "./explorer"; /** Rust `Option` type */ type Option<T> = T | null | undefined; /** `/build` request */ interface BuildRequest { /** Program files */ files: TupleFiles; /** UUID of the program */ uuid?: Option<string>; /** Build flags */ flags?: Option<{ /** Whether to enable Anchor `seeds` feature */ seedsFeature?: Option<boolean>; /** Whether to remove docs from the Anchor IDL */ noDocs?: Option<boolean>; /** Whether to enable Anchor safety checks */ safetyChecks?: Option<boolean>; }>; } /** `/new` request */ interface ShareNewRequest { explorer: { files: { [key: string]: { content?: string }; }; }; } export class PgServer { /** * Build the program files. * * @param req build request * @returns the build response */ static async build(req: BuildRequest) { /** `/build` response */ interface BuildResponse { /** Build output */ stderr: string; /** UUID of the program */ uuid: string | null; /** Anchor IDL */ idl: Idl | null; } const response = await this._send("/build", { post: { body: JSON.stringify(req) }, }); return (await response.json()) as BuildResponse; } /** * Get the program ELF. * * NOTE: The server is only responsible for sending the program binary to the * client. The deployment process is done in the client. * * @param uuid unique project id * @returns the program ELF as `Buffer` */ static async deploy(uuid: string) { const response = await this._send(`/deploy/${uuid}`); const arrayBuffer = await response.arrayBuffer(); return Buffer.from(arrayBuffer); } /** * Get the shared project information. * * @param id share id * @returns the shared project response */ static async shareGet(id: string) { /** `/share` response */ type ShareResponse = ShareNewRequest["explorer"]; const response = await this._send(`/share/${id}`, { cache: true }); return (await response.json()) as ShareResponse; } /** * Share a new project. * * @param req share request * @returns the unique share id */ static async shareNew(req: ShareNewRequest) { /** `/new` response is the share id */ type ShareNewResponse = string; const response = await this._send("/new", { post: { body: JSON.stringify(req) }, }); return (await response.text()) as ShareNewResponse; } /** Default playground server URL */ private static readonly _DEFAULT_SERVER_URL = "https://api.solpg.io"; /** Server URL that is customizable from environment variables */ private static readonly _SERVER_URL = process.env.NODE_ENV === "production" ? this._DEFAULT_SERVER_URL : process.env.REACT_APP_SERVER_URL ?? this._DEFAULT_SERVER_URL; /** * Send an HTTP request to the Playground server. * * @throws when the response is not OK with the decoded response * @returns the HTTP response */ private static async _send( path: string, options?: { post?: { body: string }; cache?: boolean } ) { const requestInit: RequestInit = {}; if (options?.post) { requestInit.method = "POST"; requestInit.headers = { "Content-Type": "application/json", }; requestInit.body = options.post.body; } if (!options?.cache) { requestInit.cache = "no-store"; } const response = await fetch(`${this._SERVER_URL}${path}`, requestInit); if (!response.ok) { const message = await response.text(); throw new Error(message); } return response; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/package.ts
import { PgCommon } from "./common"; import { PgTerminal } from "./terminal"; import { GITHUB_URL } from "../../constants"; /** Mapped import results */ interface ImportResult { "anchor-cli": typeof import("@solana-playground/anchor-cli"); playnet: typeof import("@solana-playground/playnet"); rustfmt: typeof import("@solana-playground/rustfmt"); "seahorse-compile": typeof import("@solana-playground/seahorse-compile"); "solana-cli": typeof import("@solana-playground/solana-cli"); "spl-token-cli": typeof import("@solana-playground/spl-token-cli"); "sugar-cli": typeof import("@solana-playground/sugar-cli"); } /** All package names */ type PackageName = keyof ImportResult; /** Utility class to manage packages */ export class PgPackage { /** * Import the given package asynchronously. * * @param opts.log log the import progress to the terminal * @returns the imported package */ static async import<T extends PackageName>(name: T, opts?: { log: boolean }) { const uiName = this._getUIName(name); const log = opts?.log && this._isPkgLoadingInitial(name); if (log) PgTerminal.log(PgTerminal.info(`Loading ${uiName}...`)); try { const pkg = (await this._import(name)) as unknown as ImportResult[T]; if (log) PgTerminal.log(PgTerminal.success("Success.") + "\n"); return pkg; } catch (e: any) { throw new Error( `Failed to load ${PgTerminal.bold(uiName)}. Reason: ${e.message} If the problem continues, consider filing a bug report in ${PgTerminal.underline( GITHUB_URL + "/issues" )}` ); } } /** * Import the given package asynchronously. * * @returns the imported package */ private static async _import(name: PackageName) { switch (name) { case "anchor-cli": return await import("@solana-playground/anchor-cli"); case "playnet": return await import("@solana-playground/playnet"); case "rustfmt": return await import("@solana-playground/rustfmt"); case "seahorse-compile": return await import("@solana-playground/seahorse-compile"); case "solana-cli": return await import("@solana-playground/solana-cli"); case "spl-token-cli": return await import("@solana-playground/spl-token-cli"); case "sugar-cli": return await import("@solana-playground/sugar-cli"); default: throw new Error(`Unknown package \`${name}\``); } } /** * Convert the package name to UI name. * * @param name package name * @returns UI name, defaults to title case of the package name */ private static _getUIName(name: PackageName) { switch (name) { case "seahorse-compile": return "Seahorse"; case "spl-token-cli": return "SPL Token CLI"; default: return PgCommon.toTitleFromKebab(name).replace("Cli", "CLI"); } } /** * Get whether the package is being loaded for the first time and set the * package's loaded state to `true` * * @param name package name * @returns `true` if the package hasn't been loaded before */ private static _isPkgLoadingInitial(name: PackageName) { const initial = !this._loadedPkgs[name]; if (initial) { this._loadedPkgs[name] = true; } return initial; } /** Loaded packages */ private static readonly _loadedPkgs: { [K in PackageName]?: boolean } = {}; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/account.ts
import { getAnchorProgram } from "./program"; import { PgCommon } from "../common"; import type { PgWeb3 } from "../web3"; /** * Fetch the given on-chain account. * * @param accountName name of the account * @param address public key of the account * @returns the account */ export const fetchAccount = async ( accountName: string, address: PgWeb3.PublicKey ) => { const account = getAccountClient(accountName); return await account.fetch(address); }; /** * Fetch all of the accounts that match the account type. * * @param accountName name of the account * @returns the all accounts */ export const fetchAllAccounts = async (accountName: string) => { const account = getAccountClient(accountName); return await account.all(); }; /** * Get account builder client for the given `accountName`. * * @param accountName name of the account * @returns the account builder client */ const getAccountClient = (accountName: string) => { const program = getAnchorProgram(); return program.account[PgCommon.toCamelCase(accountName)]; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/program-interaction.ts
import { fetchAccount, fetchAllAccounts } from "./account"; import { GeneratableInstruction, createGenerator, generateValue, generateProgramAddressFromSeeds, } from "./generator"; import { getPrograms, getOrInitPythAccounts } from "./generators"; import { getIdlType, IdlInstruction } from "./idl-types"; import { createGeneratableInstruction, fillRandom } from "./instruction"; import { getAnchorProgram } from "./program"; import { getInstruction, resetInstruction, saveInstruction, syncAllInstructions, } from "./storage"; import { PgCommon } from "../common"; import { PgTx } from "../tx"; import { PgWallet } from "../wallet"; import { PgWeb3 } from "../web3"; export class PgProgramInteraction { /** * Get the saved generatable instruction or create a new one if it doesn't * exist in storage. * * @param idlIx IDL instruction * @returns the saved or default created generatable instruction */ static getOrCreateInstruction(idlIx: IdlInstruction) { const savedIx = getInstruction(idlIx); if (savedIx) return savedIx; // Not saved, create default return createGeneratableInstruction(idlIx); } /** * Send a test transaction to the current program. * * @param ix generated instruction * @returns the transaction hash */ static async test(ix: GeneratableInstruction) { const program = getAnchorProgram(); const args = ix.values.args.map((arg) => { const value = generateValue(arg.generator, ix.values); const { parse } = getIdlType(arg.type, program.idl); return parse(value); }); const accounts = ix.values.accounts.reduce((acc, cur) => { acc[cur.name] = generateValue(cur.generator, ix.values); return acc; }, {} as Record<string, string>); const signerAccounts = ix.values.accounts.filter((acc) => acc.isSigner); const keypairSigners = signerAccounts .map((acc) => { if (acc.generator.type !== "Random") return null; return PgWeb3.Keypair.fromSecretKey( Uint8Array.from(acc.generator.data) ); }) .filter(PgCommon.isNonNullish); const walletSigners = signerAccounts .map((acc) => { if (acc.generator.type !== "All wallets") return null; const generatorName = acc.generator.name; const walletAccount = PgWallet.accounts.find( ({ name }) => name === generatorName )!; return PgWallet.create(walletAccount); }) .filter(PgCommon.isNonNullish); const tx = await program.methods[ix.name](...args) .accounts(accounts) .transaction(); const txHash = await PgTx.send(tx, { keypairSigners, walletSigners }); return txHash; } /** {@link createGenerator} */ static createGenerator = createGenerator; /** {@link generateValue} */ static generateValue = generateValue; /** {@link generateProgramAddressFromSeeds} */ static generateProgramAddressFromSeeds = generateProgramAddressFromSeeds; /** {@link getIdlType} */ static getIdlType = getIdlType; /** {@link getPrograms} */ static getPrograms = getPrograms; /** {@link getAnchorProgram} */ static getAnchorProgram = getAnchorProgram; /** {@link fetchAccount} */ static fetchAccount = fetchAccount; /** {@link fetchAllAccounts} */ static fetchAllAccounts = fetchAllAccounts; /** {@link getOrInitPythAccounts} */ static getOrInitPythAccounts = getOrInitPythAccounts; /** {@link fillRandom} */ static fillRandom = fillRandom; /** {@link saveInstruction} */ static saveInstruction = saveInstruction; /** {@link syncAllInstructions} */ static syncAllInstructions = syncAllInstructions; /** {@link resetInstruction} */ static resetInstruction = resetInstruction; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/instruction.ts
import { getPrograms } from "./generators"; import { getIdlType, Idl, IdlAccount, IdlInstruction } from "./idl-types"; import { PgWeb3 } from "../web3"; import type { GeneratableInstruction, InstructionValueGenerator, } from "./generator"; import type { OrString } from "../types"; /** * Create a generatable instruction from the given IDL instruction. * * @param idlIx IDL instruction * @returns the generatable instruction */ export const createGeneratableInstruction = ( idlIx: IdlInstruction ): GeneratableInstruction => { return { name: idlIx.name, values: { programId: { generator: { type: "Current program" } }, // TODO: Handle composite accounts? accounts: (idlIx.accounts as IdlAccount[]).map((acc) => ({ ...acc, generator: createAccountGenerator(acc), })), args: idlIx.args.map((arg) => ({ ...arg, generator: { type: "Custom", value: "" }, })), }, }; }; /** * Fill empty values of the given generatable instruction with "Random" * generators. * * @param ix generatable instruction * @param idl IDL * @returns the instruction with empty values filled with "Random" generator */ export const fillRandom = ( ix: GeneratableInstruction, idl: Idl ): GeneratableInstruction => ({ ...ix, values: { ...ix.values, accounts: ix.values.accounts.map((acc) => { // Only override empty fields if (acc.generator.type === "Custom" && !acc.generator.value) { return { ...acc, generator: { type: "Random", data: Array.from(PgWeb3.Keypair.generate().secretKey), get value() { return PgWeb3.Keypair.fromSecretKey( Uint8Array.from((this as { data: number[] }).data) ).publicKey.toBase58(); }, }, }; } return acc; }), args: ix.values.args.map((arg) => { // Only override empty fields if (arg.generator.type === "Custom" && !arg.generator.value) { return { ...arg, generator: { type: "Random", value: getIdlType(arg.type, idl).generateRandom(), }, }; } return arg; }), }, }); /** * Create an account generator from the given IDL account. * * @param acc IDL account * @returns the account generator */ const createAccountGenerator = (acc: IdlAccount): InstructionValueGenerator => { // Handle `seeds` feature // TODO: Re-evaluate this once Anchor package has proper types for PDA seeds // https://github.com/coral-xyz/anchor/issues/2750 if (acc.pda) { return { type: "From seed", seeds: acc.pda.seeds.map((seed) => { switch (seed.kind) { case "const": return { type: seed.type, generator: { type: "Custom", value: seed.value }, }; case "arg": return { type: seed.type, generator: { type: "Arguments", name: seed.path }, }; case "account": return { type: seed.type, generator: { type: "Accounts", name: seed.path }, }; default: throw new Error(`Unknown seed kind: \`${seed.kind}\``); } }), // TODO: Handle `acc.pda.programId` programId: { generator: { type: "Current program" } }, }; } // Set common wallet account names to current wallet const COMMON_WALLET_ACCOUNT_NAMES = ["authority", "owner", "payer", "signer"]; if (acc.isSigner && COMMON_WALLET_ACCOUNT_NAMES.includes(acc.name)) { return { type: "Current wallet" }; } // Check whether it's a known program const knownProgram = getPrograms().find((p) => p.alias?.includes(acc.name)); if (knownProgram) return { type: "All programs", name: knownProgram.name }; return { type: "Custom", value: getKnownAccountKey(acc.name) ?? "" }; }; /** * Get the public key of known accounts, e.g. `systemProgram`. * * @param name name of the account * @returns account public key as string or empty string if the name is unknown */ const getKnownAccountKey = < T extends typeof KNOWN_ACCOUNT_KEYS, N extends OrString<keyof T> >( name: N ) => { return (KNOWN_ACCOUNT_KEYS[name as keyof typeof KNOWN_ACCOUNT_KEYS] ?? null) as N extends keyof T ? T[N] : string | null; }; /* Known account name -> account key map */ // TODO: Add sysvar generator const KNOWN_ACCOUNT_KEYS = { clock: PgWeb3.SYSVAR_CLOCK_PUBKEY.toBase58(), rent: PgWeb3.SYSVAR_RENT_PUBKEY.toBase58(), } as const;
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/program.ts
import { AnchorProvider, Program } from "@coral-xyz/anchor"; import { PgCommon } from "../common"; import { PgConnection } from "../connection"; import { PgProgramInfo } from "../program-info"; import { PgWallet } from "../wallet"; /** * Create an Anchor program instance. * * @param params optional overrides of the default playground values * @returns the created Anchor program instance. */ export const getAnchorProgram = (params?: { connection?: typeof PgConnection["current"]; wallet?: typeof PgWallet["current"]; programId?: typeof PgProgramInfo["pk"]; idl?: typeof PgProgramInfo["idl"]; }) => { const { connection, wallet, programId, idl } = PgCommon.setDefault(params, { connection: PgConnection.current, wallet: PgWallet.current, programId: PgProgramInfo.pk, idl: PgProgramInfo.idl, }); if (!wallet) throw new Error("Not connected"); if (!programId) throw new Error("Program ID not found"); if (!idl) throw new Error("Anchor IDL not found"); const provider = new AnchorProvider( connection, wallet, AnchorProvider.defaultOptions() ); return new Program(idl, programId, provider); };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/storage.ts
import { PgCommon } from "../common"; import type { GeneratableInstruction } from "./generator"; import type { IdlAccount, IdlInstruction } from "./idl-types"; /** * Get the instruction from the configured {@link storage}. * * @param idlIx IDL instruction * @returns the saved instruction or `null` */ export const getInstruction = ( idlIx: IdlInstruction ): GeneratableInstruction | null => { const savedIx = getAllInstructions()[idlIx.name]; return savedIx ? { name: idlIx.name, values: savedIx } : null; }; /** * Save the instruction to the configured {@link storage}. * * @param ix generatable instruction */ export const saveInstruction = (ix: GeneratableInstruction) => { const savedIxs = getAllInstructions(); savedIxs[ix.name] = ix.values; saveAllInstructions(savedIxs); }; /** * Sync all instructions in storage based on the given IDL. * * @param idlIxs IDL instructions */ export const syncAllInstructions = (idlIxs: IdlInstruction[]) => { // Delete the instructions that exists in storage but doesn't exist in the IDL const savedIxs = getAllInstructions(); const ixNames = idlIxs.map((ix) => ix.name); const ixNamesToRemove = Object.keys(savedIxs).filter( (ixName) => !ixNames.includes(ixName) ); for (const ixName of ixNamesToRemove) delete savedIxs[ixName]; // Update the instructions that changed const ixsNamesToUpdate = idlIxs .filter((ix) => { const savedIx = savedIxs[ix.name]; if (!savedIx) return true; // Check lengths if (savedIx.args.length !== ix.args.length) return true; if (savedIx.accounts.length !== ix.accounts.length) return true; // Check args const isAllArgsEqual = savedIx.args.every((savedArg) => { const arg = ix.args.find((arg) => arg.name === savedArg.name); if (!arg) return false; return PgCommon.isEqual(arg.type, savedArg.type); }); if (!isAllArgsEqual) return true; // Check accounts const isAllAccsEqual = savedIx.accounts.every((savedAcc) => { const acc = ix.accounts.find((acc) => acc.name === savedAcc.name); if (!acc) return false; // TODO: Handle composite accounts? const { isMut, isSigner } = acc as IdlAccount; return savedAcc.isMut === isMut && savedAcc.isSigner === isSigner; }); if (!isAllAccsEqual) return true; return false; }) .map((ix) => ix.name); // Delete and allow for the instruction to be recrated with default values // TODO: Only update the instruction values that changed for (const ixName of ixsNamesToUpdate) delete savedIxs[ixName]; // Save the instructions if (ixNamesToRemove.length || ixsNamesToUpdate.length) { saveAllInstructions(savedIxs); } }; /** * Reset the given instruction in storage {@link storage}. * * @param ix generatable instruction */ export const resetInstruction = (ix: GeneratableInstruction) => { const savedIxs = getAllInstructions(); delete savedIxs[ix.name]; saveAllInstructions(savedIxs); }; /** A map of instruction names to generatable instruction values */ type SavedInstructions = Record<string, GeneratableInstruction["values"]>; /** Storage to use for program interactions */ const storage = sessionStorage; /** Program interaction key in {@link storage} */ const STORAGE_KEY = "program-interaction"; /** * Get all instructions from the {@link storage}. * * @returns the instructions from storage */ const getAllInstructions = (): SavedInstructions => { const value = storage.getItem(STORAGE_KEY); if (!value) { const defaultValue: SavedInstructions = {}; saveAllInstructions(defaultValue); return defaultValue; } return JSON.parse(value); }; /** * Save all instructions to the {@link storage}. * * @param ixs instructions to save to storage */ const saveAllInstructions = (ixs: SavedInstructions) => { storage.setItem(STORAGE_KEY, JSON.stringify(ixs)); };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/generator.ts
import { IdlType, getIdlType } from "./idl-types"; import { getPrograms, getPythAccounts } from "./generators"; import { PgProgramInfo } from "../program-info"; import { PgWallet } from "../wallet"; import { PgWeb3 } from "../web3"; /** * Generatable instruction, i.e. the values of the instruction can be derived * from its generators. * * The reason why the values are generated via generators rather than saving * the plain value is, the values should change when how they are generated * change, e.g. if a public key is generated via "Current wallet" generator, * the value should update when the current wallet changes. */ export interface GeneratableInstruction { /** Instruction name */ name: string; /** Instruction values */ values: { /** Generatable program id */ programId: WithGenerator<ProgramIdGenerator>; /** Generatable instruction accounts */ accounts: Array< { /** Account name */ name: string; /** Whether the account is mutable */ isMut: boolean; /** Whether the account is a signer */ isSigner: boolean; } & WithGenerator<AccountGenerator> >; /** Generatable instruction arguments */ args: Array< { /** Argument name */ name: string; /** Argument IDL type */ type: IdlType; } & WithGenerator<ArgsGenerator> >; }; } /** Common generator definition utility type */ type WithGenerator<T extends { type: string }> = { generator: T; error?: string | boolean; }; /** All possible generators for an instruction */ export type InstructionValueGenerator = | ProgramIdGenerator | AccountGenerator | ArgsGenerator; /** Generators for the program id */ type ProgramIdGenerator = CustomGenerator | RefGenerator | ProgramGenerator; /** Generators for the accounts */ type AccountGenerator = | CustomGenerator | RandomGenerator | RefGenerator | PublicKeyGenerator | ProgramGenerator; /** Generators for the arguments */ type ArgsGenerator = | CustomGenerator | RandomGenerator | RefGenerator | PublicKeyGenerator | ProgramGenerator; /** * Custom generator, i.e. any user supplied value that doesn't fit the other * generator types. */ type CustomGenerator = { type: "Custom"; value: string }; /** Random value generator */ type RandomGenerator = { type: "Random"; value: string; data?: any }; /** Reference generators */ type RefGenerator = | { type: "Accounts"; name: string } | { type: "Arguments"; name: string }; /** Public key generators */ type PublicKeyGenerator = | { type: "Current wallet" } | { type: "All wallets"; name: string } | { type: "From seed"; seeds: Seed[]; programId: WithGenerator<ProgramGenerator>; } | { type: "All programs"; name: string } | { type: "Pyth"; name: string }; /** Program public key generator */ type ProgramGenerator = { type: "Current program" }; /** Generatable derivation seed */ export type Seed = { type: IdlType; generator: InstructionValueGenerator }; /** * Create an instruction value generator. * * @param selectedItems selected items in search bar * @param value search bar input value * @returns the created instruction value generator */ export const createGenerator = ( selectedItems: Array<{ label: string; data?: any }>, value: string ): InstructionValueGenerator | null => { if (!selectedItems.length) return { type: "Custom", value }; const type = selectedItems[0].label as InstructionValueGenerator["type"]; switch (type) { case "Custom": return { type, value }; case "Random": return { type, value, data: selectedItems[0].data }; case "Current wallet": case "Current program": return { type }; case "All wallets": case "All programs": case "Pyth": case "Accounts": case "Arguments": if (selectedItems.length !== 2) return null; return { type, name: selectedItems[1].label }; case "From seed": if (selectedItems.length !== 2) return null; return { type, ...selectedItems[1].data }; default: { // Default non-standard types to "Custom", e.g. `false` return { type: "Custom", value }; } } }; /** * Generate the value from the given generator. * * @param generator generator * @param values generatable instruction values * @returns the generatable value */ export const generateValue = ( generator: InstructionValueGenerator, values: GeneratableInstruction["values"] ): string => { switch (generator.type) { case "Custom": case "Random": return generator.value; case "Current wallet": return PgWallet.current!.publicKey.toBase58(); case "All wallets": { const walletAcc = PgWallet.accounts.find( (acc) => acc.name === generator.name )!; return PgWallet.create(walletAcc).publicKey.toBase58(); } case "From seed": return generateProgramAddressFromSeeds( generator.seeds, generateValue(generator.programId.generator, values), values ).toBase58(); case "Current program": return PgProgramInfo.getPkStr()!; case "All programs": return getPrograms().find((p) => p.name === generator.name)!.programId; case "Pyth": return getPythAccounts()[generator.name]; case "Accounts": { const accRef = values.accounts.find( (acc) => acc.name === generator.name )!; return generateValue(accRef.generator, values); } case "Arguments": { const argRef = values.args.find((arg) => arg.name === generator.name)!; return generateValue(argRef.generator, values); } } }; /** * Generate program derived address. * * @param seeds derivation seeds * @param programId program's public key * @param values generatable instruction values * @returns the program address derived from the given seeds */ export const generateProgramAddressFromSeeds = ( seeds: Seed[], programId: PgWeb3.PublicKey | string, values: GeneratableInstruction["values"] ) => { if (typeof programId !== "object") programId = new PgWeb3.PublicKey(programId); const buffers = seeds.map((seed) => { const value = generateValue(seed.generator, values); const { parse, toBuffer } = getIdlType(seed.type); return toBuffer(parse(value)); }); return PgWeb3.PublicKey.findProgramAddressSync(buffers, programId)[0]; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/index.ts
export { PgProgramInteraction } from "./program-interaction"; export type { Idl, IdlInstruction, IdlType } from "./idl-types"; export type { GeneratableInstruction, InstructionValueGenerator, Seed, } from "./generator";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/idl-types.ts
import { BN, DecodeType } from "@coral-xyz/anchor"; import type { Idl, IdlEnumFieldsNamed, IdlEnumFieldsTuple, IdlEnumVariant, IdlType, } from "@coral-xyz/anchor/dist/cjs/idl"; import { PgCommon } from "../common"; import { PgWeb3 } from "../web3"; import type { MergeUnion, OrString } from "../types"; export type { Idl, IdlAccount, IdlInstruction, IdlType, } from "@coral-xyz/anchor/dist/cjs/idl"; interface PgIdlType< T extends IdlType, V extends DecodeType<T, never> = DecodeType<T, never> > { /** Display type to show in UI */ displayType: OrString<Exclude<T, object>>; /** * Parse from string to the IDL type's JS equivalent. * * @param value string value * @returns the parsed value */ parse: (value: string) => V; /** * Serialize the type. * * **NOTE:** This is default serialization and is **not** related to `borsh`. * * @param value parsed value * @returns the serialized bytes */ toBuffer: (value: V) => Buffer; /** * Generate a stringified random value. * * @returns the generated value */ generateRandom: () => string; } /** * Get IDL type, i.e. an object that has all the necessary data to handle * operations of the given IDL type. * * @param idlType Anchor IDL type * @param idl Anchor IDL(only required for defined types) * @returns the IDL type */ // @ts-ignore export const getIdlType: <T extends IdlType>( idlType: T, idl?: Idl ) => PgIdlType<T> = (idlType, idl) => { switch (idlType) { case "publicKey": return publicKey; case "string": return string; case "bool": return bool; case "u8": return u8; case "u16": return u16; case "u32": return u32; case "u64": return u64; case "u128": return u128; case "i8": return i8; case "i16": return i16; case "i32": return i32; case "i64": return i64; case "i128": return i128; case "f32": return f32; case "f64": return f64; case "bytes": return bytes; } const { defined, option, coption, array, vec } = idlType as Partial< MergeUnion<Exclude<IdlType, string>> >; if (defined) { if (!idl?.types) { throw new Error(`Defined type \`${defined}\` requires idl.types`); } const definedType = idl.types.find((type) => type.name === defined); if (!definedType) throw new Error(`Type \`${defined}\` not found`); switch (definedType.type.kind) { case "struct": { const fields = definedType.type.fields; return createIdlType({ displayType: definedType.name, parse: (value) => { if (!value.startsWith("{") || !value.endsWith("}")) { throw new Error("Not an object"); } // The implementation assumes the struct only has basic properties // e.g. `String` and not a nested struct property. The initial // implementation of the test UI had support for complex structs // from JSON inputs but that wasn't intuitive and it also didn't // work for some types like `u64`. The current implementation // supports inputs similar to JS argument inputs. Adding support // for complex structs would make the implementation a lot harder // as it would require some sort of a JS parser to correctly parse // the input and given how rarely they are being used, it's better // to avoid implementing complex struct support. const inputFields = value.slice(1, -1).split(","); if (inputFields.length !== fields.length) { throw new Error("Struct fields do not match"); } return inputFields.reduce((acc, cur) => { const [key, value] = cur.split(":").map((part) => part.trim()); const field = fields.find((f) => f.name === key); if (!field) throw new Error(`Field \`${key}\` not found`); acc[key] = getIdlType(field.type, idl).parse(value); return acc; }, {} as Record<string, unknown>); }, toBuffer: (value) => { const buffers = Object.entries(value as object).map( ([key, value]) => { const field = fields.find((field) => field.name === key); if (!field) throw new Error(`Field \`${key}\` not found`); return getIdlType(field.type, idl).toBuffer(value); } ); return Buffer.concat(buffers); }, generateRandom: () => { return ( fields.reduce((acc, field, i) => { const value = getIdlType(field.type, idl).generateRandom(); return `${acc}${i ? "," : ""} ${field.name}: ${value}`; }, "{") + " }" ); }, }); } case "enum": { const variants = definedType.type.variants; const getVariant = (variantName: string) => { // Object keys are converted to camelCase because Anchor generated // enum names as PascalCase prior to 0.29.0 and the user can import // a custom IDL. const camelCaseVariantName = PgCommon.toCamelCase(variantName); const variant = variants.find( (v) => PgCommon.toCamelCase(v.name) === camelCaseVariantName ); if (!variant) { throw new Error(`Variant \`${variantName}\` not found`); } return variant; }; const handleVariant = <U, N, T>( variant: IdlEnumVariant, unitCb: () => U, namedCb: (fields: IdlEnumFieldsNamed) => N, tupleCb: (fields: IdlEnumFieldsTuple) => T ) => { // Unit if (!variant.fields?.length) return unitCb(); // Named if ((variant.fields as IdlEnumFieldsNamed)[0].name) { return namedCb(variant.fields as IdlEnumFieldsNamed); } // Tuple return tupleCb(variant.fields as IdlEnumFieldsTuple); }; const getStructFromNamedEnum = (fields: IdlEnumFieldsNamed) => { return getIdlType( { defined: "__" }, { ...idl, types: [ ...idl.types!, { name: "__", type: { kind: "struct", fields }, }, ], } ); }; return createIdlType({ displayType: definedType.name, parse: (value) => { // Allow unit enums to be passed by name try { const unitVariant = getVariant(value); if (unitVariant) return { [PgCommon.toCamelCase(value)]: {} }; } catch {} // Named if (!value.startsWith("{") || !value.endsWith("}")) { throw new Error("Not an object"); } const parsedKeyValue = value .slice(1, -1) .match(/(\S+)(\s*)?:\s+(.+[\]|}])/); if (!parsedKeyValue) throw new Error("Unable to parse input"); const variantKey = PgCommon.toCamelCase(parsedKeyValue[1]); const variantValue = parsedKeyValue[3]; const openingChar = variantValue[0]; const isNamed = openingChar === "{"; // { named: { a: 1, b: true } } const isUnnamed = openingChar === "["; // { unnamed: [1, true] } if (!isNamed && !isUnnamed) throw new Error("Unable to parse"); const parsedValue = handleVariant( getVariant(variantKey), () => ({}), (fields) => getStructFromNamedEnum(fields).parse(variantValue), (fields) => { const inputElements = variantValue.slice(1, -1).split(","); if (inputElements.length !== fields.length) { throw new Error("Tuple length doesn't match"); } return inputElements.map((value, i) => { return getIdlType(fields[i], idl).parse(value.trim()); }); } ); return { [variantKey]: parsedValue }; }, toBuffer: (value: any) => { const variantName = Object.keys(value)[0]; const variantValue = value[variantName]; const disc = variants.findIndex( (v) => PgCommon.toCamelCase(v.name) === variantName ); const data = handleVariant( getVariant(variantName), () => Buffer.alloc(0), (fields) => { const buffers = fields.map((f) => { return getIdlType(f.type, idl).toBuffer(variantValue[f.name]); }); return Buffer.concat(buffers); }, (fields) => { const buffers = fields.map((f, i) => { return getIdlType(f, idl).toBuffer(variantValue[i]); }); return Buffer.concat(buffers); } ); return Buffer.concat([Buffer.from([disc]), data]); }, generateRandom: () => { const index = PgCommon.generateRandomInt(0, variants.length - 1); const variant = variants[index]; const camelCaseName = PgCommon.toCamelCase(variant.name); return handleVariant( variant, () => camelCaseName, (fields) => { return ( `{ ${camelCaseName}: ` + getStructFromNamedEnum(fields).generateRandom() + " }" ); }, (fields) => { return ( `{ ${camelCaseName}: [` + fields.reduce((acc, field, i) => { return ( acc + (i ? ", " : "") + getIdlType(field, idl).generateRandom() ); }, "") + "] }" ); } ); }, }); } case "alias": { return { ...getIdlType(definedType.type.value, idl), displayType: definedType.name, }; } } } const optionLike = option ?? coption; if (optionLike) { const none = option ? [0] : [0, 0, 0, 0]; const some = option ? [1] : [1, 0, 0, 0]; const inner = getIdlType(optionLike, idl); return createIdlType({ ...inner, displayType: `${option ? "" : "C"}Option<${inner.displayType}>`, parse: (value) => { if (["", "null", "none"].includes(value)) return null; return inner.parse(value); }, toBuffer: (value) => { if (value === null) return Buffer.from(none); return Buffer.concat([Buffer.from(some), inner.toBuffer(value)]); }, generateRandom: () => { if (!PgCommon.generateRandomInt(0, 1)) return "null"; return inner.generateRandom(); }, }); } if (array || vec) { const [elementType, len] = array ?? [vec]; const inner = getIdlType(elementType!, idl); return createIdlType({ displayType: array ? `[${inner.displayType}; ${len}]` : `Vec<${inner.displayType}>`, parse: (value) => { if (!value.startsWith("[") || !value.endsWith("]")) { throw new Error("Not an array"); } const parsedArray = value .slice(1, -1) .split(",") .map((el) => el.trim()) .filter(Boolean) .map(inner.parse); if (array && parsedArray.length !== len) { throw new Error("Invalid length"); } return parsedArray; }, toBuffer: (value) => { if (!Array.isArray(value)) throw new Error("Not an array"); return Buffer.concat(value.map(inner.toBuffer)); }, generateRandom: () => { const stringifiedArray = JSON.stringify( new Array(array ? len : 4).fill(null).map(inner.generateRandom) ); if (inner.displayType === "string") return stringifiedArray; return stringifiedArray.replaceAll('"', ""); }, }); } throw new Error(`Unknown IDL type: ${idlType}`); }; /** * Create an IDL type. * * @param idlType type-inferred IDL type * @returns the created IDL type */ const createIdlType = <T extends IdlType>(idlType: PgIdlType<T>) => { return idlType; }; const publicKey = createIdlType({ displayType: "publicKey", parse: (value) => new PgWeb3.PublicKey(string.parse(value)), toBuffer: (value) => value.toBuffer(), generateRandom: () => PgWeb3.Keypair.generate().publicKey.toBase58(), }); const string = createIdlType({ displayType: "string", // Remove the quotes from string in order to make struct inputs intuitive // e.g. `{ name: "Abc" }` should be parsed as "Abc" instead of "\"Abc\"". // Maybe replace only the first and the last quotes? parse: (value) => value.replaceAll('"', "").replaceAll("'", ""), toBuffer: (value) => Buffer.from(value), generateRandom: () => { return Buffer.from( new Array(4).fill(0).map(() => PgCommon.generateRandomInt(65, 122)) ).toString(); }, }); const bool = createIdlType({ displayType: "bool", parse: (value) => { if (value === "true") return true; if (value === "false") return false; throw new Error("Invalid bool"); }, toBuffer: (value) => Buffer.from([value ? 1 : 0]), generateRandom: () => (PgCommon.generateRandomInt(0, 1) ? "true" : "false"), }); const u8 = createIdlType({ displayType: "u8", parse: (value) => { assertUint(value, 1); return parseInt(value); }, toBuffer: (value) => Buffer.from([value]), generateRandom: () => generateRandomUint(1), }); const u16 = createIdlType({ displayType: "u16", parse: (value) => { assertUint(value, 2); return parseInt(value); }, toBuffer: (value) => new BN(value).toArrayLike(Buffer, "le", 2), generateRandom: () => generateRandomUint(2), }); const u32 = createIdlType({ displayType: "u32", parse: (value) => { assertUint(value, 4); return parseInt(value); }, toBuffer: (value) => new BN(value).toArrayLike(Buffer, "le", 4), generateRandom: () => generateRandomUint(4), }); const u64 = createIdlType({ displayType: "u64", parse: (value) => { assertUint(value, 8); return new BN(value); }, toBuffer: (value) => value.toArrayLike(Buffer, "le", 8), generateRandom: () => generateRandomUint(8), }); const u128 = createIdlType({ displayType: "u128", parse: (value) => { assertUint(value, 16); return new BN(value); }, toBuffer: (value) => value.toArrayLike(Buffer, "le", 16), generateRandom: () => generateRandomUint(16), }); const i8 = createIdlType({ displayType: "i8", parse: (value) => { assertInt(value, 1); return parseInt(value); }, toBuffer: (value) => Buffer.from([value]), generateRandom: () => generateRandomInt(1), }); const i16 = createIdlType({ displayType: "i16", parse: (value) => { assertInt(value, 2); return parseInt(value); }, toBuffer: (value) => new BN(value).toArrayLike(Buffer, "le", 2), generateRandom: () => generateRandomInt(2), }); const i32 = createIdlType({ displayType: "i32", parse: (value) => { assertInt(value, 4); return parseInt(value); }, toBuffer: (value) => new BN(value).toArrayLike(Buffer, "le", 4), generateRandom: () => generateRandomInt(4), }); const i64 = createIdlType({ displayType: "i64", parse: (value) => { assertInt(value, 8); return new BN(value); }, toBuffer: (value) => value.toArrayLike(Buffer, "le", 8), generateRandom: () => generateRandomInt(8), }); const i128 = createIdlType({ displayType: "i128", parse: (value) => { assertInt(value, 16); return new BN(value); }, toBuffer: (value) => value.toArrayLike(Buffer, "le", 16), generateRandom: () => generateRandomInt(16), }); const f32 = createIdlType({ displayType: "f32", parse: (value) => { if (!PgCommon.isFloat(value)) throw new Error("Invalid float"); return parseFloat(value); }, toBuffer: (value) => { const buf = Buffer.alloc(4); buf.writeFloatLE(value); return buf; }, generateRandom: () => Math.random().toString(), }); const f64 = createIdlType({ displayType: "f64", parse: (value) => { if (!PgCommon.isFloat(value)) throw new Error("Invalid float"); return parseFloat(value); }, toBuffer: (value) => { const buf = Buffer.alloc(8); buf.writeFloatLE(value); return buf; }, generateRandom: () => Math.random().toString(), }); const bytes = createIdlType({ displayType: "bytes", parse: (value) => { const array: number[] = JSON.parse(value); const isValid = array.every((el) => el === 0 || u8.parse(el.toString())); if (!isValid) throw new Error("Invalid bytes"); return Buffer.from(array); }, toBuffer: (value) => value, generateRandom: () => { const randomBytes = new Uint8Array(4); crypto.getRandomValues(randomBytes); return JSON.stringify(Array.from(randomBytes)); }, }); /** * Assert whether the given value is parsable to an unsigned integer and is * within the allowed range. * * @param value input * @param len byte length for the unsigned integer */ function assertUint(value: string, len: number) { if (value === "") throw new Error("Cannot be empty"); const bn = new BN(value); if (bn.isNeg()) { throw new Error(`uint cannot be negative: ${value}`); } if (bn.gt(new BN(new Array(len).fill(0xff)))) { throw new Error(`${value} is not within range`); } } /** * Assert whether the given value is parsable to an signed integer and is * within the allowed range. * * @param value input * @param len byte length for the signed integer */ function assertInt(value: string, len: number) { if (value === "") throw new Error("Cannot be empty"); const bn = new BN(value); const intMax = new BN(new Array(len).fill(0xff)).divn(2); if (bn.gt(intMax) || bn.lt(intMax.addn(1).neg())) { throw new Error(`${value} is not within range`); } } /** * Generate a random unsigned integer for the given byte length. * * @param len byte length * @returns the randomly generated unsigned integer */ function generateRandomUint(len: number) { return PgCommon.generateRandomBigInt( 0n, BigInt(new BN(new Array(len).fill(0xff)).toString()) ).toString(); } /** * Generate a random signed integer for the given byte length. * * @param len byte length * @returns the randomly generated signed integer */ function generateRandomInt(len: number) { const max = BigInt(new BN(new Array(len).fill(0xff)).toString()) / 2n; return PgCommon.generateRandomBigInt(-(max + 1n), max).toString(); }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/generators/pyth.ts
import { PgCommon } from "../../common"; import { Cluster, PgConnection } from "../../connection"; /** Pyth feed accounts per cluster */ const PYTH_ACCOUNTS: { /** Map of feed account name -> public key */ [K in Cluster]?: { [name: string]: string }; } = {}; /** * Get or initialize Pyth feed accounts for the current cluster. * * This function will only fetch the data once per cluster and all subsequent * calls can be synchronous via {@link getPythAccounts}. * * @returns the Pyth feed accounts for the current cluster */ export const getOrInitPythAccounts = async () => { PYTH_ACCOUNTS[PgConnection.cluster] ??= await PgCommon.fetchJSON( `/pyth/${PgConnection.cluster}.json` ); return getPythAccounts(); }; /** * Get Pyth accounts for the current cluster. * * This function requires the {@link getOrInitPythAccounts} function to be called * at least once before otherwise it will throw an error. * * @returns the Pyth feed accounts for the current cluster */ export const getPythAccounts = () => { const accounts = PYTH_ACCOUNTS[PgConnection.cluster]; if (accounts) return accounts; throw new Error(`Pyth accounts on ${PgConnection.cluster} not found`); };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/generators/program.ts
import { ASSOCIATED_PROGRAM_ID, TOKEN_PROGRAM_ID, } from "@coral-xyz/anchor/dist/cjs/utils/token"; import { PgCommon } from "../../common"; import { PgProgramInfo } from "../../program-info"; import { PgWeb3 } from "../../web3"; import type { Arrayable } from "../../types"; /** Program data */ interface Program { /** Title Case name of the program */ name: string; /** Program's public key */ programId: string; /** Program name alias to match against account name */ alias?: Arrayable<string>; } /** Known programs */ const PROGRAMS: Readonly<Program[]> = [ { name: "System", programId: PgWeb3.SystemProgram.programId.toBase58(), }, { name: "Token", programId: TOKEN_PROGRAM_ID.toBase58(), }, { name: "Token 2022", programId: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", }, { name: "Associated Token", programId: ASSOCIATED_PROGRAM_ID.toBase58(), }, { name: "Token Metadata", programId: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", }, ].map((program) => { const nameCamel = PgCommon.toCamelCase(program.name); const alias = [nameCamel, nameCamel + "Program"]; return { ...program, alias }; }); /** * Get known program names and their public keys. * * @returns the programs */ export const getPrograms = () => { if (PgProgramInfo.idl && PgProgramInfo.pk) { const currentProgram: Readonly<Program> = { name: PgCommon.toTitleFromSnake(PgProgramInfo.idl.name), programId: PgProgramInfo.getPkStr()!, }; return [currentProgram].concat(PROGRAMS); } return PROGRAMS; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/program-interaction/generators/index.ts
export { getPrograms } from "./program"; export { getOrInitPythAccounts, getPythAccounts } from "./pyth";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tutorial/storage.ts
import { PgExplorer } from "../explorer"; import type { ValueOf } from "../types"; /** A map of string to unknown data as used for tutorial storage data */ type Data = Record<string, unknown>; /** * Get the current tutorial's storage object that is useful for persisting user * data in the current tutorial. * * The API is rougly the same as the `Storage` API, e.g. `localStorage`, main * differences being: * - Asynchronous API due to using `indexedDB` under the hood * - Optionally, the storage object can be made type-safe * * # Example * * ```ts * type StorageData { * field: number; * anotherField: string; * } * * const storage = getTutorialStorage<StorageData>(); * const field = await storage.getItem("field"); // number | undefined * ``` * * @returns the tutorial storage */ export const getTutorialStorage = <T extends Data = Data>() => { class PgTutorialStorage { /** * Get the item from the given key. * * @param key key of the item * @returns the value or `undefined` if key doesn't exist */ async getItem(key: keyof T) { const data = await this._readFile(); return data[key] as ValueOf<T> | undefined; } /** * Set the key-value pair. * * @param key key of the item * @param value value of the item */ async setItem(key: keyof T, value: ValueOf<T>) { const data = await this._readFile(); data[key] = value; await this._writeFile(data); } /** * Remove the key-value pair if it exists. * * @param key key of the item */ async removeItem(key: keyof T) { const data = await this._readFile(); delete data[key]; await this._writeFile(data); } /** Clear all key-value pairs and reset to the default state. */ async clear() { await this._writeFile(PgTutorialStorage._DEFAULT); } /** * Read the tutorial storage data file as JSON. * * @returns the data as JSON */ private async _readFile() { return await PgExplorer.fs.readToJSONOrDefault<T>( PgTutorialStorage._PATH, PgTutorialStorage._DEFAULT ); } /** * Save the file with the given storage data. * * @param data storage data */ private async _writeFile(data: T) { await PgExplorer.fs.writeFile( PgTutorialStorage._PATH, JSON.stringify(data) ); } /** Relative path to the tutorial storage JSON file */ private static _PATH = ".workspace/tutorial-storage.json"; /** Default state of the tutorial storage data */ private static _DEFAULT = {} as T; } return new PgTutorialStorage(); };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tutorial/details.ts
export const TUTORIAL_LEVELS = [ "Beginner", "Intermediate", "Advanced", ] as const; export const TUTORIAL_CATEGORIES = [ "Compression", "DeFi", "Gaming", "Governance", "Lending", "Multisig", "NFT", "Payment", "Stablecoin", "SPL", "Staking", "Token", "Trading", ] as const;
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tutorial/types.ts
import type { ComponentType } from "react"; import { TUTORIAL_CATEGORIES, TUTORIAL_LEVELS } from "./details"; import type { Nullable, RequiredKey } from "../types"; type Author = { /** Author's name that will be displayed as one of the creators of the tutorial */ name: string; /** Optional link to the author's page, e.g Twitter, Github */ link?: string; }; /** Program info state */ export type TutorialState = Nullable< TutorialMetadata & { view: "about" | "main"; data: TutorialData } >; /** Serialized program info that's used in storage */ export type SerializedTutorialState = Nullable<TutorialMetadata>; /** Tutorial data with optional fields. */ export interface TutorialDataInit { /** Tutorial name that will be shown in tutorials section */ name: string; /** * Tutorial description that will be shown in tutorials section. * * Only the first 72 characters will be shown in the tutorials page. */ description: string; /** Authors of the tutorial */ authors: Author[]; /** Difficulty level of the tutorial */ level: TutorialLevel; /** Solana program framework */ framework?: FrameworkName; /** Programming languages used in the tutorial */ languages?: LanguageName[]; /** Category of the tutorial. Can specify up to 3 categories. */ categories?: TutorialCategory[]; /** Whether the tutorial is featured */ featured?: boolean; /** * Tutorial cover image that will be shown in tutorials section. * * It can either be `/tutorials/...` or full url to the image. * * Thumbnails are displayed at 4:3 aspect ratio(278x216). * * Defaults to `/tutorials/<tutorial-name>/thumbnail.*`. */ thumbnail?: string; /** * Tutorial component async import. * * Defaults to `./<TutorialName>`. */ elementImport?: () => Promise<{ default: ComponentType<Omit<TutorialData, "elementImport">>; }>; } /** Tutorial data with optional fields filled with defaults. */ export type TutorialData = RequiredKey< TutorialDataInit, "thumbnail" | "elementImport" >; export interface TutorialMetadata { /** Current page number */ pageNumber: number; /** Total page amount of the tutorial */ pageCount: number; /** Whether the tutorial has been completed */ completed: boolean; } export type TutorialLevel = typeof TUTORIAL_LEVELS[number]; export type TutorialCategory = typeof TUTORIAL_CATEGORIES[number]; export type TutorialDetailKey = keyof Pick< TutorialData, "level" | "framework" | "languages" | "categories" >;
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tutorial/index.ts
export * from "./details"; export { PgTutorial } from "./tutorial"; export { getTutorialStorage } from "./storage"; export * from "./types";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tutorial/tutorial.ts
import { PgCommon } from "../common"; import { PgExplorer, TupleFiles } from "../explorer"; import { PgRouter } from "../router"; import { PgView } from "../view"; import { declareUpdatable, updatable } from "../decorators"; import type { SerializedTutorialState, TutorialData, TutorialMetadata, TutorialState, } from "./types"; const defaultState: TutorialState = { pageNumber: null, pageCount: null, completed: null, view: null, data: null, }; const storage = { /** Relative path to the tutorial info */ PATH: ".tutorial.json", /** Read from storage and deserialize the data. */ async read(): Promise<TutorialState> { if (!PgTutorial.data || !PgTutorial.isStarted(PgTutorial.data.name)) { return { ...defaultState, data: PgTutorial.data }; } let serializedState: SerializedTutorialState; try { serializedState = await PgExplorer.fs.readToJSON(this.PATH); } catch { return { ...defaultState, data: PgTutorial.data }; } return { ...defaultState, ...serializedState, data: PgTutorial.data }; }, /** Serialize the data and write to storage. */ async write(state: TutorialState) { if (!PgTutorial.data || !PgTutorial.isStarted(PgTutorial.data.name)) { return; } // Don't use spread operator(...) because of the extra state const serializedState: SerializedTutorialState = { pageNumber: state.pageNumber, pageCount: state.pageCount, completed: state.completed, }; await PgExplorer.fs.writeFile(this.PATH, JSON.stringify(serializedState)); }, }; @updatable({ defaultState, storage }) class _PgTutorial { /** All tutorials */ static all: TutorialData[]; /** * Get the tutorial's data from its name. * * @param name tutorial name * @returns the tutorial's data if it exists */ static getTutorialData(name: string) { return this.all.find((t) => { return PgRouter.isPathsEqual( PgCommon.toKebabFromTitle(t.name), PgCommon.toKebabFromTitle(name) ); }); } /** * Get whether the given workspace name is a tutorial. * * @param name workspace name * @returns whether the given workspace name is a tutorial */ static isWorkspaceTutorial(name: string) { return _PgTutorial.all.some((t) => t.name === name); } /** * Get whether the current workspace is a tutorial. * * @returns whether the current workspace is a tutorial */ static isCurrentWorkspaceTutorial() { const workspaceName = PgExplorer.currentWorkspaceName; return workspaceName ? this.isWorkspaceTutorial(workspaceName) : false; } /** * Get all tutorial names the user has started. * * @returns user tutorial names */ static getUserTutorialNames() { if (!PgExplorer.allWorkspaceNames) { throw new Error("Explorer not initialized"); } return PgExplorer.allWorkspaceNames.filter(this.isWorkspaceTutorial); } /** * Get whether the user has started the given tutorial. * * @param name tutorial name * @returns whether the tutorial is started */ static isStarted(name: string) { return PgExplorer.allWorkspaceNames?.includes(name) ?? false; } /** * Get given tutorial's metadata from file system. * * @param name tutorial name * @returns tutorial metadata */ static async getMetadata(name: string) { return await PgExplorer.fs.readToJSON<TutorialMetadata>( PgCommon.joinPaths(PgExplorer.PATHS.ROOT_DIR_PATH, name, storage.PATH) ); } /** * Open the given tutorial. * * @param name tutorial name */ static async open(name: string) { const tutorialPath = `/tutorials/${PgCommon.toKebabFromTitle(name)}`; if (PgRouter.isPathsEqual(PgRouter.location.pathname, tutorialPath)) { // Open the tutorial pages view PgTutorial.update({ view: "main" }); // Sleep before setting the sidebar state to avoid flickering when the // current page modifies the sidebar state, e.g. inside `onMount` await PgCommon.sleep(0); PgView.setSidebarPage((state) => { if (state === "Tutorials") return "Explorer"; return state; }); } else { PgRouter.navigate(tutorialPath); } } /** * Start the current tutorial. * * This method can only start the current selected tutorial. * * @param props tutorial properties */ static async start( props: { files: TupleFiles; defaultOpenFile?: string } & Pick< TutorialMetadata, "pageCount" > ) { const tutorialName = PgTutorial.data?.name; if (!tutorialName) throw new Error("Tutorial is not selected"); if (!PgTutorial.isStarted(tutorialName)) { // Initial tutorial setup await PgExplorer.newWorkspace(tutorialName, { files: props.files, defaultOpenFile: props.defaultOpenFile, }); PgTutorial.update({ pageNumber: 1, pageCount: props.pageCount, completed: false, view: "main", }); } await this.open(tutorialName); } /** Finish the current tutorial. */ static finish() { PgTutorial.completed = true; PgView.setSidebarPage("Tutorials"); } } export const PgTutorial = declareUpdatable(_PgTutorial, { defaultState });
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/playnet/utils.ts
import type { WasmAccount } from "@solana-playground/playnet"; import { PgCommon } from "../common"; import { PgWeb3 } from "../web3"; export class PgPlaynetUtils { /** * Convert WASM account to `web3.js.AccountInfo` * * @param wasmAccount the account object that wasm-bindgen created * @returns `web3.js` parsed account */ static convertAccountInfo( wasmAccount: WasmAccount ): PgWeb3.AccountInfo<Buffer> { return { data: Buffer.from(wasmAccount.data), executable: wasmAccount.executable, lamports: PgCommon.bigintToInt(wasmAccount.lamports), owner: new PgWeb3.PublicKey(wasmAccount.owner.toBytes()), rentEpoch: PgCommon.bigintToInt(wasmAccount.rentEpoch), }; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/playnet/rpc.ts
import type { PgRpc, TransactionStatus } from "@solana-playground/playnet"; import { PgSerde } from "./serde"; import { PgPlaynetUtils } from "./utils"; import { PgBytes } from "../bytes"; import { PgCommon } from "../common"; import { PgConnection } from "../connection"; import { PgSettings } from "../settings"; import { Endpoint } from "../../../constants"; import type { OverridableConnection, RpcRequest, RpcResponse, RpcResponseWithContext, } from "./types"; import { PgWeb3 } from "../web3"; export class PgPlaynetRpc { /** * Get whether the given URL belongs to Playnet. * * @param url RPC endpoint * @returns whether the given URL starts with `Endpoint.PLAYNET` */ static isUrlPlaynet(url: string = PgSettings.connection.endpoint) { return url.startsWith(Endpoint.PLAYNET); } /** * Create a Playnet compatible connection instance. * * If `playnet` is specified: * 1. `window.fetch` will be overridden with a Playnet compatible method. * 2. A new connection instance will be created. * 3. The connection instance will be overridden to make it compatible with * Playnet. * 4. The connection instance will be returned. * * If `playnet` is **NOT** specified: * 1. `window.fetch` will be overridden with the default `fetch` method. * 2. `null` will be returned. * * @param rpc Playnet RPC * @returns the overridden connection or `null` */ static overrideConnection(rpc?: PgRpc) { // Override `window.fetch` const newFetch = this._overrideFetch(rpc); // Return early if `playnet` doesn't exist if (!rpc) return null; // Override connection to make it compatible with Playnet const connection: OverridableConnection = PgConnection.create({ fetch: newFetch, }); // @ts-ignore connection.confirmTransaction = async ( ...params: Parameters<PgWeb3.Connection["confirmTransaction"]> ) => { let signature; if (typeof params[0] === "string") { signature = params[0]; } else { const strat = params[0] as PgWeb3.BlockheightBasedTransactionConfirmationStrategy; signature = strat.signature; } const result = rpc.getSignatureStatuses([signature]); const status: TransactionStatus | undefined = result.statuses()[0]; if (!status) throw new Error("Transaction not found."); return { value: { err: status.error() ?? null }, context: { slot: PgCommon.bigintToInt(rpc.getSlot()) }, }; }; // @ts-ignore connection.onAccountChange = ( ...params: Parameters<PgWeb3.Connection["onAccountChange"]> ) => { const address = params[0].toBase58(); const cb = params[1]; let currentAccountInfo = PgPlaynetUtils.convertAccountInfo( rpc.getAccountInfo(address) ); const id = PgCommon.setIntervalOnFocus(() => { const newAccountInfo = PgPlaynetUtils.convertAccountInfo( rpc.getAccountInfo(address) ); if (!PgCommon.isEqual(currentAccountInfo, newAccountInfo)) { cb(newAccountInfo, { slot: PgCommon.bigintToInt(rpc.getSlot()), }); currentAccountInfo = newAccountInfo; } }, 3000); return id; }; connection.removeAccountChangeListener = async ( ...params: Parameters<PgWeb3.Connection["removeAccountChangeListener"]> ) => { const [id] = params; clearInterval(id); }; // `Connection` is not ready until this property is set connection.overridden = true; return connection; } /** * Override `window.fetch` method. * * @param rpc Playnet RPC. The default `fetch` will be used if `undefined`. * @returns the new or the default `fetch` method */ private static _overrideFetch(rpc?: PgRpc) { let newFetch; if (rpc) { newFetch = this._getNewFetch(rpc); } else { newFetch = defaultFetch; } // WASM client uses global `fetch` method window.fetch = newFetch; return newFetch; } /** * Create a new `fetch` function that detects and rebinds the requests of * Solana JSON-RPC methods. */ private static _getNewFetch(rpc: PgRpc) { return async (...args: Parameters<Window["fetch"]>) => { // Get whether the request url is playnet let parsedRequest: RpcRequest | null = null; if (typeof args[0] === "string") { const url = args[0]; if (this.isUrlPlaynet(url)) { const requestBody = args[1]?.body; if (requestBody) { parsedRequest = JSON.parse(requestBody.toString()); } } } else if (typeof args[0] === "object") { const request = args[0] as Request; if (this.isUrlPlaynet(request.url)) { parsedRequest = await request.json(); } } // Playnet response if (parsedRequest) return this._getPlaynetResponse(rpc, parsedRequest); // Response for every URL other than Playnet endpoint return await defaultFetch(...args); }; } /** * Create Solana JSON-RPC compatible RPC response for Playnet. * * This implementation allows Playnet to be used with `Connection` like a * normal cluster. */ private static _getPlaynetResponse(rpc: PgRpc, request: RpcRequest) { const slot = PgCommon.bigintToInt(rpc.getSlot()); const context = { apiVersion: "1.15.0", slot, }; switch (request.method) { case "getAccountInfo": { const [address] = request.params; const account = rpc.getAccountInfo(address); const lamports = PgCommon.bigintToInt(account.lamports); return this._createRpcResponse<"getAccountInfo">(request, context, { // @ts-ignore value: lamports === 0 ? null : { data: [PgBytes.toBase64(Buffer.from(account.data)), "base64"], executable: account.executable, lamports, owner: new PgWeb3.PublicKey(account.owner.toBytes()), rentEpoch: PgCommon.bigintToInt(account.rentEpoch), }, }); } case "getBalance": { const [address] = request.params; const account = rpc.getAccountInfo(address); return this._createRpcResponse<"getBalance">(request, context, { value: PgCommon.bigintToInt(account.lamports), }); } case "getBlockHeight": { return this._createRpcResponse<"getBlockHeight">(request, context, { result: PgCommon.bigintToInt(rpc.getBlockHeight()), }); } case "getFeeForMessage": { const [msgBase64] = request.params; const rustMsgBytes = PgSerde.serializeMsg(msgBase64); const fee = PgCommon.bigintToInt(rpc.getFeeForMessage(rustMsgBytes)); return this._createRpcResponse<"getFeeForMessage">(request, context, { result: fee === undefined ? undefined : { context: { slot }, value: fee, }, }); } case "getGenesisHash": { return this._createRpcResponse<"getGenesisHash">(request, context, { result: rpc.getGenesisHash(), }); } case "getLatestBlockhash": { const blockhashInfo = rpc.getLatestBlockhash(); return this._createRpcResponse<"getLatestBlockhash">(request, context, { value: { blockhash: blockhashInfo.blockhash(), lastValidBlockHeight: PgCommon.bigintToInt( blockhashInfo.lastValidBlockHeight() ), }, }); } case "getMinimumBalanceForRentExemption": { const [dataLen] = request.params; return this._createRpcResponse<"getMinimumBalanceForRentExemption">( request, context, { result: PgCommon.bigintToInt( rpc.getMinimumBalanceForRentExemption(dataLen) ), } ); } case "getRecentBlockhash": { return this._createRpcResponse<"getRecentBlockhash">(request, context, { value: { blockhash: rpc.getLatestBlockhash().blockhash(), feeCalculator: { lamportsPerSignature: 5000 }, }, }); } case "getSignatureStatuses": { const [signatures] = request.params; const statusesResult = rpc.getSignatureStatuses(signatures); const statuses: (TransactionStatus | undefined)[] = statusesResult.statuses(); return this._createRpcResponse<"getSignatureStatuses">( request, context, { result: { context, value: statuses.map((status) => status ? { confirmationStatus: (() => { switch (status.confirmationStatus) { case 0: return "processed"; case 1: return "confirmed"; case 2: return "finalized"; default: return "finalized"; } })() as PgWeb3.TransactionConfirmationStatus, confirmations: status.confirmations!, err: status.error() ?? null, slot: PgCommon.bigintToInt(status.slot), } : null ), }, } ); } case "getSlot": { return this._createRpcResponse<"getSlot">(request, context, { result: slot, }); } case "getTransaction": { const [signature, options] = request.params; const getTxResult = rpc.getTransaction(signature); const meta = getTxResult.meta(); // web3.js expects tx object but solana-cli expects base64 encoded tx // string. We get base64 tx string from `playnet` and convert it to // `VersionedTransaction` let tx: | [string, string] | PgWeb3.VersionedTransactionResponse["transaction"] = [ getTxResult.transaction(), "base64", ]; if (!options?.encoding) { const versionedTx = PgWeb3.VersionedTransaction.deserialize( PgBytes.fromBase64(tx[0]) ); const signatures = versionedTx.signatures.map((signatureBytes) => { return PgBytes.toBase58(Buffer.from(signatureBytes)); }); tx = { message: versionedTx.message, signatures, }; } const convertBalances = (bigintBalances: BigUint64Array) => { const balances = []; for (const i in bigintBalances) { balances.push(PgCommon.bigintToInt(bigintBalances[i])); } return balances; }; return this._createRpcResponse<"getTransaction">(request, context, { // @ts-ignore result: getTxResult.exists() ? { slot, transaction: tx, meta: { fee: PgCommon.bigintToInt(meta.fee()), innerInstructions: meta.innerInstructions(), preBalances: convertBalances(meta.preBalances()), postBalances: convertBalances(meta.postBalances()), logMessages: meta.logs(), preTokenBalances: meta.preTokenBalances(), postTokenBalances: meta.postTokenBalances(), err: meta.err() ?? null, loadedAddresses: meta.loadedAddresses(), computeUnitsConsumed: PgCommon.bigintToInt( meta.computeUnitsConsumed() ), rewards: [], status: meta.err() ? { Err: meta.err() } : { Ok: null }, }, blockTime: PgCommon.bigintToInt(getTxResult.blockTime()), version: getTxResult.version() ?? "legacy", } : null, }); } case "requestAirdrop": { const [address, lamports] = request.params; const airdropResult = rpc.requestAirdrop(address, BigInt(lamports)); this._handleError(airdropResult); return this._createRpcResponse<"requestAirdrop">(request, context, { result: airdropResult.txHash(), }); } case "sendTransaction": { const [txBase64] = request.params; const rustTxBytes = PgSerde.serializeTx(txBase64); const txResult = rpc.sendTransaction(rustTxBytes); this._handleError(txResult); return this._createRpcResponse<"sendTransaction">(request, context, { result: txResult.txHash(), }); } case "simulateTransaction": { const [txBase64] = request.params; const rustTxBytes = PgSerde.serializeTx(txBase64); const simulationResult = rpc.simulateTransaction(rustTxBytes); const returnData = simulationResult.returnData(); return this._createRpcResponse<"simulateTransaction">( request, context, { result: { context, value: { err: simulationResult.error() ?? null, logs: simulationResult.logs(), unitsConsumed: PgCommon.bigintToInt( simulationResult.unitsConsumed() ), returnData: returnData ? { programId: returnData.programId.toString(), data: [ PgBytes.toBase64(Buffer.from(returnData.data)), "base64", ], } : null, accounts: null, }, }, } ); } default: { throw new Error(`Method: '${request.method}' is not yet implemented.`); } } } /** Create `web3.js` compatible responses with type safety. */ private static _createRpcResponse<K extends keyof PgWeb3.Connection>( request: RpcRequest, context: RpcResponseWithContext<K>["result"]["context"], data: { result?: RpcResponse<K>["result"]; value?: RpcResponseWithContext<K>["result"]["value"]; } ) { const responseBody: RpcResponse<K> | RpcResponseWithContext<K> = { id: request.id, jsonrpc: request.jsonrpc, result: data.result !== undefined ? data.result! : { context, value: data.value!, }, }; // WASM URL parsing fails if the `Response.url` is empty return Object.defineProperty( new Response(JSON.stringify(responseBody)), "url", { value: Endpoint.PLAYNET } ); } /** * Handle WASM errors. * * @param result WASM result object that has `error()` method */ private static _handleError<R extends { error: () => string | undefined }>( result: R ) { const error = result.error(); if (error) { throw new Error(error); } } } /** Default `window.fetch` method */ const defaultFetch = fetch;
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/playnet/types.ts
import type { PgWeb3 } from "../web3"; /** Playnet RPC request */ export interface RpcRequest { jsonrpc: string; method: keyof PgWeb3.Connection; params: any[]; id: string; } /** Playnet RPC response */ export type RpcResponse<K extends keyof PgWeb3.Connection> = { jsonrpc: string; result: PgWeb3.Connection[K] extends (...args: any[]) => any ? Awaited<ReturnType<PgWeb3.Connection[K]>> : null; id: string; }; /** Playnet RPC response with context */ export type RpcResponseWithContext<K extends keyof PgWeb3.Connection> = { jsonrpc: string; result: { context: { apiVersion: string; slot: number }; value: PgWeb3.Connection[K] extends (...args: any[]) => any ? Awaited<ReturnType<PgWeb3.Connection[K]>> : null; }; id: string; }; /** Overridable `Connection` instance */ export type OverridableConnection = PgWeb3.Connection & { overridden?: boolean; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/playnet/serde.ts
import { PgBytes } from "../bytes"; import { PgWeb3 } from "../web3"; export class PgSerde { /** * Serialize the base64 transaction string to make it compatible for Serde * to deserialize it from WASM. * * @param txBase64 base64 encoded transaction string * @returns Rust Serde serialized transaction string */ static serializeTx(txBase64: string) { // Decode base64 tx and get tx object const txBuffer = PgBytes.fromBase64(txBase64); const tx = PgWeb3.Transaction.from(txBuffer); // Convert tx object into Rust Serde format const rustTx = this._convertTx(tx); // Serialize Rust tx object return this._serializeObject(rustTx); } /** * Serialize the base64 message string to make it compatible for Serde to * deserialize it from WASM. * * @param msgBase64 base64 encoded message string * @returns Rust Serde serialized message string */ static serializeMsg(msgBase64: string) { // Decode base64 msg and get msg object const msgBuffer = PgBytes.fromBase64(msgBase64); const msg = PgWeb3.Message.from(msgBuffer); // Convert msg object into Rust Serde format const rustMsg = this._convertMsg(msg); // Serialize Rust msg object return this._serializeObject(rustMsg); } /** Serialize the given object to bytes. */ private static _serializeObject(obj: Object) { return Uint8Array.from(Buffer.from(JSON.stringify(obj))); } /** Convert the given transaction to a `serde` compatible transaction. */ private static _convertTx(tx: PgWeb3.Transaction) { return { signatures: this._convertToSerdeArray( tx.signatures .filter((item) => item.signature !== null) .map((item) => Array.from(item.signature!)) ), message: this._convertMsg(tx.compileMessage()), }; } /** Convert the given message to a `serde` compatible message. */ private static _convertMsg(msg: PgWeb3.Message) { return { header: msg.header, accountKeys: this._convertToSerdeArray( msg.accountKeys.map((key) => Array.from(key.toBytes())) ), recentBlockhash: Array.from(PgBytes.fromBase58(msg.recentBlockhash)), instructions: this._convertToSerdeArray( msg.instructions.map((ix) => ({ ...ix, accounts: this._convertToSerdeArray(ix.accounts), data: this._convertToSerdeArray( Array.from(PgBytes.fromBase58(ix.data)) ), })) ), }; } /** Converts the array according to `short_vec` length serialization. */ private static _convertToSerdeArray<T>(arr: T[]): [number[], ...T[]] { return [ arr.length < 0x80 ? [arr.length] : [0x80 + (arr.length % 0x80), Math.floor(arr.length / 0x80)], ...arr, ]; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/playnet/index.ts
export { PgPlaynet } from "./playnet"; export * from "./types";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/playnet/playnet.ts
import { PgPlaynetRpc } from "./rpc"; import { PgCommon } from "../common"; import { PgExplorer } from "../explorer"; import { PgPackage } from "../package"; import { EventName } from "../../../constants"; import type { OverridableConnection } from "./types"; export class PgPlaynet { /** Overridable Playnet connection */ static connection: OverridableConnection | null; /** * Initialize Playnet and apply the necessary changes for the client to be * able to interact with Playnet via JSON-RPC endpoints. * * This method returns early if Playnet instance already exists. */ static async init() { if (this._playnet) return; // Get the saved data from IndexedDB const saveData = await this._getSaveData(); // Only load when Playnet needs to get initialized const { Playnet } = await PgPackage.import("playnet"); const playnet = new Playnet(saveData); this._playnet = playnet; // Override `fetch` and `connection` this.connection = PgPlaynetRpc.overrideConnection(this._playnet.rpc); // Dispatch `init` event to create a new connection object PgCommon.createAndDispatchCustomEvent(EventName.PLAYNET_ON_DID_INIT); // Save Playnet data periodically this._SAVE_INTERVAL_ID = PgCommon.setIntervalOnFocus(() => { this._save(); }, this._SAVE_INTERVAL_MS); } /** * Destroy the Playnet instance by: * 1. Clear save interval. * 2. Save data. * 3. Set `connection`and `fetch` to default. * 4. Free WASM memory. * * This method returns early if Playnet instance doesn't exist. */ static async destroy() { if (!this._playnet) return; // Clear save interval if (this._SAVE_INTERVAL_ID) { clearInterval(this._SAVE_INTERVAL_ID); } // Save Playnet instance data await this._save(); // Reset to defaults this.connection = PgPlaynetRpc.overrideConnection(); // Free memory this._playnet.free(); this._playnet = null; } /** {@link PgPlaynetRpc.isUrlPlaynet} */ static isUrlPlaynet = PgPlaynetRpc.isUrlPlaynet; /** * @param cb callback function to run after Playnet has been initialialized * @returns a dispose function to clear the event */ static onDidInit(cb: () => any) { return PgCommon.onDidChange({ cb, eventName: EventName.PLAYNET_ON_DID_INIT, }); } /** Static Playnet instance */ private static _playnet: import("@solana-playground/playnet").Playnet | null = null; /** Playnet related paths in fs */ private static _PATHS = { DIR: PgCommon.joinPaths(PgExplorer.PATHS.ROOT_DIR_PATH, ".playnet"), get SAVE_DATA() { return PgCommon.joinPaths(this.DIR, "data.json"); }, }; /** Save the Playnet instance data to IndexedDB at this interval */ private static _SAVE_INTERVAL_MS = 30 * 1000; /** Data saving interval that must be cleared while destroying the Playnet instance */ private static _SAVE_INTERVAL_ID: NodeJS.Timer | null; /** Save the current playnet data */ private static async _save() { if (!this._playnet) return; try { await PgExplorer.fs.writeFile( this._PATHS.SAVE_DATA, this._playnet.getSaveData(), { createParents: true } ); } catch (e: any) { console.log("Couldn't save Playnet data:", e.message); } } /** * Get the saved data from IndexedDB * * @returns saved data as `string` or `undefined` if it doesn't exist */ private static async _getSaveData() { try { return await PgExplorer.fs.readToString(this._PATHS.SAVE_DATA); } catch (e: any) { console.log("Couldn't get Playnet data:", e.message); } } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/decorators/derivable.ts
import { addInit, addOnDidChange, getChangePropName, INTERNAL_STATE_PROPERTY, } from "./common"; import { PgCommon } from "../common"; import type { Initialize, OnDidChangeDefault, OnDidChangeProperty, } from "./types"; import type { Disposable } from "../types"; /** * Make the given static class derivable. * * This decorator defines properties from the given state keys and they will be * updated based on the given `onChange` event(s). * * The properties are read-only and the only way to update the values is * to trigger the given `onChange` method(s). */ export function derivable<T extends Derivable>( deriveState: () => { [key: string]: T } ) { return (sClass: any) => { // Add `init` method addInit(sClass, () => { const state = deriveState(); // Add `onDidChange` methods addOnDidChange(sClass, state); const disposables: Disposable[] = []; for (const prop in state) { // Define getter if (!Object.hasOwn(sClass, prop)) { Object.defineProperty(sClass, prop, { get: () => sClass[INTERNAL_STATE_PROPERTY][prop], }); } const derivable = state[prop]; derivable.onChange = PgCommon.toArray(derivable.onChange); derivable.onChange = derivable.onChange.map((onChange) => { if (typeof onChange === "string") { return sClass[getChangePropName(onChange)]; } return onChange; }); const disposable = PgCommon.batchChanges(async (value) => { sClass[INTERNAL_STATE_PROPERTY][prop] = await derivable.derive(value); // Prop change event PgCommon.createAndDispatchCustomEvent( sClass._getChangeEventName(prop), sClass[prop] ); // Main change event PgCommon.createAndDispatchCustomEvent( sClass._getChangeEventName(), sClass[INTERNAL_STATE_PROPERTY] ); }, derivable.onChange as Exclude<OnChange, string>[]); disposables.push(disposable); } return { dispose: () => disposables.forEach(({ dispose }) => dispose()), }; }); }; } /** Either `onChange` method or a string that will be checked from the state */ type OnChange<T = unknown> = ((cb: (value?: T) => void) => Disposable) | string; /** Derivable property declaration */ type Derivable<T = any, R = unknown> = { /** The method that the value will be derived from. */ derive: (value: T) => R; /** Derive method will be called whenever there is a change. */ onChange: OnChange<T> | OnChange[]; }; /** Derivable state properties */ type DerivableState<T> = { readonly // eslint-disable-next-line @typescript-eslint/no-unused-vars [K in keyof T]: T[K] extends Derivable<infer _, infer R> ? Awaited<R> : never; }; /** * Create a derivable. * * This function is a type helper function. */ export const createDerivable = <T, R>(derivable: Derivable<T, R>) => derivable; /** * Add necessary types to the given derivable static class. * * @param sClass static class * @param derive derive properties that will be added to the given class * @returns the static class with correct types */ export const declareDerivable = <C, T>(sClass: C, derive: () => T) => { return sClass as Omit<C, "prototype"> & Initialize & DerivableState<T> & OnDidChangeDefault<DerivableState<T>> & OnDidChangeProperty<DerivableState<T>>; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/decorators/common.ts
import { PgCommon } from "../common"; import type { OnDidChangeDefault } from "./types"; import type { Arrayable, Disposable, SyncOrAsync } from "../types"; /** Private state property */ export const INTERNAL_STATE_PROPERTY = "_state"; /** The property name for keeping track of whether the class has been initialized */ export const IS_INITIALIZED_PROPERTY = "_isinitialized"; /** Change event method name prefix */ export const ON_DID_CHANGE = "onDidChange"; /** Get the change event property name. */ export const getChangePropName = (prop: string) => { return ON_DID_CHANGE + PgCommon.capitalize(prop); }; /** * Add `init` property to the given static class. * * @param sClass static class * @param init init method to implement */ export const addInit = (sClass: any, init: () => SyncOrAsync<Disposable>) => { sClass[INTERNAL_STATE_PROPERTY] ??= {}; const previousInit = sClass.init; sClass.init = async () => { const disposables: Disposable[] = []; if (previousInit) { const disposable = await previousInit(); disposables.push(disposable); } const disposable = await init(); disposables.push(disposable); sClass[IS_INITIALIZED_PROPERTY] = true; return { dispose: () => disposables.forEach(({ dispose }) => dispose()), }; }; }; /** * Add `onDidChange` methods to the given static class. * * @param sClass static class * @param state default state */ export const addOnDidChange = ( sClass: any, state: { [key: string]: unknown } ) => { // Batch main change event (sClass as OnDidChangeDefault<unknown>).onDidChange = ( cb: (value: unknown) => void ) => { return PgCommon.batchChanges( () => cb(sClass[INTERNAL_STATE_PROPERTY]), [onDidChange] ); }; // Main change event const onDidChange = (cb: (value: unknown) => void) => { return PgCommon.onDidChange({ cb, eventName: sClass._getChangeEventName(), initialRun: sClass[IS_INITIALIZED_PROPERTY] ? { value: sClass[INTERNAL_STATE_PROPERTY] } : undefined, }); }; // Property change events for (const prop in state) { sClass[getChangePropName(prop)] = (cb: (value: unknown) => unknown) => { return PgCommon.onDidChange({ cb, eventName: sClass._getChangeEventName(prop), initialRun: sClass[IS_INITIALIZED_PROPERTY] ? { value: sClass[prop] } : undefined, }); }; } // Get custom event name sClass._getChangeEventName = (name?: Arrayable<string>) => { if (Array.isArray(name)) name = name.join("."); // `sClass.name` is minified to something like `e` in production builds // which cause collision with other classes and this only happens with the // main `onDidChange` method because the child change methods have `name` // appended. This results with infinite loops when using any of the main change // events as a dependency for a derivable, e.g. using `PgConnection.onDidChange` // as a dependency for `PgProgramInfo.onChain` triggers an infinite loop which // is only reproducable in production builds. // See: https://github.com/webpack/webpack/issues/8132 // https://github.com/mishoo/UglifyJS/issues/3263 // // The solution is to avoid minimizing the decorator class names in production // by overriding the Terser plugin's `keep_classnames` and `keep_fnames` option // to include only the class/function names(decorator classes can be transpiled // to either classes or functions depending on the browser version) that start // with "_Pg". return "ondidchange" + sClass.name + (name ?? ""); }; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/decorators/types.ts
import type { ON_DID_CHANGE } from "./common"; import type { Disposable, SyncOrAsync } from "../types"; /** `init` prop */ export type Initialize = { /** Initializer that returns a disposable */ init(): SyncOrAsync<Disposable>; }; /** Default `onDidChange` type */ export type OnDidChangeDefault<T> = { /** * @param cb callback function to run after the change * @returns a dispose function to clear the event */ onDidChange(cb: (value: T) => void): Disposable; }; /** Non-recursive `onDidChange${propertyName}` method types */ export type OnDidChangeProperty<T> = { [K in keyof T as `${typeof ON_DID_CHANGE}${Capitalize<K>}`]: ( cb: (value: T[K]) => void ) => Disposable; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/decorators/index.ts
export * from "./derivable"; export * from "./migratable"; export * from "./updatable";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/decorators/updatable.ts
import { PgCommon } from "../common"; import { addInit, addOnDidChange, INTERNAL_STATE_PROPERTY, IS_INITIALIZED_PROPERTY, ON_DID_CHANGE, } from "./common"; import type { Initialize, OnDidChangeDefault, OnDidChangeProperty, } from "./types"; import type { Disposable, SyncOrAsync } from "../types"; /** Updatable decorator */ type Update<T> = { /** Update state */ update(params: Partial<T>): void; }; /** Recursive `onDidChange${propertyName}` method types */ type OnDidChangePropertyRecursive<T, U = FlattenObject<T>> = { [K in keyof U as `${typeof ON_DID_CHANGE}${Capitalize<K>}`]: ( cb: (value: U[K]) => void ) => Disposable; }; /** Custom storage implementation */ type CustomStorage<T> = { /** Read from storage and deserialize the data. */ read(): SyncOrAsync<T>; /** Serialize the data and write to storage. */ write(state: T): SyncOrAsync<void>; }; /** * Make a static class updatable. * * This decorator defines getters for the given prop names and adds an * `onDidChange${propertyName}` method for each prop. * * `update` method is responsible for both updating the state and dispatching * change events. * * NOTE: Types have to be added separately as decorators don't have proper * type support. */ export function updatable<T>(params: { /** Default value to set */ defaultState: Required<T>; /** Storage that is responsible with de/serialization */ storage: CustomStorage<T>; /** Whether to add proxy setters recursively */ recursive?: boolean; }) { return (sClass: any) => { // Add `onDidChange` methods addOnDidChange(sClass, params.defaultState); // Add `init` method addInit(sClass, async () => { const state: T = await params.storage.read(); // Set the default if any prop is missing(recursively) const setMissingDefaults = (state: any, defaultState: any) => { if (Array.isArray(state)) return; for (const prop in defaultState) { if (state[prop] === undefined) { state[prop] = defaultState[prop]; } else if ( typeof state[prop] === "object" && defaultState[prop] !== null ) { setMissingDefaults(state[prop], defaultState[prop]); } } }; setMissingDefaults(state, params.defaultState); // Remove extra properties if a prop was removed(recursively) const removeExtraProperties = (state: any, defaultState: any) => { if (Array.isArray(state)) return; for (const prop in state) { if (defaultState[prop] === undefined) { delete state[prop]; } else if ( typeof state[prop] === "object" && defaultState[prop] !== null ) { removeExtraProperties(state[prop], defaultState[prop]); } } }; removeExtraProperties(state, params.defaultState); // Set the initial state sClass.update(state); return sClass.onDidChange((state: T) => params.storage.write(state)); }); // Add `update` method if (params.recursive) { (sClass as Update<T>).update = (updateParams: Partial<T>) => { for (const prop in updateParams) { update(prop, updateParams[prop]); if (typeof sClass[prop] === "object" && sClass[prop] !== null) { sClass[prop] = defineSettersRecursively({ sClass, getter: sClass[prop], internal: sClass[INTERNAL_STATE_PROPERTY][prop], propNames: [prop], }); } } }; } else { (sClass as Update<T>).update = (updateParams: Partial<T>) => { for (const prop in updateParams) { update(prop, updateParams[prop]); } }; } // Common update method const update = (prop: keyof T, value?: T[keyof T]) => { if (value === undefined) return; // Define getter and setter once if (!Object.hasOwn(sClass, prop)) { Object.defineProperty(sClass, prop, { get: () => sClass[INTERNAL_STATE_PROPERTY][prop], set: (value: T[keyof T]) => { sClass[INTERNAL_STATE_PROPERTY][prop] = value; // Change event PgCommon.createAndDispatchCustomEvent( sClass._getChangeEventName(prop), value ); // Dispatch the main update event PgCommon.createAndDispatchCustomEvent( sClass._getChangeEventName(), sClass[INTERNAL_STATE_PROPERTY] ); }, }); } // Trigger the setter sClass[prop] = value; }; }; } /** Define proxy setters for properties recursively. */ const defineSettersRecursively = ({ sClass, getter, internal, propNames, }: { sClass: any; getter: any; internal: any; propNames: string[]; }) => { getter = new Proxy(internal, { set(target: any, prop: string, value: any) { target[prop] = value; // Setting a new value should dispatch a change event for all of // the parent objects. // Example: // const obj = { nested: { number: 1 } }; // obj.a.b = 2; -> obj.OnDidChangeNestedNumber, obj.OnDidChangeNested, obj.onDidChange // 1. [nested, number].reduce // 2. [nested, nested.number].reverse // 3. [nested.number, nested].forEach propNames .concat([prop]) .reduce((acc, cur, i) => { acc.push(propNames.slice(0, i).concat([cur]).join(".")); return acc; }, [] as string[]) .reverse() .forEach((prop) => { PgCommon.createAndDispatchCustomEvent( sClass._getChangeEventName(prop), PgCommon.getProperty(sClass[INTERNAL_STATE_PROPERTY], prop) ); }); // Dispatch the main update event PgCommon.createAndDispatchCustomEvent( sClass._getChangeEventName(), sClass[INTERNAL_STATE_PROPERTY] ); return true; }, }); for (const prop in getter) { const currentPropNames = [...propNames, prop]; // Change event handlers const onDidChangeEventName = ON_DID_CHANGE + currentPropNames.reduce( (acc, cur) => acc + cur[0].toUpperCase() + cur.slice(1), "" ); sClass[onDidChangeEventName] ??= (cb: (value: unknown) => unknown) => { return PgCommon.onDidChange({ cb, eventName: sClass._getChangeEventName(currentPropNames), initialRun: sClass[IS_INITIALIZED_PROPERTY] ? { value: getter[prop] } : undefined, }); }; // Recursively update if (typeof getter[prop] === "object" && getter[prop] !== null) { getter[prop] = defineSettersRecursively({ sClass, getter: getter[prop], internal: internal[prop], propNames: currentPropNames, }); } else { // Trigger the setter // eslint-disable-next-line no-self-assign getter[prop] = getter[prop]; } } return getter; }; /** * Flatten the properties of the given object. * * ## Input: * ```ts * { * isReady: boolean; * nested: { * id: number; * double: { * name: string; * }; * }; * } * ``` * * ## Output: * ```ts * { * isReady: boolean; * nested: { * id: number; * double: { * name: string; * }; * } * nestedId: number; * nestedDouble: { * name: string; * } * nestedDoubleName: string; * } * ``` */ type FlattenObject<T, U = PropertiesToUnionOfTuples<T>> = MapNestedProperties< // This check solves `Type instantiation is excessively deep and possibly infinite.` U extends [string[], unknown] ? U : never >; /** Maps the given tuple to an object */ type MapNestedProperties<T extends [string[], unknown]> = { [K in T as Uncapitalize<JoinCapitalized<K[0]>>]: K[1]; }; /** Join the given string array capitalized */ type JoinCapitalized<T extends string[]> = T extends [ // infer Head extends string, // ...infer Tail extends string[] infer Head, ...infer Tail ] ? Head extends string ? Tail extends string[] ? `${Capitalize<Head>}${JoinCapitalized<Tail>}` : never : never : ""; /** Map the property values to a union of tuples */ type PropertiesToUnionOfTuples<T, Acc extends string[] = []> = { [K in keyof T]: T[K] extends object ? [[...Acc, K], T[K]] | PropertiesToUnionOfTuples<T[K], [...Acc, K]> : [[...Acc, K], T[K]]; }[keyof T]; /** * Add the necessary types to the given updatable static class. * * @param sClass static class * @param options type helper options * @returns the static class with correct types */ export const declareUpdatable = <C, T, R>( sClass: C, options?: { defaultState: T; recursive?: R } ) => { return sClass as unknown as Omit<C, "prototype"> & T & Initialize & Update<T> & OnDidChangeDefault<T> & (R extends boolean ? OnDidChangePropertyRecursive<T> : OnDidChangeProperty<T>); };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/decorators/migratable.ts
import type { SyncOrAsync } from "../types"; /** * Run the given `migrate` function as soon as the static class module has been * imported. * * Migration is useful for making changes to how the data is stored. */ export function migratable(migrate: () => SyncOrAsync<void>) { migrate(); return (_sClass: any) => {}; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/history.ts
/** Manage terminal history */ export class PgHistory { /** Maximum allowed size */ private _size: number; /** Cursor index */ private _cursor = 0; /** All history entries */ private _entries: string[] = []; constructor(size: number) { this._size = size; } /** Get all entries. */ getEntries() { return this._entries; } /** Push an entry while maintaining the `size` limit. */ push(entry: string) { // Skip empty entries or special last cmd if (!entry || entry === "!!") return; // If it's a duplicate entry, change index const entryIndex = this._entries.indexOf(entry); if (entryIndex !== -1) { const isEntryLastIndex = entryIndex === this._entries.length - 1; this._entries = this._entries .slice(0, entryIndex) .concat( this._entries.slice(isEntryLastIndex ? entryIndex : entryIndex + 1) ); } // Only push if the last entry is not the same if ( !this._entries.length || this._entries[this._entries.length - 1] !== entry ) { this._entries.push(entry); } // Keep track of entries if (this._entries.length > this._size) { this._entries = this._entries.slice(1); } this._cursor = this._entries.length; } /** * Set the cursor to the previous entry if it exists. * * @returns the previous entry if it exists */ getPrevious() { const index = Math.max(0, this._cursor - 1); this._cursor = index; if (this._entries.length > index) return this._entries[index]; } /** * Set the cursor to the next entry if it exists. * * @returns the next entry if it exists */ getNext() { const index = Math.min(this._entries.length, this._cursor + 1); this._cursor = index; if (this._entries.length >= index) return this._entries[index]; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/autocomplete.ts
import { getIsOption, hasTrailingWhitespace, parse } from "./utils"; import { PgCommon } from "../common"; import type { Getable } from "../types"; /** Autocomplete handler input type */ type AutocompleteHandler = | AutocompleteHandlerCallback | AutocompleteHandlerObject | AutocompleteHandlerArray; /** Callback to create the autocomplete candidates based on the given tokens */ type AutocompleteHandlerCallback = ( tokens: string[], index: number ) => string[]; /** Nested command definitions */ type AutocompleteHandlerObject = object; /** Entry based handlers */ type AutocompleteHandlerArray = Getable<string[]>; /** Terminal autocomplete functionality */ export class PgAutocomplete { /** Normalized (callback) autocomplete handlers */ private _handlers: AutocompleteHandlerCallback[] = []; constructor(handlers: AutocompleteHandler[]) { this._addHandler(...handlers); } /** * Get whether there is at least one handler * * @returns whether there is at least one handler */ hasAnyHandler() { return this._handlers.length > 0; } /** * Temporarily set autocomplete handlers to the given handler. * * @param handler handler to set * @param opts handler options: * - `append`: whether to append the handler to the existing handlers * @returns an object with `restore` callback to restore the handlers */ temporarilySetHandlers( handler: AutocompleteHandler, opts?: { append?: boolean } ) { const initialHandlers = this._handlers; this._handlers = opts?.append ? [...initialHandlers] : []; this._addHandler(handler); return { restore: () => { this._handlers = initialHandlers; }, }; } /** * Collect the autocomplete canditates from the given input. * * @param input terminal input * @returns the sorted autocomplete candidates for the given input */ getCandidates(input: string) { const tokens = parse(input); let index = tokens.length - 1; // Empty expressions if (!input.trim()) index = 0; // Expressions with danging space else if (hasTrailingWhitespace(input)) index += 1; // Collect all auto-complete candidates from the callbacks const candidates = this._handlers.reduce((acc, cb) => { try { const candidates = cb(tokens, index); return acc.concat(candidates); } catch (e) { console.log("Autocomplete error:", e); return acc; } }, [] as string[]); return ( // Candidates might include duplicates PgCommon.toUniqueArray(candidates) // Sort for consistent output .sort((a, b) => { // Prioritize arguments over options if (getIsOption(a) && !getIsOption(b)) return 1; if (getIsOption(b)) return -1; return a.localeCompare(b); }) // Only show options when the last token starts with '-' .filter((candidate) => { if (getIsOption(candidate)) { const lastToken = tokens.at(-1); if (lastToken) { if (candidate.startsWith("--")) return lastToken.startsWith("--"); if (candidate.startsWith("-")) return lastToken.startsWith("-"); } } return true; }) ); } /** * Add the given handler(s) with normalization i.e. converting all handlers * to a callback handler. * * @param handlers handler(s) to add */ private _addHandler(...handlers: AutocompleteHandler[]) { this._handlers.push( ...handlers.map((handler): AutocompleteHandlerCallback => { if (Array.isArray(handler) || typeof handler === "function") { // Example: // // handler = ["anchor idl init", "anchor idl upgrade"] // // index: 0 // tokens: [] // return: ["anchor"] // // index: 1 // tokens: ["anchor"] // return: ["idl"] // // index: 2 // tokens: ["anchor", "idl"] // return: ["init", "upgrade"] return (tokens, index) => { return (PgCommon.callIfNeeded(handler) as string[]) .map(parse) .map((entryTokens) => { const lastIndex = tokens.length - 1; const matches = tokens.every((token, i) => i === lastIndex && index <= lastIndex ? entryTokens[i]?.startsWith(token) : token === entryTokens[i] ); if (matches) return entryTokens.at(index); return null; }) .filter(PgCommon.isNonNullish); }; } // Example: // // handler = { // anchor: { // idl: { // init: {}, // upgrade: {} // } // } // } // // index: 0 // tokens: [] // return: ["anchor"] // // index: 1 // tokens: ["anchor"] // return: ["idl"] // // index: 2 // tokens: ["anchor", "idl"] // return: ["init", "upgrade"] return (tokens, index) => { const recursivelyGetCandidates = (obj: any, i = 0): string[] => { if (i > index) return []; const candidates = []; for (const [key, value] of PgCommon.entries(obj)) { // Argument values if (PgCommon.isInt(key)) { // Skip options if (tokens[i] && getIsOption(tokens[i])) continue; if (index - i === +key && value.values) { const token = tokens[index]; const values: string[] = PgCommon.callIfNeeded(value.values); const filteredValues = values.filter( (v) => !token || v.startsWith(token) ); candidates.push(...filteredValues); } else if (value.multiple) { candidates.push(...recursivelyGetCandidates(obj, i + 1)); } else { // Options are also valid after arguments const opts = Object.entries(obj).reduce( (acc, [prop, val]) => { if (getIsOption(prop)) acc[prop] = val; return acc; }, {} as typeof obj ); // The completion index for the next option is the sum of // `i` and how many previous arguments exist. // // The calculation below assumes all arguments have been // passed beforehand, which means option completions between // arguments won't work. Supplying options before or after // all arguments work expected. // // TODO: Calculate how many arguments exist properly to make // option completions between arguments work const argAmount = Object.keys(obj).filter( PgCommon.isInt ).length; candidates.push( ...recursivelyGetCandidates(opts, i + argAmount) ); } } // Subcommands or options else if (!tokens[i] || key.startsWith(tokens[i])) { // Current key and doesn't exist previously in tokens if (i === index && !tokens.slice(0, i).includes(key)) { candidates.push(key); } // Next candidates if (key === tokens[i]) { if (getIsOption(key)) { // Remove long/short to not suggest duplicates if (value.other) { obj = { ...obj }; delete obj[value.other]; } if (index - i === 1 && value.values) { const token = tokens[index]; const values: string[] = PgCommon.callIfNeeded( value.values ); const filteredValues = values.filter( (v) => !token || v.startsWith(token) ); candidates.push(...filteredValues); } candidates.push( ...recursivelyGetCandidates( obj, // Decide the next index based on whether the option // takes in a value value.takeValue ? i + 2 : i + 1 ) ); } else { // Subcommand candidates.push(...recursivelyGetCandidates(value, i + 1)); } } } } return candidates; }; return recursivelyGetCandidates(handler); }; }) ); } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/utils.ts
/** * Parse the given input to tokens. * * @param input command input * @returns the parsed tokens */ export const parse = (input: string) => { const tokens = []; let currentTokenIndex = 0; let isInQuotes = false; for (const char of input) { switch (char) { case '"': case "'": isInQuotes = !isInQuotes; break; case " ": if (!isInQuotes) currentTokenIndex++; else if (!tokens[currentTokenIndex]) tokens[currentTokenIndex] = char; else tokens[currentTokenIndex] += char; break; default: if (!tokens[currentTokenIndex]) tokens[currentTokenIndex] = char; else tokens[currentTokenIndex] += char; } } return tokens; }; /** * @returns whether the given token is a command option */ export const getIsOption = (token: string) => token.startsWith("-"); /** * Get the closest *left* word boundary of the given input at the given offset. */ export const closestLeftBoundary = (input: string, offset: number) => { const found = getWordBoundaries(input, true) .reverse() .find((x) => x < offset); return found === undefined ? 0 : found; }; /** * Get the closest *right* word boundary of the given input at the given offset. */ export const closestRightBoundary = (input: string, offset: number) => { const found = getWordBoundaries(input, false).find((x) => x > offset); return found === undefined ? input.length : found; }; /** Get all the word boundaries from the given input. */ const getWordBoundaries = (input: string, leftSide: boolean = true) => { let match; const words = []; const regex = /\w+/g; match = regex.exec(input); while (match) { if (leftSide) words.push(match.index); else words.push(match.index + match[0].length); match = regex.exec(input); } return words; }; /** * Checks if there is an incomplete input * * An incomplete input is considered: * - An input that contains unterminated single quotes * - An input that contains unterminated double quotes * - An input that ends with "\" * - An input that has an incomplete boolean shell expression (&& and ||) * - An incomplete pipe expression (|) */ export const isIncompleteInput = (input: string) => { // Empty input is not incomplete if (input.trim() === "") { return false; } // Check for dangling single-quote strings if ((input.match(/'/g) || []).length % 2 !== 0) { return true; } // Check for dangling double-quote strings if ((input.match(/"/g) || []).length % 2 !== 0) { return true; } // Check for dangling boolean or pipe operations if ((input.split(/(\|\||\||&&)/g).pop() as string).trim() === "") { return true; } // Check for tailing slash if (input.endsWith("\\") && !input.endsWith("\\\\")) { return true; } return false; }; /** * @returns whether the input ends with trailing whitespace */ export const hasTrailingWhitespace = (input: string) => { return input.match(/[^\\][ \t]$/m) !== null; }; /** * @returns the last expression in the given input */ export const getLastToken = (input: string) => { if (!input.trim()) return ""; if (hasTrailingWhitespace(input)) return ""; // Last token const tokens = parse(input); return tokens.pop() || ""; };
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/types.ts
/** Tty print options */ export interface PrintOptions { /** Whether the command is sync */ sync?: boolean; /** Whether to append a new line */ newLine?: boolean; /** Disable automatic coloring */ noColor?: boolean; } /** Manage terminal commands */ export type CommandManager<R = unknown> = { /** Get the available command names. */ getNames: () => string[]; /** * Get command completions. * * Command completions are defined as an object with properties defined as * commands/subcommands (subcommand if depth > 0). * * # Example * * ```ts * { * anchor: { * idl: { * init: {}, * upgrade: {} * } * } * } * ``` */ getCompletions: () => Record<string, any>; /** Execute from the given tokens. */ execute: (tokens: string[]) => Promise<R>; }; export interface ActiveCharPrompt { promptPrefix: string; promise: Promise<any>; resolve?: (input: string) => any; reject?: (error: Error) => any; } export interface ActivePrompt extends ActiveCharPrompt { continuationPromptPrefix: string; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/shell.ts
import { PgAutocomplete } from "./autocomplete"; import { PgHistory } from "./history"; import { PgTty } from "./tty"; import { closestLeftBoundary, closestRightBoundary, hasTrailingWhitespace, isIncompleteInput, parse, } from "./utils"; import { PgTerminal } from "./terminal"; import { PgCommon } from "../common"; import type { ActiveCharPrompt, ActivePrompt, CommandManager } from "./types"; /** * A shell is the primary interface that is used to start other programs. * * Its purpose is to handle: * - Job control (control of child processes), * - Line editing and history * - Output text to the tty -> terminal * - Interpret text within the tty to launch processes and interpret programs */ export class PgShell { private _tty: PgTty; private _cmdManager: CommandManager; private _autocomplete: PgAutocomplete; private _history: PgHistory; private _waitingForInput = false; private _processCount = 0; private _activePrompt: ActivePrompt | null = null; private _activeCharPrompt: ActiveCharPrompt | null = null; constructor( tty: PgTty, cmdManager: CommandManager, autocomplete: PgAutocomplete, history: PgHistory ) { this._tty = tty; this._cmdManager = cmdManager; this._autocomplete = autocomplete; this._history = history; } /** Terminal history */ get history() { return this._history; } /** Disable shell. */ disable() { this._incrementProcessCount(); } /** Enable shell. */ enable() { setTimeout(() => { this._decrementProcessCount(); if (!this._processCount) this.prompt(); }, 10); } /** * Prompt terminal. * * This function also helps with command history. */ async prompt() { // If we are already prompting, do nothing if (this._activePrompt && this._tty.getInputStartsWithPrompt()) { return; } try { const promptText = this._waitingForInput ? PgTerminal.WAITING_INPUT_PROMPT_PREFIX : PgTerminal.PROMPT_PREFIX; this._activePrompt = this._tty.read(promptText); await this._activePrompt.promise; const input = this._tty.input.trim(); this._history.push(input); } catch (e: any) { this._tty.println(e.message); this.prompt(); } } /** Get whether the shell is active, and the user can type. */ isPrompting() { return !this._processCount || this._waitingForInput; } /** * Complete the current input, call the given callback and then re-display * the old prompt. */ printAndRestartPrompt(cb: () => Promise<any> | void) { // Complete input this._tty.setCursor(this._tty.input.length); this._tty.print("\r\n"); // Prepare a function that will resume prompt const resume = () => { this._tty.setCursor(this._tty.cursor); this._tty.setInput(this._tty.input); }; // Call the given callback to echo something, and if there is a promise // returned, wait for the resolution before resuming prompt. const ret = cb(); if (ret) { ret.then(resume); } else { resume(); } } /** * Wait for user input. * * @param msg message to print to the terminal before prompting user * @returns user input */ async waitForUserInput(msg: string) { return new Promise<string>((res, rej) => { if (this._waitingForInput) rej("Already waiting for input."); else { this._tty.clearLine(); this._tty.println( PgTerminal.secondary(PgTerminal.WAITING_INPUT_MSG_PREFIX) + msg ); this._waitingForInput = true; this.prompt(); // This will happen once user sends the input const handleInput = () => { document.removeEventListener( PgShell._TERMINAL_WAIT_FOR_INPUT, handleInput ); this._waitingForInput = false; res(this._tty.input); }; document.addEventListener( PgShell._TERMINAL_WAIT_FOR_INPUT, handleInput ); } }); } /** * Handle input completion. * * @param clearCmd whether to clean the current line before parsing the command */ async handleReadComplete(clearCmd?: boolean) { const input = this._tty.input; if (this._activePrompt && this._activePrompt.resolve) { this._activePrompt.resolve(input); this._activePrompt = null; } if (clearCmd) this._tty.clearLine(); else this._tty.print("\r\n"); if (this._waitingForInput) { PgCommon.createAndDispatchCustomEvent(PgShell._TERMINAL_WAIT_FOR_INPUT); } else { const parsedInput = parse(input).flatMap((token) => token === "!!" ? parse(this._history.getPrevious() ?? "") : [token] ); return await this._cmdManager.execute(parsedInput); } } /** Handle terminal -> tty input. */ handleTermData = (data: string) => { // Only Allow CTRL+C through if (!this.isPrompting() && data !== "\x03") return; if (this._tty.firstInit && this._activePrompt) { const line = this._tty.buffer.getLine( this._tty.buffer.cursorY + this._tty.buffer.baseY ); if (!line) return; const promptRead = line.translateToString( false, 0, this._tty.buffer.cursorX ); this._activePrompt.promptPrefix = promptRead; this._tty.setPromptPrefix(promptRead); this._tty.setFirstInit(false); } // If we have an active character prompt, satisfy it in priority if (this._activeCharPrompt && this._activeCharPrompt.resolve) { this._activeCharPrompt.resolve(data); this._activeCharPrompt = null; this._tty.print("\r\n"); return; } // If this looks like a pasted input, expand it if (data.length > 3 && data.charCodeAt(0) !== 0x1b) { const normData = data.replace(/[\r\n]+/g, "\r"); Array.from(normData).forEach((c) => this._handleData(c)); } else { this._handleData(data); } }; /** Move cursor at given direction. */ private _handleCursorMove = (dir: number) => { if (dir > 0) { const num = Math.min(dir, this._tty.input.length - this._tty.cursor); this._tty.setCursorDirectly(this._tty.cursor + num); } else if (dir < 0) { const num = Math.max(dir, -this._tty.cursor); this._tty.setCursorDirectly(this._tty.cursor + num); } }; /** Insert character at cursor location. */ private _handleCursorInsert = (data: string) => { const newInput = this._tty.input.substring(0, this._tty.cursor) + data + this._tty.input.substring(this._tty.cursor); this._tty.setCursorDirectly(this._tty.cursor + data.length); this._tty.setInput(newInput); }; /** Erase a character at cursor location. */ private _handleCursorErase = (backspace: boolean) => { if (backspace) { if (this._tty.cursor <= 0) return; const newInput = this._tty.input.substring(0, this._tty.cursor - 1) + this._tty.input.substring(this._tty.cursor); this._tty.clearInput(); this._tty.setCursorDirectly(this._tty.cursor - 1); this._tty.setInput(newInput, true); } else { const newInput = this._tty.input.substring(0, this._tty.cursor) + this._tty.input.substring(this._tty.cursor + 1); this._tty.setInput(newInput); } }; /** Handle a single piece of information from the terminal -> tty. */ private _handleData = (data: string) => { // Only Allow CTRL+C Through if (!this.isPrompting() && data !== "\x03") return; const ord = data.charCodeAt(0); // Handle ANSI escape sequences if (ord === 0x1b) { switch (data.substring(1)) { case "[A": { // Up arrow const value = this._history.getPrevious(); if (value) { this._tty.setInput(value); this._tty.setCursor(value.length); } break; } case "[B": { // Down arrow const value = this._history.getNext() ?? ""; this._tty.setInput(value); this._tty.setCursor(value.length); break; } case "[D": // Left Arrow this._handleCursorMove(-1); break; case "[C": // Right Arrow this._handleCursorMove(1); break; case "[3~": // Delete this._handleCursorErase(false); break; case "[F": // End this._tty.setCursor(this._tty.input.length); break; case "[H": // Home this._tty.setCursor(0); break; case "b": { // ALT + LEFT const offset = closestLeftBoundary(this._tty.input, this._tty.cursor); this._tty.setCursor(offset); break; } case "f": { // ALT + RIGHT const offset = closestRightBoundary( this._tty.input, this._tty.cursor ); this._tty.setCursor(offset); break; } case "\x7F": { // CTRL + BACKSPACE const offset = closestLeftBoundary(this._tty.input, this._tty.cursor); this._tty.setInput( this._tty.input.substring(0, offset) + this._tty.input.substring(this._tty.cursor) ); this._tty.setCursor(offset); break; } } } // Handle special characters else if (ord < 32 || ord === 0x7f) { switch (data) { case "\r": // ENTER if (isIncompleteInput(this._tty.input)) { this._handleCursorInsert("\n"); } else { this.handleReadComplete(); } break; case "\x7F": // BACKSPACE case "\x08": // CTRL+H case "\x04": // CTRL+D this._handleCursorErase(true); break; case "\t": // TAB if (this._autocomplete.hasAnyHandler()) { const inputFragment = this._tty.input.substring( 0, this._tty.cursor ); const createNewInput = (candidate: string) => { const tokens = parse(inputFragment); return [ ...(hasTrailingWhitespace(inputFragment) ? tokens : tokens.slice(0, -1)), candidate, ] .map((token) => (token.includes(" ") ? `"${token}"` : token)) .join(" "); }; const candidates = this._autocomplete.getCandidates(inputFragment); // Depending on the number of candidates, we are handing them in a // different way. if (candidates.length === 0) { // Add a space if there is none already if (!hasTrailingWhitespace(inputFragment)) { this._handleCursorInsert(" "); } } else if (candidates.length === 1) { // Set the input const newInput = createNewInput(candidates[0]); this._tty.setInput(newInput); this._tty.setCursor(newInput.length); } else if (candidates.length <= 100) { // If the candidate count is less than maximum auto-complete // candidates, find the common candidate let commonCandidate = ""; for (let i = 0; i < candidates[0].length; i++) { const char = candidates[0][i]; const matches = candidates.every((cand) => cand[i] === char); if (matches) commonCandidate += char; else break; } const newInput = createNewInput(commonCandidate); // If the input is already the common candidate, print all // candidates to the user and re-start prompt if (inputFragment === newInput) { this.printAndRestartPrompt(() => { this._tty.printWide(candidates); }); } else { // Set the input to the common candidate this._tty.setInput(newInput); this._tty.setCursor(newInput.length); } } else { // If we have more than maximum auto-complete candidates, print // them only if the user acknowledges a warning this.printAndRestartPrompt(() => this._tty .readChar( `Display all ${candidates.length} possibilities? (y or n)` ) .promise.then((answer: string) => { if (answer.toLowerCase() === "y") { this._tty.printWide(candidates); } }) ); } } else { this._handleCursorInsert(" "); } break; case "\x01": // CTRL+A this._tty.setCursor(0); break; case "\x02": // CTRL+B this._handleCursorMove(-1); break; // TODO: implement stopping commands // case "\x03": // CTRL+C case "\x05": // CTRL+E this._tty.setCursor(this._tty.input.length); break; case "\x06": // CTRL+F this._handleCursorMove(1); break; case "\x07": // CTRL+G this._history.getPrevious(); this._tty.setInput(""); break; case "\x0b": // CTRL+K this._tty.setInput(this._tty.input.substring(0, this._tty.cursor)); this._tty.setCursor(this._tty.input.length); break; case "\x0e": { // CTRL+N const value = this._history.getNext() ?? ""; this._tty.setInput(value); this._tty.setCursor(value.length); break; } case "\x10": { // CTRL+P const value = this._history.getPrevious(); if (value) { this._tty.setInput(value); this._tty.setCursor(value.length); } break; } case "\x15": // CTRL+U this._tty.setInput(this._tty.input.substring(this._tty.cursor)); this._tty.setCursor(0); break; } // Handle visible characters } else { this._handleCursorInsert(data); } }; /** Increment active process count. */ private _incrementProcessCount() { this._processCount++; } /** Decrement active process count if process count is greater than 0. */ private _decrementProcessCount() { if (this._processCount) this._processCount--; } /** Event name of terminal input wait */ private static readonly _TERMINAL_WAIT_FOR_INPUT = "terminalwaitforinput"; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/terminal.ts
import { ITerminalOptions, Terminal as XTerm } from "xterm"; import { FitAddon } from "xterm-addon-fit"; import { WebLinksAddon } from "xterm-addon-web-links"; import { format } from "util"; import { PgAutocomplete } from "./autocomplete"; import { PgHistory } from "./history"; import { PgShell } from "./shell"; import { PgTty } from "./tty"; import { Emoji, EventName, GITHUB_URL, OTHER_ERROR, PROGRAM_ERROR, PROJECT_NAME, RPC_ERROR, SERVER_ERROR, } from "../../../constants"; import { PgCommon } from "../common"; import type { CommandManager, PrintOptions } from "./types"; import type { Methods, ClassReturnType, SyncOrAsync } from "../types"; export class PgTerminal { /** Welcome text */ static readonly DEFAULT_TEXT = [ `Welcome to ${PgTerminal.bold(PROJECT_NAME)}.`, `Popular crates for Solana development are available to use.`, `See the list of available crates and request new crates from ${PgTerminal.underline( GITHUB_URL )}`, `Type ${PgTerminal.bold("help")} to see all commands.\n`, ].join("\n\n"); /** Default prompt string before entering commands */ static readonly PROMPT_PREFIX = "$ "; /** Prompt after `\` or `'` */ static readonly CONTINUATION_PROMPT_PREFIX = "> "; /** Prefix for the waiting user input prompt message */ static readonly WAITING_INPUT_MSG_PREFIX = "? "; /** Prompt prefix for waiting user input */ static readonly WAITING_INPUT_PROMPT_PREFIX = ">> "; static success(text: string) { return `\x1b[1;32m${text}\x1b[0m`; } static error(text: string) { return `\x1b[1;31m${text}\x1b[0m`; } static warning(text: string) { return `\x1b[1;33m${text}\x1b[0m`; } static info(text: string) { return `\x1b[1;34m${text}\x1b[0m`; } static primary(text: string) { return `\x1b[1;35m${text}\x1b[0m`; } static secondary(text: string) { return `\x1b[1;36m${text}\x1b[0m`; } static secondaryText(text: string) { return `\x1b[30m${text}\x1b[0m`; } static bold(text: string) { return `\x1b[1m${text}\x1b[0m`; } static italic(text: string) { return `\x1b[3m${text}\x1b[0m`; } static underline(text: string) { return `\x1b[4m${text}\x1b[0m`; } /** * Make error messages more friendly */ static convertErrorMessage(msg: string) { // Hex program errors for (const programErrorCode in PROGRAM_ERROR) { if (msg.endsWith("0x" + programErrorCode.toLowerCase())) { const parts = msg.split(":"); let ixIndex = parts[2][parts[2].length - 1]; if (!PgCommon.isInt(ixIndex)) ixIndex = "0"; const programError = PROGRAM_ERROR[programErrorCode]; msg = `\n${this.bold("Instruction index:")} ${ixIndex}\n${this.bold( "Reason:" )} ${programError}`; return msg; } } // Descriptive program errors if (msg.startsWith("failed to send")) { const parts = msg.split(":"); // With ix index if (parts.length === 4) { const ixIndex = parts[2][parts[2].length - 1]; const programError = parts[3][1].toUpperCase() + parts[3].substring(2); msg = `\n${this.bold("Instruction index:")} ${ixIndex}\n${this.bold( "Reason:" )} ${programError}.`; return msg; } // Without ix index const programError = parts[2][1].toUpperCase() + parts[2].substring(2); msg = `\n${this.bold("Reason:")} ${programError}.`; return msg; } // Rpc errors for (const rpcError in RPC_ERROR) { if (msg.includes(rpcError)) { msg = RPC_ERROR[rpcError]; return msg; } } // Server errors for (const serverError in SERVER_ERROR) { if (msg === serverError) { msg = SERVER_ERROR[serverError]; return msg; } } // Other errors for (const otherError in OTHER_ERROR) { if (msg === otherError) { msg = OTHER_ERROR[otherError]; return msg; } } return msg; } /** Get whether the terminal is focused or in blur. */ static isFocused() { return document .getElementsByClassName("terminal xterm xterm-dom-renderer-owner-1")[0] ?.classList.contains("focus"); } /** Dispatch enable terminal custom event. */ static async enable() { await PgTerminal.run({ enable: [] }); } /** Dispatch disable terminal custom event. */ static async disable() { await PgTerminal.run({ disable: [] }); } /** Log terminal messages from anywhere. */ static async log(msg: any, opts?: PrintOptions) { await PgTerminal.run({ println: [msg, opts] }); } /** Dispatch focus terminal custom event. */ static async focus() { await PgTerminal.run({ focus: [] }); } /** Dispatch focus terminal custom event. */ static async clear() { await PgTerminal.run({ clear: [] }); } // TODO: Remove /** * Log terminal messages from anywhere * * Mainly used from WASM */ static logWasm(msg: any) { this.log(msg); } /** Dispatch scroll to bottom custom event. */ static async scrollToBottom() { await PgTerminal.run({ scrollToBottom: [] }); } /** Execute the given command from string. */ static async executeFromStr(...args: Parameters<PgTerm["executeFromStr"]>) { const term = await PgTerminal.get(); return await term.executeFromStr(...args); } /** * Wrapper function for commands that interact with the terminal * * This function should be used as a wrapper function when calling any * terminal command. */ static async process<T>(cb: () => SyncOrAsync<T>) { this.disable(); this.scrollToBottom(); try { return await cb(); } catch (e: any) { this.log(`Process error: ${e?.message ? e.message : e}`); } finally { this.enable(); } } /** * Statically get the terminal object from state * * @returns the terminal object */ static async get() { return await PgCommon.sendAndReceiveCustomEvent<PgTerm>( PgCommon.getStaticEventNames(EventName.TERMINAL_STATIC).get ); } /** * Run any method of terminal in state from anywhere * * @param data method and its data to run * @returns the result from the method call */ static async run< R extends ClassReturnType<PgTerm, keyof M>, M extends Methods<PgTerm> >(data: M) { return await PgCommon.sendAndReceiveCustomEvent<R, M>( PgCommon.getStaticEventNames(EventName.TERMINAL_STATIC).run, data ); } /** * Set progressbar percentage. * * Progress bar will be hidden if `progress` is set to 0. * * @param progress progress percentage in 0-100 */ static setProgress(progress: number) { PgCommon.createAndDispatchCustomEvent( EventName.TERMINAL_PROGRESS_SET, progress ); } /** * Redifined console.log for showing mocha logs in the playground terminal */ static consoleLog(msg: string, ...rest: any[]) { _log(msg, ...rest); if (msg !== undefined) { // We only want to log mocha logs to the terminal const fullMessage = format(msg, ...rest); if (fullMessage.startsWith(" ")) { const editedMessage = fullMessage // Replace checkmark icon .replace(Emoji.CHECKMARK, PgTerminal.success("βœ” ")) // Make '1) testname' red .replace(/\s+\d\)\s\w*$/, (match) => PgTerminal.error(match)) // Passing text .replace(/\d+\spassing/, (match) => PgTerminal.success(match)) // Failing text .replace(/\d+\sfailing/, (match) => PgTerminal.error(match)) // Don't show the stack trace because it shows the transpiled code // TODO: show where the error actually happened in user code .replace(/\s+at.*$/gm, ""); PgTerminal.log(editedMessage); } } } } // Keep the default console.log const _log = console.log; export class PgTerm { private _xterm: XTerm; private _container: HTMLElement | null; private _fitAddon: FitAddon; private _tty: PgTty; private _shell: PgShell; private _autocomplete: PgAutocomplete; private _isOpen: boolean; constructor(cmdManager: CommandManager, xtermOptions?: ITerminalOptions) { // Create xterm element this._xterm = new XTerm(xtermOptions); // Container is empty at start this._container = null; // Load xterm addons this._fitAddon = new FitAddon(); this._xterm.loadAddon(this._fitAddon); this._xterm.loadAddon(new WebLinksAddon()); // Create Shell and TTY const history = new PgHistory(20); this._autocomplete = new PgAutocomplete([ cmdManager.getCompletions(), () => history.getEntries(), ]); this._tty = new PgTty(this._xterm, cmdManager, this._autocomplete); this._shell = new PgShell( this._tty, cmdManager, this._autocomplete, history ); // Add a custom resize handler that clears the prompt using the previous // configuration, updates the cached terminal size information and then // re-renders the input. This leads (most of the times) into a better // formatted input. // // Also stops multiline inputs rendering unnecessarily. this._xterm.onResize(({ rows, cols }) => { this._tty.clearInput(); this._tty.setTermSize(cols, rows); this._tty.setInput(this._tty.input, true); }); // Add a custom key handler in order to fix a bug with spaces this._xterm.onKey((ev) => { if (ev.key === " ") { ev.domEvent.preventDefault(); return false; } }); // Any data event (key, paste...) this._xterm.onData(this._shell.handleTermData); this._isOpen = false; } /** Open terminal */ open(container: HTMLElement) { this._container = container; this._xterm.open(container); this._xterm.attachCustomKeyEventHandler(this._handleCustomEvent); this._isOpen = true; // Fit terminal this.fit(); // Print welcome text this.println(PgTerminal.DEFAULT_TEXT); // Prompt this.enable(); } /** Fit terminal */ fit() { this._fitAddon.fit(); } /** Focus terminal and scroll to cursor */ focus() { this._xterm.focus(); this.scrollToCursor(); } /** Scroll terminal to wherever the cursor currently is */ scrollToCursor() { if (!this._container) { return; } // We don't need `cursorX`, since we want to start at the beginning of the terminal const cursorY = this._tty.buffer.cursorY; const size = this._tty.size; const containerBoundingClientRect = this._container.getBoundingClientRect(); // Find how much to scroll because of our cursor const cursorOffsetY = (cursorY / size.rows) * containerBoundingClientRect.height; let scrollX = containerBoundingClientRect.left; let scrollY = containerBoundingClientRect.top + cursorOffsetY + 10; if (scrollX < 0) { scrollX = 0; } if (scrollY > document.body.scrollHeight) { scrollY = document.body.scrollHeight; } window.scrollTo(scrollX, scrollY); } /** Print a message */ print(msg: any, opts?: PrintOptions) { if (typeof msg === "string") { // For some reason, double new lines are not respected. Thus, fixing that here msg = msg.replace(/\n\n/g, "\n \n"); } if (!this._isOpen) { return; } if (this._shell.isPrompting()) { // Cancel the current prompt and restart this._shell.printAndRestartPrompt(() => { this._tty.print(msg + "\n", opts); }); return; } this._tty.print(msg, opts); } /** Print a message with end line character appended */ println(msg: any, opts?: PrintOptions) { this.print(msg, { ...opts, newLine: true }); } /** * Clear terminal screen. This will move the cursor to the top of the terminal * but will not clear xterm buffer by default. * * @param opts.full whether to fully clean xterm buffer * */ clear(opts?: { full?: boolean }) { this._tty.clearTty(); if (opts?.full) { this._tty.clear(); } else { this._tty.print(`${PgTerminal.PROMPT_PREFIX}${this._tty.input}`); } } /** * Disable shell: * - Disables shell * - Clears current line for for actions that were committed from outside of terminal * like pressing build button */ disable() { this._shell.disable(); this._tty.clearLine(); } /** Enable shell */ enable() { this._shell.enable(); } /** Scroll the terminal to bottom */ scrollToBottom() { this._xterm.scrollToBottom(); } /** Destroy xterm instance */ destroy() { this._xterm.dispose(); // @ts-ignore delete this._xterm; } /** * Wait for user input * * @param msg message to print to the terminal before prompting user * @param opts - * - allowEmpty: whether to allow the input to be empty * - choice.items: set of values to choose from. Returns the selected index if * `allowMultiple` is not specified. * - choice.allowMultiple: whether to allow multiple choices. Returns the indices. * - confirm: yes/no question. Returns the result as boolean. * - default: default value to set * - validator: callback function to validate the user input * @returns user input */ async waitForUserInput< O extends { allowEmpty?: boolean; confirm?: boolean; default?: string; choice?: { items: string[]; allowMultiple?: boolean; }; validator?: ( userInput: string ) => boolean | void | Promise<boolean | void>; } >( msg: string, opts?: O ): Promise< O["confirm"] extends boolean ? boolean : O["choice"] extends object ? O["choice"]["allowMultiple"] extends boolean ? number[] : number : string > { this.focus(); let convertedMsg = msg; let restore; if (opts?.default) { const value = opts.default; convertedMsg += ` (default: ${value})`; restore = this._autocomplete.temporarilySetHandlers([value], { append: true, }).restore; } if (opts?.choice) { // Show multi choice items const items = opts.choice.items; convertedMsg += items.reduce( (acc, cur, i) => acc + `\n[${i}] - ${cur}`, "\n" ); restore = this._autocomplete.temporarilySetHandlers( items.map((_, i) => i.toString()) ).restore; } else if (opts?.confirm) { convertedMsg += PgTerminal.secondaryText(` [yes/no]`); restore = this._autocomplete.temporarilySetHandlers([ "yes", "no", ]).restore; } let userInput; try { userInput = await this._shell.waitForUserInput(convertedMsg); } finally { restore?.(); } // Set the input to the default if it exists on empty input if (!userInput && opts?.default) userInput = opts.default; // Default validators if (opts && !opts.validator) { // Validate confirm if (opts.confirm) { opts.validator = (input) => input === "yes" || input === "no"; } // Validate multi choice if (opts.choice) { const choiceMaxLength = opts.choice.items.length - 1; opts.validator = (input) => { const parsed: number[] = JSON.parse(`[${input}]`); return ( (opts.choice?.allowMultiple ? true : parsed.length === 1) && parsed.every( (v) => PgCommon.isInt(v.toString()) && v >= 0 && v <= choiceMaxLength ) ); }; } } // Allow empty if (!userInput && !opts?.allowEmpty) { this.println(PgTerminal.error("Can't be empty.\n")); return await this.waitForUserInput(msg, opts); } // Validator if (opts?.validator && userInput) { try { if ((await opts.validator(userInput)) === false) { this.println( PgTerminal.error(`'${userInput}' is not a valid value.\n`) ); return await this.waitForUserInput(msg, opts); } } catch (e: any) { this.println( PgTerminal.error(`${e.message || `Validation failed: ${e}`}\n`) ); return await this.waitForUserInput(msg, opts); } } // Return value let returnValue; // Confirm if (opts?.confirm) { returnValue = userInput === "yes" ? true : false; } // Multichoice else if (opts?.choice) { if (opts.choice.allowMultiple) { returnValue = JSON.parse(`[${userInput}]`); } else { returnValue = parseInt(userInput); } } // Default as string else { returnValue = userInput; } const visibleText = returnValue?.length === 0 ? PgTerminal.secondaryText("empty") : PgTerminal.success(userInput); this._tty.changeLine(PgTerminal.WAITING_INPUT_PROMPT_PREFIX + visibleText); return returnValue; } /** * Write the given input in the terminal and press `Enter` * * @param cmd command to run * @param clearCmd whether to clean the command afterwards - defaults to `true` */ async executeFromStr(cmd: string, clearCmd?: boolean) { this._tty.setInput(cmd); return await this._shell.handleReadComplete(clearCmd); } /** * Handle custom keyboard events. Only runs when terminal is in focus. * * @param ev keyboard event * @returns whether to keep the defaults * * NOTE: This function is intentionally uses arrow functions for `this` to be * defined from the outer class (PgTerm) otherwise `this` is being defined from * XTerm's instance */ private _handleCustomEvent = (ev: KeyboardEvent) => { if (PgCommon.isKeyCtrlOrCmd(ev) && ev.type === "keydown") { const key = ev.key.toUpperCase(); switch (key) { case "C": if (ev.shiftKey) { ev.preventDefault(); const selection = this._xterm.getSelection(); navigator.clipboard.writeText(selection); return false; } return true; case "V": // Ctrl+Shift+V does not work with Firefox but works with Chromium. // We fallback to Ctrl+V for Firefox if (ev.shiftKey || PgCommon.getBrowser() === "Firefox") return false; return true; case "L": case "M": case "J": return false; } } return true; }; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/index.ts
export * from "./terminal"; export type { CommandManager } from "./types";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/terminal/tty.ts
import { Terminal as XTerm } from "xterm"; import { PgAutocomplete } from "./autocomplete"; import { PgTerminal } from "./terminal"; import { getLastToken } from "./utils"; import { PgCommon } from "../common"; import type { ActiveCharPrompt, ActivePrompt, CommandManager, PrintOptions, } from "./types"; /** * TTY manages text I/O related things such as prompting, input parsing and * printing messages to the terminal. */ export class PgTty { private _xterm: XTerm; private _cmdManager: CommandManager; private _autocomplete: PgAutocomplete; private _termSize: { cols: number; rows: number; }; private _firstInit = true; private _promptPrefix = ""; private _continuationPromptPrefix = ""; private _cursor = 0; private _input = ""; constructor( xterm: XTerm, cmdManager: CommandManager, autocomplete: PgAutocomplete ) { this._xterm = xterm; this._cmdManager = cmdManager; this._autocomplete = autocomplete; this._termSize = { cols: this._xterm.cols, rows: this._xterm.rows, }; } /** Whether it is the initial read */ get firstInit() { return this._firstInit; } /** Current input in the terminal */ get input() { return this._input; } /** Current cursor position */ get cursor() { return this._cursor; } /** TTY size (columns and rows) */ get size() { return this._termSize; } /** Active terminal buffer */ get buffer() { return this._xterm.buffer.active; } /** * Get whether the current input starts with prompt. * * Useful for `PgTerm.fit()`. */ getInputStartsWithPrompt() { for (let i = 0; i < 10; i++) { const currentLine = this._getCurrentLine(i); if (!currentLine) return; if (!currentLine.isWrapped) { const currentLineStr = currentLine.translateToString(); return ( currentLineStr.startsWith(PgTerminal.PROMPT_PREFIX) || currentLineStr.startsWith(PgTerminal.CONTINUATION_PROMPT_PREFIX) || currentLineStr.startsWith(PgTerminal.WAITING_INPUT_PROMPT_PREFIX) ); } } } /** * Replace input with the given input. * * This function clears all the lines that the current input occupies and * then replaces them with the new input. */ setInput(newInput: string, noClearInput?: boolean) { if (!noClearInput) this.clearInput(); // Write the new input lines, including the current prompt const newPrompt = this._applyPrompts(newInput); this.print(newPrompt); // Trim cursor overflow if (this._cursor > newInput.length) { this._cursor = newInput.length; } // Move the cursor to the appropriate row/col const newCursor = this._applyPromptOffset(newInput, this._cursor); const newLines = PgTty._countLines(newPrompt, this._termSize.cols); const { col, row } = PgTty._offsetToColRow( newPrompt, newCursor, this._termSize.cols ); const moveUpRows = newLines - row - 1; this._xterm.write("\r"); for (let i = 0; i < moveUpRows; ++i) this._xterm.write("\x1b[F"); for (let i = 0; i < col; ++i) this._xterm.write("\x1b[C"); // Replace input this._input = newInput; } /** Set the new cursor position, as an offset on the input string. */ setCursor(newCursor: number) { if (newCursor < 0) newCursor = 0; if (newCursor > this._input.length) newCursor = this._input.length; this._writeCursorPosition(newCursor); } /** Set the direct cursor value. Should only be used in keystroke contexts. */ setCursorDirectly(newCursor: number) { this._writeCursorPosition(newCursor); } /** Set the terminal TTY size. */ setTermSize(cols: number, rows: number) { this._termSize = { cols, rows }; } /** Set the first init. */ setFirstInit(value: boolean) { this._firstInit = value; } /** Set the prompt prefix. */ setPromptPrefix(value: string) { this._promptPrefix = value; } /** * Return a promise that will resolve when the user has completed typing a * single line. */ read( promptPrefix: string, continuationPromptPrefix: string = PgTerminal.CONTINUATION_PROMPT_PREFIX ): ActivePrompt { if (promptPrefix.length > 0) { this.print(promptPrefix); } this._firstInit = true; this._promptPrefix = promptPrefix; this._continuationPromptPrefix = continuationPromptPrefix; this._input = ""; this._cursor = 0; return { promptPrefix, continuationPromptPrefix, ...this._getAsyncRead(), }; } /** * Return a promise that will be resolved when the user types a single * character. * * This can be active in addition to `.read()` and will be resolved in * priority before it. */ readChar(promptPrefix: string): ActiveCharPrompt { if (promptPrefix.length > 0) { this.print(promptPrefix); } return { promptPrefix, ...this._getAsyncRead(), }; } /** Print a message and properly handle new-lines. */ print(msg: any, opts?: PrintOptions) { if (typeof msg === "object") msg = PgCommon.prettyJSON(msg); else msg = `${msg}`; // All data types should be converted to string msg = msg.replace(/[\r\n]+/g, "\n").replace(/\n/g, "\r\n"); // Color text if (!opts?.noColor) msg = this._highlightText(msg); if (opts?.newLine) msg += "\n"; if (opts?.sync) { // We write it synchronously via hacking a bit on xterm //@ts-ignore this._xterm._core.writeSync(msg); //@ts-ignore this._xterm._core._renderService._renderer._runOperation((renderer) => renderer.onGridChanged(0, this._xterm.rows - 1) ); } else { this._xterm.write(msg); } } /** Print a message with an extra line appended. */ println(msg: string, opts?: PrintOptions) { this.print(msg, { ...opts, newLine: true }); } /** Print a list of items using a wide-format. */ printWide(items: Array<string>, padding = 2) { if (items.length === 0) return this.println(""); // Compute item sizes and matrix row/cols const itemWidth = items.reduce((width, item) => Math.max(width, item.length), 0) + padding; const wideCols = Math.floor(this._termSize.cols / itemWidth); const wideRows = Math.ceil(items.length / wideCols); // Print matrix let i = 0; for (let row = 0; row < wideRows; ++row) { let rowStr = ""; // Prepare columns for (let col = 0; col < wideCols; ++col) { if (i < items.length) { let item = items[i++]; item += " ".repeat(itemWidth - item.length); rowStr += item; } } this.println(rowStr); } } /** * Print a status message on the current line. * * This function meant to be used with `clearStatus()`. */ printStatus(message: string, sync?: boolean) { // Save the cursor position this.print("\u001b[s", { sync }); this.print(message, { sync }); } /** * Clear the current status on the line. * * This function is meant to be run after `printStatus()`. */ clearStatus(sync?: boolean) { // Restore the cursor position this.print("\u001b[u", { sync }); // Clear from cursor to end of screen this.print("\u001b[1000D", { sync }); this.print("\u001b[0J", { sync }); } /** * Clear the current prompt. * * This function will erase all the lines that display the current prompt * and move the cursor in the beginning of the first line of the prompt. */ clearInput() { const currentPrompt = this._applyPrompts(this._input); // Get the overall number of lines to clear const allRows = PgTty._countLines(currentPrompt, this._termSize.cols); // Get the line we are currently in const promptCursor = this._applyPromptOffset(this._input, this._cursor); const { row } = PgTty._offsetToColRow( currentPrompt, promptCursor, this._termSize.cols ); // First move on the last line const moveRows = allRows - row - 1; for (let i = 0; i < moveRows; ++i) this._xterm.write("\x1b[E"); // Clear current input line(s) this._xterm.write("\r\x1b[K"); for (let i = 1; i < allRows; ++i) this._xterm.write("\x1b[F\x1b[K"); } /** Clear the entire XTerm buffer. */ clear() { this._xterm.clear(); } /** * Clear the entire TTY. * * This function will erase all the lines that display on the tty, * and move the cursor in the beginning of the first line of the prompt. */ clearTty() { // Clear the screen this._xterm.write("\x1b[2J"); // Set the cursor to 0, 0 this._xterm.write("\x1b[0;0H"); // Scroll to bottom this._xterm.scrollToBottom(); } /** * Clear the current line. * * @param offset amount of lines before the current line */ clearLine(offset?: number) { if (offset) { // Move up this.print(`\x1b[${offset}A`); } // Clears the whole line this.print(`\x1b[G`); // This also clears the line but helps with parsing errors this.print(`\x1b[2K`); } /** * Change the specified line with the new input. * * @param newInput input to change the line to * @param offset line offset. 0 is current, 1 is last. Defaults to 1. */ changeLine(newInput: string, offset: number = 1) { this.clearLine(offset); this.println(newInput); } /** Create a deconstructed read promise. */ private _getAsyncRead() { let readResolve; let readReject; const readPromise = new Promise((resolve, reject) => { readResolve = (response: string) => { this._promptPrefix = ""; this._continuationPromptPrefix = ""; resolve(response); }; readReject = reject; }); return { promise: readPromise, resolve: readResolve, reject: readReject, }; } /** Apply prompts to the given input. */ private _applyPrompts(input: string) { return ( this._promptPrefix + input.replace(/\n/g, "\n" + this._continuationPromptPrefix) ); } /** Get the current line. */ private _getCurrentLine(offset: number = 0) { const buffer = this.buffer; return buffer.getLine(buffer.baseY + buffer.cursorY - offset); } /** * Advance the `offset` as required in order to accompany the prompt * additions to the input. */ private _applyPromptOffset(input: string, offset: number) { const newInput = this._applyPrompts(input.substring(0, offset)); return newInput.length; } /** Write the new cursor position. */ private _writeCursorPosition(newCursor: number) { // Apply prompt formatting to get the visual status of the display const inputWithPrompt = this._applyPrompts(this._input); // Estimate previous cursor position const prevPromptOffset = this._applyPromptOffset(this._input, this._cursor); const { col: prevCol, row: prevRow } = PgTty._offsetToColRow( inputWithPrompt, prevPromptOffset, this._termSize.cols ); // Estimate next cursor position const newPromptOffset = this._applyPromptOffset(this._input, newCursor); const { col: newCol, row: newRow } = PgTty._offsetToColRow( inputWithPrompt, newPromptOffset, this._termSize.cols ); // Adjust vertically if (newRow > prevRow) { for (let i = prevRow; i < newRow; ++i) this._xterm.write("\x1b[B"); } else { for (let i = newRow; i < prevRow; ++i) this._xterm.write("\x1b[A"); } // Adjust horizontally if (newCol > prevCol) { for (let i = prevCol; i < newCol; ++i) this._xterm.write("\x1b[C"); } else { for (let i = newCol; i < prevCol; ++i) this._xterm.write("\x1b[D"); } // Set new offset this._cursor = newCursor; } /** Add highighting to the given text based on ANSI escape sequences. */ private _highlightText(text: string) { // Prompt highlighting if (this._promptPrefix && text.startsWith(this._promptPrefix)) { const inputWithoutPrefix = text.replace(this._promptPrefix, ""); if (inputWithoutPrefix) { // Autocomplete hints const candidates = this._autocomplete.getCandidates(inputWithoutPrefix); if (candidates.length) { const [candidate] = candidates; const lastToken = getLastToken(inputWithoutPrefix); if (candidate !== lastToken) { const missingText = candidate.replace(lastToken, ""); text = text.replace( inputWithoutPrefix, inputWithoutPrefix + PgTerminal.secondaryText(missingText) ); } } // Command based highlighting for (const cmd of this._cmdManager.getNames()) { if (inputWithoutPrefix.startsWith(cmd)) { text = text.replace(cmd, PgTerminal.secondary); break; } } } } const hl = (s: string, colorCb: (s: string) => string) => { if (s.endsWith(":")) { return colorCb(s.substring(0, s.length - 1)) + s[s.length - 1]; } return colorCb(s); }; return ( text // Match for error .replace(/\w*\s?(\w*)error(:|\[.*?:)/gim, (match) => hl(match, PgTerminal.error) ) // Match for warning .replace(/(\d+\s)?warning(s|:)?/gim, (match) => hl(match, PgTerminal.warning) ) // Match until ':' from the start of the line: e.g "Commands:" .replace(/^(.*?:)/gm, (match) => { if ( /(http|{|})/.test(match) || /"\w+":/.test(match) || /\(\w+:/.test(match) || /^\s*\|/.test(match) || /^\s?\d+/.test(match) || /\(/.test(match) ) { return match; } if (!match.includes(" ")) { if (match.startsWith(" ")) { // Indented return hl(match, PgTerminal.bold); } if (!match.toLowerCase().includes("error")) { return hl(match, PgTerminal.primary); } } return match; }) // Secondary text color for (...) .replace(/\(.+\)/gm, (match) => match === "(s)" ? match : PgTerminal.secondaryText(match) ) // Numbers .replace(/^\s*\d+$/, PgTerminal.secondary) // Progression [1/5] .replace(/\[\d+\/\d+\]/, (match) => PgTerminal.bold(PgTerminal.secondaryText(match)) ) ); } /** * Convert offset at the given input to col/row location. * * This function is not optimized and practically emulates via brute-force * the navigation on the terminal, wrapping when they reach the column width. */ private static _offsetToColRow( input: string, offset: number, maxCols: number ) { let row = 0; let col = 0; for (let i = 0; i < offset; ++i) { const chr = input.charAt(i); if (chr === "\n") { col = 0; row += 1; } else { col += 1; if (col > maxCols) { col = 0; row += 1; } } } return { row, col }; } /** Count the lines of the given input. */ private static _countLines(input: string, maxCols: number) { return PgTty._offsetToColRow(input, input.length, maxCols).row + 1; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/explorer/workspace.ts
import { WorkspaceError } from "../../../constants"; import { PgCommon } from "../common"; interface Workspaces { /** All workspace names */ allNames: string[]; /** Current workspace name */ currentName?: string; } /** * Workspace functionality class that only exists in the memory state * * This class does not have access to IndexedDB */ export class PgWorkspace { /** Class methods */ private _state: Workspaces; constructor(workspaces: Workspaces = PgWorkspace.DEFAULT) { this._state = workspaces; } /** Get all workspace names */ get allNames() { return this._state.allNames; } /** Get current workspace name */ get currentName() { return this._state.currentName; } /** * Get the current workspaces. * * @returns the current workspaces state */ get(): Workspaces { return { currentName: this.currentName, allNames: this.allNames, }; } /** * Set the current workspaces. * * @param workspaces new workspaces config to set the state to */ setCurrent(workspaces: Workspaces) { this._state.allNames = workspaces.allNames; this._state.currentName = workspaces.currentName; } /** * Set the current workspace name. * * @param name new workspace name to set the current name to */ setCurrentName(name: string) { if (this.allNames.includes(name)) { this._state.currentName = name; } } /** * Create a new workspace in state and set the current state. * * @param name workspace name */ new(name: string) { if (this.allNames.includes(name)) { throw new Error(WorkspaceError.ALREADY_EXISTS); } this._state.allNames.push(name); this._state.currentName = name; } /** * Delete the given workspace in state. * * @param name workspace name */ delete(name: string) { this._state.allNames = this._state.allNames.filter((n) => n !== name); } /** * Rename the given workspace and make it current. * * @param newName new workspace name */ rename(newName: string) { if (this._state.allNames.includes(newName)) { throw new Error(WorkspaceError.ALREADY_EXISTS); } const oldName = this._state.currentName; this._state.allNames = this._state.allNames.map((n) => n === oldName ? newName : n ); this._state.currentName = newName; } /* ---------------------------- Static methods ---------------------------- */ /** Default workspaces */ static readonly DEFAULT: Workspaces = { allNames: [], }; /** Path to the file that has data about all the workspaces */ static readonly WORKSPACES_CONFIG_PATH = "/.config/workspaces.json"; /* ----------------------- Workspace relative paths ----------------------- */ /** Relative PATH to workspace data */ static readonly WORKSPACE_PATH = ".workspace"; /** Relative path to file metadatas */ static readonly METADATA_PATH = PgCommon.joinPaths( this.WORKSPACE_PATH, "metadata.json" ); /** Default name to name the projects that used to be in localStorage */ static readonly DEFAULT_WORKSPACE_NAME = "default"; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/explorer/fs.ts
import FS from "@isomorphic-git/lightning-fs"; import { PgExplorer } from "./explorer"; export class PgFs { /** Async `indexedDB` based file system instance */ private static _fs = new FS("solana-playground").promises; /** * Write a file. * * @param path file path * @param data file content * @param opts - * `createParents`: Whether to create the parent folders if they don't exist */ static async writeFile( path: string, data: string, opts?: { createParents?: boolean } ) { path = PgExplorer.convertToFullPath(path); if (opts?.createParents) { // TODO: Create a path module const parentFolder = PgExplorer.getParentPathFromPath(path); await this.createDir(parentFolder, opts); } await this._fs.writeFile(path, data); } /** * Read a file as string. * * @param path file path * @returns the content of the file */ static async readToString(path: string) { path = PgExplorer.convertToFullPath(path); return (await this._fs.readFile(path, { encoding: "utf8" })) as string; } /** * Read a file and parse it to JSON. * * @param path file path * @returns JSON parsed result */ static async readToJSON<T>(path: string): Promise<T> { const data = await this.readToString(path); return JSON.parse(data); } /** * Read a file and parse it to JSON. * * If there was an error while getting the JSON, the error will be caught and * the given `defaultValue` will be returned instead. * * @param path file path * @param defaultValue the default value to return if the file doesn't exist * @returns JSON parsed result or the given `defaultValue` */ static async readToJSONOrDefault<T>(path: string, defaultValue: T) { try { return await this.readToJSON<T>(path); } catch { return defaultValue; } } /** * Rename an item(file or folder). * * @param oldPath old item path * @param newPath new item path */ static async rename(oldPath: string, newPath: string) { oldPath = PgExplorer.convertToFullPath(oldPath); newPath = PgExplorer.convertToFullPath(newPath); await this._fs.rename(oldPath, newPath); } /** * Remove a file. * * @param path file path */ static async removeFile(path: string) { path = PgExplorer.convertToFullPath(path); await this._fs.unlink(path); } /** * Create a new directory. * * @param path directory path * @param opts - * `createParents`: Whether to create the parent folders if they don't exist */ static async createDir(path: string, opts?: { createParents?: boolean }) { path = PgExplorer.convertToFullPath(path); if (opts?.createParents) { const folders = path.split("/"); let currentPath = ""; for (let i = 1; i < folders.length - 1; i++) { currentPath += "/" + folders[i]; // Only create if the dir doesn't exist const exists = await this.exists(currentPath); if (!exists) await this._fs.mkdir(currentPath); } } else { await this._fs.mkdir(path); } } /** * Read a directory. * * @param path directory path * @returns an array of the item names */ static async readDir(path: string) { path = PgExplorer.convertToFullPath(path); return await this._fs.readdir(path); } /** * Remove a directory. * * @param path directory path * @param opts - * `recursive`: Whether the recursively remove all of the child items */ static async removeDir(path: string, opts?: { recursive?: boolean }) { path = PgExplorer.convertToFullPath(path); if (opts?.recursive) { const recursivelyRmdir = async (dir: string[], currentPath: string) => { if (!dir.length) { // Delete if it's an empty directory await this._fs.rmdir(currentPath); return; } for (const childName of dir) { const childPath = currentPath + childName; const metadata = await this.getMetadata(childPath); if (metadata.isDirectory()) { const childDir = await this.readDir(childPath); if (childDir.length) { await recursivelyRmdir(childDir, childPath + "/"); } else await this._fs.rmdir(childPath); } else { await this.removeFile(childPath); } } // Read the directory again and delete if it's empty const _dir = await this.readDir(currentPath); if (!_dir.length) await this._fs.rmdir(currentPath); }; const dir = await this.readDir(path); await recursivelyRmdir(dir, path); } else { await this._fs.rmdir(path); } } /** * Get the metadata of a file. * * @param path item path * @returns the metadata of the file */ static async getMetadata(path: string) { path = PgExplorer.convertToFullPath(path); return await this._fs.stat(path); } /** * Get whether the given file exists in the file system. * * @param path item path * @returns whether the given file exists */ static async exists(path: string) { path = PgExplorer.convertToFullPath(path); try { await this.getMetadata(path); return true; } catch (e: any) { if (e.code === "ENOENT" || e.code === "ENOTDIR") return false; else { console.log("Unknown error in exists: ", e); throw e; } } } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/explorer/explorer.ts
import { PgExplorerEvent } from "./events"; import { PgFs } from "./fs"; import { PgWorkspace } from "./workspace"; import { PgCommon } from "../common"; import { PgLanguage } from "../language"; import { ClassName, Id, ItemError, WorkspaceError } from "../../../constants"; import type { Explorer, TupleFiles, Folder, FullFile, ItemMetaFile, ExplorerFiles, Position, } from "./types"; export class PgExplorer { /** Internal state */ private static _explorer = this._getDefaultState(); /** Whether the explorer is initialized */ private static _isInitialized = false; /** Whether the current explorer state is temporary */ private static _isTemporary: boolean; /** Workspace functionality */ private static _workspace: PgWorkspace | null = null; /** Current initialized workspace name */ private static _initializedWorkspaceName: string | null = null; /** `indexedDB` file system */ static fs = PgFs; /* -------------------------------- Getters ------------------------------- */ /** Get whether the explorer is initialized */ static get isInitialized() { return this._isInitialized; } /** Get whether the current workspace is temporary */ static get isTemporary() { return this._isTemporary; } /** Get explorer files */ static get files() { return this._explorer.files; } /** Get explorer tabs */ static get tabs() { return this._explorer.tabs as Readonly<Explorer["tabs"]>; } /** Get current file path */ static get currentFilePath() { return this.tabs.at(this._currentIndex); } /** Get current file path index */ private static get _currentIndex() { return this._explorer.currentIndex; } /** * Get full path of current workspace('/' appended) * * @throws if the workspace doesn't exist. Shouldn't be used with temporary projects. */ static get currentWorkspacePath() { if (!this.currentWorkspaceName) { throw new Error(WorkspaceError.CURRENT_NOT_FOUND); } return PgCommon.joinPaths( PgExplorer.PATHS.ROOT_DIR_PATH, PgCommon.appendSlash(this.currentWorkspaceName) ); } /** Get current workspace name */ static get currentWorkspaceName() { return this._workspace?.currentName; } /** Get names of all workspaces */ static get allWorkspaceNames() { return this._workspace?.allNames; } /* ---------------------------- Public methods ---------------------------- */ /** * Initialize explorer. * * @param params - * - `files`: Files to initialize the explorer from * - `name`: Initialize the given workspace name */ static async init(params?: { files?: ExplorerFiles | TupleFiles; name?: string; }) { if (params?.files) { this._isTemporary = true; this._workspace = null; // Reset the explorer state this._explorer = this._getDefaultState(); // Files this._explorer.files = Array.isArray(params.files) ? this._convertToExplorerFiles(params.files) : params.files; // Tabs, current const currentFilePath = this._getDefaultOpenFile(this._explorer.files); if (currentFilePath) this.openFile(currentFilePath); } // Skip initializing if the workspace has already been initialized else if ( this._initializedWorkspaceName === (params?.name ?? this.currentWorkspaceName) ) { } else { this._isTemporary = false; if (!this._workspace) await this._initWorkspaces(); // Check whether the workspace exists const workspaceName = params?.name ?? this.currentWorkspaceName; if (workspaceName && this.allWorkspaceNames!.includes(workspaceName)) { await this.switchWorkspace(workspaceName); } // Reset files if there are no workspaces else if (this.allWorkspaceNames!.length === 0) { // Reset the explorer state this._explorer = this._getDefaultState(); } } this._isInitialized = true; PgExplorerEvent.dispatchOnDidInit(); } /** * If the project is not temporary(default): * - Name and path checks * - Create new item in `indexedDB` * - If create is successful, also create the item in the state * * If the project is temporary: * - Name and path checks * - Create item in the state */ static async newItem( path: string, content: string = "", opts?: { skipNameValidation?: boolean; override?: boolean; openOptions?: { dontOpen?: boolean; onlyRefreshIfAlreadyOpen?: boolean; }; } ) { const fullPath = this.convertToFullPath(path); // Invalid name if ( !opts?.skipNameValidation && !PgExplorer.isItemNameValid(PgExplorer.getItemNameFromPath(fullPath)) ) { throw new Error(ItemError.INVALID_NAME); } const files = this.files; // Check whether the item already exists if (files[fullPath] && !opts?.override) { throw new Error(ItemError.ALREADY_EXISTS); } const itemType = PgExplorer.getItemTypeFromPath(fullPath); // Ordering of `indexedDB` calls and state calls matter. If `indexedDB` call fails, // state will not change. Can't say the same if the ordering was in reverse. if (itemType.file) { if (!this.isTemporary) { await this.fs.writeFile(fullPath, content, { createParents: true }); } files[fullPath] = { content, meta: files[fullPath]?.meta ?? {}, }; if (!opts?.openOptions || opts?.openOptions?.onlyRefreshIfAlreadyOpen) { const isCurrentFile = this.currentFilePath === fullPath; // Close the file if we are overriding to correctly display the new content if (opts?.override && isCurrentFile) this.closeFile(fullPath); // Open if it's the current file or there is no open options if (!opts?.openOptions || isCurrentFile) this.openFile(fullPath); } } // Folder else { if (!this.isTemporary) await this.fs.createDir(fullPath); files[fullPath] = {}; } PgExplorerEvent.dispatchOnDidCreateItem(); await this.saveMeta(); } /** * If the project is not temporary(default): * - Name and path checks * - Rename in `indexedDB` * - If rename is successful also rename item in the state * * If the project is temporary: * - Name and path checks * - Rename in state */ static async renameItem( oldPath: string, newPath: string, opts?: { skipNameValidation?: boolean; override?: boolean } ) { oldPath = this.convertToFullPath(oldPath); newPath = this.convertToFullPath(newPath); // Return if there is no change if (PgCommon.isPathsEqual(newPath, oldPath)) return; if (!opts?.skipNameValidation && !PgExplorer.isItemNameValid(newPath)) { throw new Error(ItemError.INVALID_NAME); } if (PgCommon.isPathsEqual(oldPath, this.getCurrentSrcPath())) { throw new Error(ItemError.SRC_RENAME); } const itemType = PgExplorer.getItemTypeFromPath(oldPath); const newItemType = PgExplorer.getItemTypeFromPath(newPath); if ( (itemType.file && !newItemType.file) || (itemType.folder && !newItemType.folder) ) { throw new Error(ItemError.TYPE_MISMATCH); } if (!opts?.override) { // Check whether `newPath` exists because `fs.rename` doesn't throw when // `newPath` exists let newPathExists: boolean; if (itemType.file) { newPathExists = !!this.getFile(newPath); } else { const { files, folders } = this.getFolderContent(newPath); newPathExists = files.length > 0 || folders.length > 0; } if (newPathExists) throw new Error(ItemError.ALREADY_EXISTS); } // Rename in `indexedDB` if (!this.isTemporary) await this.fs.rename(oldPath, newPath); // Rename in state const files = this.files; const rename = (oldPath: string, newPath: string) => { // Store the item const item = files[oldPath]; // Delete the old item delete files[oldPath]; // Set the new path files[newPath] = item; // Handle tabs if it's a file if (PgExplorer.getItemTypeFromPath(newPath).file) { // Rename tabs manually instead of closing the old file and opening the // new file in order to keep the tab order const tabIndex = this.tabs.indexOf(oldPath); if (tabIndex !== -1) this._explorer.tabs[tabIndex] = newPath; } }; // Rename in state if (itemType.file) { rename(oldPath, newPath); // Moving all elements from a folder results with the parent folder // disappearing, add the folder back to mitigate files[PgExplorer.getParentPathFromPath(oldPath)] = {}; } else { // We need to loop through all files in order to change every child path for (const path in files) { // /programs/my_program/logs/logfile.log // If we are renaming 'my_program' then we can replace '/programs/my_program/' // with '/programs/<new_name>/' if (path.startsWith(oldPath)) { const childPath = path.replace( oldPath, oldPath.endsWith("/") ? PgCommon.appendSlash(newPath) : newPath ); rename(path, childPath); } } } // Set tabs to close the duplicate paths if (opts?.override) this.setTabs(this.tabs); // Keep the same current file after rename PgExplorerEvent.dispatchOnDidOpenFile(this.getCurrentFile()!); PgExplorerEvent.dispatchOnDidRenameItem(oldPath); await this.saveMeta(); } /** * If the project is not temporary(default): * - Delete from `indexedDB`(recursively) * - If delete is successful, delete from state * * If the project is temporary: * - Delete from state */ static async deleteItem(path: string) { const fullPath = this.convertToFullPath(path); // Can't delete src folder if (PgCommon.isPathsEqual(fullPath, this.getCurrentSrcPath())) { throw new Error(ItemError.SRC_DELETE); } if (!this.isTemporary) { const metadata = await this.fs.getMetadata(fullPath); if (metadata.isFile()) await this.fs.removeFile(fullPath); else await this.fs.removeDir(fullPath, { recursive: true }); } // If we are deleting current file's parent(s), we need to set the current // file to the last tab const isCurrentFile = this.currentFilePath === fullPath; const isCurrentParent = this.currentFilePath?.startsWith(fullPath); for (const path in this.files) { if (path.startsWith(fullPath)) { delete this.files[path]; this.closeFile(path); } } // Deleting all elements from a folder results with the parent folder // disappearing, add the folder back to mitigate this.files[PgExplorer.getParentPathFromPath(fullPath)] = {}; // Change the current file to the closest tab when current file or its // parent is deleted if (isCurrentFile || isCurrentParent) { const lastTabPath = this.tabs.at(-1); if (lastTabPath) this.openFile(lastTabPath); } PgExplorerEvent.dispatchOnDidDeleteItem(fullPath); await this.saveMeta(); } /** * Create a new workspace and change the current workspace to the created workspace. * * @param name new workspace name * @param opts - * - `files`: `TupleFiles` to create the workspace from * - `defaultOpenFile`: default file to open in the editor * - `fromTemporary`: whether to create new workspace from a temporary project * - `skipNameValidation`: whether to skip workspace name validation */ static async newWorkspace( name: string, opts?: { files?: TupleFiles; defaultOpenFile?: string; fromTemporary?: boolean; skipNameValidation?: boolean; } ) { name = name.trim(); if (!opts?.skipNameValidation && !this.isWorkspaceNameValid(name)) { throw new Error(WorkspaceError.INVALID_NAME); } if (opts?.fromTemporary && this.isTemporary) { // The reason we are not just getting the necessary files and re-calling this // function with { files } is because we would lose the tab info. Instead we // are creating a valid workspace state and writing it to `indexedDB`. // Init workspace await this._initWorkspaces(); // Create a new workspace in state this._workspace!.new(name); // It's important to set `_isTemporary` after the workspace is created, // otherwise there is a chance the creation fails, and the state ends up // being invalid. // See https://github.com/solana-playground/solana-playground/issues/275 this._isTemporary = false; // Change state paths(temporary projects start with /src) const getFullPath = (path: string) => { return PgCommon.joinPaths(PgExplorer.PATHS.ROOT_DIR_PATH, name, path); }; for (const path in this.files) { const data = this.files[path]; delete this.files[path]; this.files[getFullPath(path)] = data; } this.setTabs(this.tabs.map(getFullPath)); // Save files from state to `indexedDB` await this._writeAllFromState(); await this.switchWorkspace(name); return; } if (!this._workspace) throw new Error(WorkspaceError.NOT_FOUND); // Create a new workspace in state this._workspace.new(name); // Create files if (opts?.files) { for (const [path, content] of opts.files) { await this.fs.writeFile(path, content, { createParents: true }); } // Set the default open file opts.defaultOpenFile ??= this._getDefaultOpenFile(opts.files); } await this.switchWorkspace(name, { defaultOpenFile: opts?.defaultOpenFile, }); PgExplorerEvent.dispatchOnDidCreateWorkspace(); } /** * Change the current workspace to the given workspace. * * @param name workspace name to change to * @param opts - * - `defaultOpenFile`: the file to open in the editor */ static async switchWorkspace( name: string, opts?: { defaultOpenFile?: string } ) { // Save metadata before changing the workspace to never lose data await this.saveMeta(); // Set the workspace this.setWorkspaceName(name); await this._saveWorkspaces(); // Initialize the workspace await this._initCurrentWorkspace(); // Open the default file if it has been specified if (opts?.defaultOpenFile) { this.openFile(opts.defaultOpenFile); // Save metadata to never lose default open file await this.saveMeta(); } else { PgExplorerEvent.dispatchOnDidOpenFile(this.getCurrentFile()!); } // Set initialized workspace name this._initializedWorkspaceName = name; // Dispatch change event PgExplorerEvent.dispatchOnDidSwitchWorkspace(); } /** * Rename the current workspace. * * @param newName new workspace name */ static async renameWorkspace(newName: string) { newName = newName.trim(); if (!this._workspace) { throw new Error(WorkspaceError.NOT_FOUND); } if (!this.currentWorkspaceName) { throw new Error(WorkspaceError.CURRENT_NOT_FOUND); } if (!this.isWorkspaceNameValid(newName)) { throw new Error(WorkspaceError.INVALID_NAME); } if (this.allWorkspaceNames!.includes(newName)) { throw new Error(WorkspaceError.ALREADY_EXISTS); } // Rename workspace folder const newPath = this.currentWorkspacePath.replace( this.currentWorkspaceName, newName ); await this.renameItem(this.currentWorkspacePath, newPath, { skipNameValidation: true, }); // Rename workspace in state this._workspace.rename(newName); await this.switchWorkspace(newName); PgExplorerEvent.dispatchOnDidRenameWorkspace(); } /** Delete the current workspace. */ static async deleteWorkspace() { if (!this._workspace) { throw new Error(WorkspaceError.NOT_FOUND); } if (!this.currentWorkspaceName) { throw new Error(WorkspaceError.CURRENT_NOT_FOUND); } // Delete from `indexedDB` await this.deleteItem(this.currentWorkspacePath); // Delete from state this._workspace.delete(this.currentWorkspaceName); const workspaceCount = this._workspace.allNames.length; if (workspaceCount) { const lastWorkspace = this._workspace.allNames[workspaceCount - 1]; await this.switchWorkspace(lastWorkspace); } else { this._workspace.setCurrent({ allNames: [] }); await this._saveWorkspaces(); PgExplorerEvent.dispatchOnDidSwitchWorkspace(); } PgExplorerEvent.dispatchOnDidDeleteWorkspace(); } /** * Saves file metadata to `indexedDB` * * NOTE: Only runs when the project is not temporary. */ static async saveMeta() { const paths = Object.keys(this.files); if (!this.currentWorkspaceName || !paths.length) return; // Check whether the files start with the correct workspace path const isInvalidState = paths.some( (path) => !path.startsWith(this.currentWorkspacePath) ); if (isInvalidState) return; const metaFile = paths .reduce((acc, path) => { // Only save the files in the current workspace if (path.startsWith(this.currentWorkspacePath)) { acc.push({ path, isTabs: this.tabs.includes(path), isCurrent: this.currentFilePath === path, position: this.files[path].meta?.position, }); } return acc; }, [] as ItemMetaFile) .sort((a, b) => { // Sort based on tab order if (!a.isTabs) return 1; if (!b.isTabs) return -1; return this.tabs.indexOf(a.path) - this.tabs.indexOf(b.path); }) .map((meta) => ({ ...meta, path: this.getRelativePath(meta.path) })); // Save file await this.fs.writeFile( PgWorkspace.METADATA_PATH, JSON.stringify(metaFile), { createParents: true } ); } /* ----------------------------- State methods ---------------------------- */ /** * Get all files as `TupleFiles` * * @returns all files as an array of [path, content] tuples */ static getAllFiles() { return this._convertToTupleFiles(this.files); } /** * Save the file to the state only. * * @param path file path * @param content file content */ static saveFileToState(path: string, content: string) { path = this.convertToFullPath(path); if (this.files[path]) this.files[path].content = content; } /** * Get the full file data. * * @param path path of the file, defaults to the current file if it exists */ static getFile(path: string): FullFile | null { path = this.convertToFullPath(path); const itemInfo = this.files[path]; if (itemInfo) return { path, ...this.files[path] }; return null; } /** * Get file content from state. * * @param path file path * @returns the file content from state */ static getFileContent(path: string) { return this.getFile(path)?.content; } /** * Get the item names from inside the given folder and group them into * `files` and `folders`. * * @param path folder path * @returns the groupped folder items */ static getFolderContent(path: string) { path = PgCommon.appendSlash(PgExplorer.convertToFullPath(path)); const files = this.files; const filesAndFolders: Folder = { folders: [], files: [] }; for (const itemPath in files) { if (itemPath.startsWith(path)) { const item = itemPath.split(path)[1].split("/")[0]; if ( !filesAndFolders.files.includes(item) && !filesAndFolders.folders.includes(item) && item ) { // It's a file if it contains '.' // TODO: Implement a better system for folders and files if (item.includes(".")) filesAndFolders.files.push(item); else filesAndFolders.folders.push(item); } } } return filesAndFolders; } /** * Get the current open file from state if it exists. * * @returns the current file */ static getCurrentFile() { if (this.currentFilePath) return this.getFile(this.currentFilePath); return null; } /** * Get the current file's language from it's path. * * @returns the current language name */ static getCurrentFileLanguage() { if (this.currentFilePath) { return PgLanguage.getFromPath(this.currentFilePath); } } /** * Get whether current file is a regular JS/TS or test JS/TS file. * * @returns whether the current file is a JavaScript-like file */ static isCurrentFileJsLike() { if (this.currentFilePath) { return PgLanguage.getIsPathJsLike(this.currentFilePath); } } /** * Open the file at the given path. * * This method mutates the existing tabs array. * * @param path file path */ static openFile(path: string) { path = this.convertToFullPath(path); // Return if it's already the current file if (this.currentFilePath === path) return; // Add to tabs if it hasn't yet been added if (!this.tabs.includes(path)) this._explorer.tabs.push(path); // Update the current file index this._explorer.currentIndex = this.tabs.indexOf(path); PgExplorerEvent.dispatchOnDidOpenFile(this.getCurrentFile()!); } /** * Close the file at the given path. * This method mutates the existing tabs array. * * @param path file path */ static closeFile(path: string) { path = this.convertToFullPath(path); // If closing the current file, change the current file to the next tab if (this.currentFilePath === path) { const pathToOpen = this.tabs.at(this._currentIndex + 1) ?? this.tabs.at(-2); if (pathToOpen) this.openFile(pathToOpen); } // Update tabs and the current index if (this.currentFilePath) { this._explorer.tabs.splice(this.tabs.indexOf(path), 1); this._explorer.currentIndex = this.tabs.indexOf(this.currentFilePath); } PgExplorerEvent.dispatchOnDidCloseFile(); } /** * Set the tab paths without duplication. * * @param tabs tab paths to set */ static setTabs(tabs: readonly string[]) { const currentPath = this.currentFilePath; this._explorer.tabs = [...new Set(tabs)]; if (currentPath) { this._explorer.currentIndex = this.tabs.indexOf(currentPath); } PgExplorerEvent.dispatchOnDidSetTabs(); } /** * Get the position data for the file from state. * * @param path file path * @returns the file's position data */ static getEditorPosition(path: string): Position { return ( this.getFile(path)?.meta?.position ?? { cursor: { from: 0, to: 0 }, topLineNumber: 1, } ); } /** * Save editor position data to state. * * @param path file path * @param position position data */ static saveEditorPosition(path: string, position: Position) { path = this.convertToFullPath(path); this.files[path].meta ??= {}; this.files[path].meta!.position = position; } /** * Set the current workspace name. * * @param name workspace name */ static setWorkspaceName(name: string) { this._workspace!.setCurrentName(name); } /** * Get the path without the workspace path prefix. * * @param fullPath full path * @returns the relative path */ static getRelativePath(fullPath: string) { // /src/lib.rs -> src/lib.rs if (PgExplorer.isTemporary) return fullPath.substring(1); // /name/src/lib.rs -> src/lib.rs return fullPath.replace(PgExplorer.currentWorkspacePath, ""); } /** * Get the canonical path, i.e. the full path from the project root and * directory paths end with `/`. * * @param path item path * @returns the canonical path */ static getCanonicalPath(path: string) { path = PgExplorer.convertToFullPath(path); if (PgExplorer.getItemTypeFromPath(path).file) return path; return PgCommon.appendSlash(path); } // TODO: Path module /** * Convert the given path to a full path. * * @param path path to convert * @returns the full path */ static convertToFullPath(path: string) { // Return absolute path if (path.startsWith(this.PATHS.ROOT_DIR_PATH)) return path; // Convert to absolute path if it doesn't start with '/' return PgCommon.joinPaths(this.getProjectRootPath(), path); } /** * Get the current project root path. * * This is not to be confused with root path(`/`). * * @returns the current project root path */ static getProjectRootPath() { return this.isTemporary ? this.PATHS.ROOT_DIR_PATH : this.currentWorkspacePath; } /** * Get the current `src` directory path. * * @returns the current `src` directory path with `/` appended */ static getCurrentSrcPath() { const srcPath = PgCommon.joinPaths( this.getProjectRootPath(), this.PATHS.SRC_DIRNAME ); return PgCommon.appendSlash(srcPath); } /* --------------------------- Change listeners --------------------------- */ /** * Runs after explorer state has changed and the UI needs to re-render. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onNeedRender(cb: () => unknown) { return PgCommon.batchChanges(cb, [ PgExplorer.onDidInit, PgExplorer.onDidCreateItem, PgExplorer.onDidDeleteItem, PgExplorer.onDidOpenFile, PgExplorer.onDidCloseFile, ]); } /** * Runs after explorer has been initialized. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidInit(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_INIT, }); } /** * Runs after creating a new item. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidCreateItem(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_CREATE_ITEM, }); } /** * Runs after renaming an item. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidRenameItem(cb: (path: string) => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_RENAME_ITEM, }); } /** * Runs after deleting an item. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidDeleteItem(cb: (path: string) => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_DELETE_ITEM, }); } /** * Runs after switching to a different file. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidOpenFile(cb: (file: FullFile | null) => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_OPEN_FILE, initialRun: { value: PgExplorer.getCurrentFile() }, }); } /** * Runs after closing a file. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidCloseFile(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_CLOSE_FILE, }); } /** * Runs after setting tabs. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidSetTabs(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_SET_TABS, }); } /** * Runs after creating a workspace. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidCreateWorkspace(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_CREATE_WORKSPACE, }); } /** * Runs after renaming a workspace. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidRenameWorkspace(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_RENAME_WORKSPACE, }); } /** * Runs after deleting a workspace. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidDeleteWorkspace(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_DELETE_WORKSPACE, }); } /** * Runs after switching to a different workspace. * * @param cb callback function to run * @returns a dispose function to clear the event */ static onDidSwitchWorkspace(cb: () => unknown) { return PgCommon.onDidChange({ cb, eventName: PgExplorerEvent.ON_DID_SWITCH_WORKSPACE, }); } /* ---------------------------- Private methods --------------------------- */ /** * Initialize explorer with the current workspace. * * Only the current workspace at a time will be in the memory. */ private static async _initCurrentWorkspace() { if (!this._workspace) { throw new Error(WorkspaceError.NOT_FOUND); } // Reset files this._explorer.files = {}; // Sets up the files from `indexedDB` to the state const setupFiles = async (path: string) => { const itemNames = await this.fs.readDir(path); // Empty directory if (!itemNames.length) { this.files[path] = {}; return; } const subItemPaths = itemNames .filter(PgExplorer.isItemNameValid) .map((itemName) => { return PgExplorer.getCanonicalPath( PgCommon.joinPaths(path, itemName) ); }); for (const subItemPath of subItemPaths) { const metadata = await this.fs.getMetadata(subItemPath); if (metadata.isFile()) { try { // This might fail if the user closes the window when a file delete // operation has not been completed yet const content = await this.fs.readToString(subItemPath); this.files[subItemPath] = { content }; } catch (e: any) { console.log(`Couldn't read to string: ${e.message} ${subItemPath}`); } } else { await setupFiles(subItemPath); } } }; try { await setupFiles(this.currentWorkspacePath); } catch (e: any) { console.log("Couldn't setup files:", e.message); // The most likely cause for `setupFiles` failure is if the current // workspace doesn't exist in the filesystem but it's saved as the // current workspace. To fix this, set the current workspace name to // either the last workspace, or reset all workspaces in the case of no // valid workspace directory in `/`. if (this._workspace.allNames.length) { const rootDirs = await this.fs.readDir(PgExplorer.PATHS.ROOT_DIR_PATH); const workspaceDirs = rootDirs.filter(PgExplorer.isItemNameValid); if (!workspaceDirs.length) { // Reset workspaces since there is no workspace directories this._workspace = new PgWorkspace(); } else { // Open the last workspace const lastWorkspaceName = workspaceDirs[workspaceDirs.length - 1]; this._workspace.rename(lastWorkspaceName); } await this._saveWorkspaces(); await this._initCurrentWorkspace(); return; } console.log("No workspace found. Most likely needs initial setup."); } // Runs when `indexedDB` is empty if (!Object.keys(this.files).length && !this.allWorkspaceNames?.length) { console.log("Setting up default FS..."); // For backwards compatibility reasons, we check whether explorer key is used in localStorage // and move the localStorage FS to `indexedDB`. // TODO: delete this check after moving domains const lsExplorerStr = localStorage.getItem("explorer"); if (lsExplorerStr) { // Create a default workspace this._workspace.new(PgWorkspace.DEFAULT_WORKSPACE_NAME); // Save workspaces await this._saveWorkspaces(); const lsExplorer: Explorer = JSON.parse(lsExplorerStr); const lsFiles = lsExplorer.files; for (const path in lsFiles) { const oldData = lsFiles[path]; delete lsFiles[path]; lsFiles[ path.replace( PgExplorer.PATHS.ROOT_DIR_PATH, this.currentWorkspacePath ) ] = { content: oldData.content, // @ts-ignore // ignoring because the type of oldData changed meta: { current: oldData.current, tabs: oldData.tabs }, }; } this._explorer.files = lsFiles; } else { // There are no files in state and `indexedDB` // return and show create a project option return; } // Save file(s) to `indexedDB` await this._writeAllFromState(); // Create tab info file await this.saveMeta(); } // Load metadata info from `indexedDB` let metaFile = await this.fs.readToJSONOrDefault<ItemMetaFile>( PgWorkspace.METADATA_PATH, [] ); // Convert the old metadata file // TODO: Delete in 2024 if (!Array.isArray(metaFile)) { type OldItemMetaFile = Record< string, { current?: boolean; tabs?: boolean; position?: Position; } >; const oldMetaFile = metaFile as OldItemMetaFile; metaFile = []; for (const path in oldMetaFile) { const meta = oldMetaFile[path]; metaFile.push({ path, isTabs: meta.tabs, isCurrent: meta.current, position: meta.position, }); } } // Metadata file paths are relative, convert to full path const fullPathMetaFile = metaFile.map((meta) => ({ ...meta, path: this.convertToFullPath(meta.path), })); // Tabs const tabs = fullPathMetaFile .filter((meta) => meta.isTabs) .map((meta) => meta.path); this.setTabs(tabs); // Current const current = fullPathMetaFile.find((meta) => meta.isCurrent); this._explorer.currentIndex = current ? this.tabs.indexOf(current.path) : -1; // Metadata for (const itemMeta of fullPathMetaFile) { const file = this.files[itemMeta.path]; if (file?.content !== undefined) { file.meta = { position: itemMeta.position }; } } } /** Write all state data to `indexedDB`. */ private static async _writeAllFromState() { for (const path in this.files) { const itemType = PgExplorer.getItemTypeFromPath(path); if (itemType.file) { await this.fs.writeFile(path, this.files[path].content ?? "", { createParents: true, }); } else { await this.fs.createDir(path, { createParents: true }); } } } /** * Read workspaces config from `indexedDB`. * * @returns the workspaces state */ private static async _getWorkspaces() { return await this.fs.readToJSONOrDefault( PgWorkspace.WORKSPACES_CONFIG_PATH, PgWorkspace.DEFAULT ); } /** Initialize workspaces from `indexedDB` to state. */ private static async _initWorkspaces() { const workspaces = await this._getWorkspaces(); this._workspace ??= new PgWorkspace(); this._workspace.setCurrent(workspaces); await this._saveWorkspaces(); } /** Saves workspaces from state to `indexedDB`. */ private static async _saveWorkspaces() { if (this._workspace) { await this.fs.writeFile( PgWorkspace.WORKSPACES_CONFIG_PATH, JSON.stringify(this._workspace.get()), { createParents: true } ); } } /** * Get the default explorer state. * * NOTE: This is intentionally a method instead of a property in order to create a * new object each time since explorer methods mutate the existing object. * * @returns the default explorer state */ private static _getDefaultState(): Explorer { return { files: {}, tabs: [], currentIndex: -1, }; } /* ------------------------------- Utilities ------------------------------ */ /** Paths */ static readonly PATHS = { ROOT_DIR_PATH: "/", SRC_DIRNAME: "src", CLIENT_DIRNAME: "client", TESTS_DIRNAME: "tests", }; /** * Get item's name from its path. * * @param path item path * @returns the item name */ static getItemNameFromPath(path: string) { const items = path.split("/"); const name = path.endsWith("/") ? items.at(-2) : items.at(-1); return name!; } // TODO: Implement a better identifier /** * Get the item's type from its name. * * @param itemName item name * @returns the item type */ static getItemTypeFromName(itemName: string) { if (itemName.includes(".")) return { file: true }; return { folder: true }; } /** * Get the item's type from its path. * * @param path item path * @returns the item type */ static getItemTypeFromPath(path: string) { return PgExplorer.getItemTypeFromName(PgExplorer.getItemNameFromPath(path)); } /** * Get the item's type from the given element. * * @param el item element * @returns the item type */ static getItemTypeFromEl(el: HTMLDivElement) { const path = PgExplorer.getItemPathFromEl(el); if (path) return PgExplorer.getItemTypeFromPath(path); } /** * Get the item's path from the given element. * * @param el item element * @returns the item path */ static getItemPathFromEl(el: Element) { return el?.getAttribute("data-path"); } /** * Get the parent's path from the given path with `/` appended. * * @param path item path * @returns the parent path */ static getParentPathFromPath(path: string) { const itemType = this.getItemTypeFromPath(path); const names = path.split("/"); const parentPath = path .split("/") .filter((_itemName, i) => i !== names.length - (itemType.file ? 1 : 2)) .reduce((acc, itemName) => { if (itemName) return (acc += `/${itemName}`); return acc; }); return PgCommon.appendSlash(parentPath); } /** * Get the parent path from the given element. * * @param el item element * @returns the parent path */ static getParentPathFromEl(el: HTMLDivElement) { const itemType = PgExplorer.getItemTypeFromEl(el); if (itemType?.folder) { return PgExplorer.getItemPathFromEl(el); } else if (itemType?.file) { // The file's owner folder is parent element's previous sibling return PgExplorer.getItemPathFromEl( el.parentElement!.previousElementSibling as HTMLDivElement ); } } /** * Get the eleemnt from its path. * * @param path item path * @returns the element */ static getElFromPath(path: string) { return document.querySelector(`[data-path='${path}']`) as | HTMLDivElement | undefined; } /** Get the root folder elemement. */ static getRootFolderEl() { return document.getElementById(Id.ROOT_DIR); } /** Get the current selected element. */ static getSelectedEl() { return document.getElementsByClassName(ClassName.SELECTED)[0] as | HTMLDivElement | undefined; } /** * Set the current selected element. * * @param newEl new element to select */ static setSelectedEl(newEl: HTMLDivElement) { PgExplorer.getSelectedEl()?.classList.remove(ClassName.SELECTED); newEl.classList.add(ClassName.SELECTED); } /** Get the selected context element. */ static getCtxSelectedEl() { const ctxSelectedEls = document.getElementsByClassName( ClassName.CTX_SELECTED ); if (ctxSelectedEls.length) return ctxSelectedEls[0]; } /** Set the selected context element. */ static setCtxSelectedEl(newEl: HTMLDivElement) { PgExplorer.removeCtxSelectedEl(); newEl.classList.add(ClassName.CTX_SELECTED); } /** Remove the selected context element. */ static removeCtxSelectedEl() { PgExplorer.getCtxSelectedEl()?.classList.remove(ClassName.CTX_SELECTED); } /** * Open the given folder element. * * @param el folder element */ static openFolder(el: HTMLDivElement) { // Folder icon el.classList.add(ClassName.OPEN); // Toggle inside folder const insideFolderEl = el.nextElementSibling; if (insideFolderEl) insideFolderEl.classList.remove(ClassName.HIDDEN); } /** * Toggle open/close state of the given folder element. * * @param el folder element */ static toggleFolder(el: HTMLDivElement) { // Folder icon el.classList.toggle(ClassName.OPEN); // Toggle inside folder const insideFolderEl = el.nextElementSibling; if (insideFolderEl) insideFolderEl.classList.toggle(ClassName.HIDDEN); } /** * Recursively open all parent folders of the given path. * * @param path item path */ static openAllParents(path: string) { for (;;) { const parentPath = this.getParentPathFromPath(path); const parentEl = this.getElFromPath(parentPath); if (!parentEl) break; this.openFolder(parentEl); if (parentPath === this.PATHS.ROOT_DIR_PATH) break; path = parentPath; } } /** Collapse all folders in the UI. */ static collapseAllFolders() { // Close all folders const folderElements = document.getElementsByClassName(ClassName.FOLDER); for (const folder of folderElements) { folder.classList.remove(ClassName.OPEN); } // Hide all folder inside elements const insideElements = document.getElementsByClassName( ClassName.FOLDER_INSIDE ); for (const folderInside of insideElements) { folderInside.classList.add(ClassName.HIDDEN); } } /** * Get whether the given name can be used for an item. * * @param name item name * @returns whether the item name is valid */ static isItemNameValid(name: string) { return ( /^(?![.])[\w\d.-/]+/.test(name) && !name.includes("//") && !name.includes("..") && !name.endsWith("/") && !name.endsWith(".") ); } /** * Get whether the given name can be used for a workspace. * * @param name item name * @returns whether the workspace name is valid */ static isWorkspaceNameValid(name: string) { return !!name.match(/^(?!\s)[\w\s-]+$/); } /* --------------------------- Private utilities -------------------------- */ /** * Convert the given `ExplorerFiles` to `TupleFiles`. * * @returns all files as an array of [path, content] tuples */ private static _convertToTupleFiles(explorerFiles: ExplorerFiles) { const tupleFiles: TupleFiles = []; for (const path in explorerFiles) { const content = explorerFiles[path].content; if (content !== undefined) tupleFiles.push([path, content]); } return tupleFiles; } /** * Convert the given `TupleFiles` to `ExplorerFiles`. * * @param tupleFiles tuple files to convert * @returns the converted `ExplorerFiles` */ private static _convertToExplorerFiles(tupleFiles: TupleFiles) { const explorerFiles: ExplorerFiles = {}; for (const [path, content] of tupleFiles) { const fullPath = PgCommon.joinPaths(PgExplorer.PATHS.ROOT_DIR_PATH, path); explorerFiles[fullPath] = { content }; } return explorerFiles; } /** * Get the default open file from the given tuple files. * * @param files tuple or explorer files * @returns the default open file path */ private static _getDefaultOpenFile(files: TupleFiles | ExplorerFiles) { if (!Array.isArray(files)) files = this._convertToTupleFiles(files); let defaultOpenFile: string | undefined; const libRsFile = files.find(([path]) => path.endsWith("lib.rs")); if (libRsFile) { defaultOpenFile = libRsFile[0]; } else if (files.length) { defaultOpenFile = files[0][0]; } return defaultOpenFile; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/explorer/types.ts
import type { TupleString } from "../types"; /** Playground explorer */ export interface Explorer { /** Explorer files */ files: ExplorerFiles; /** Full path of the files in tabs */ tabs: string[]; /** Current file index(in tabs) */ currentIndex: number; } /** Full path -> `ItemInfo` */ export type ExplorerFiles = Record<string, ItemInfo>; /** `ItemInfo` with `path` property */ export interface FullFile extends ItemInfo { /** Path to the file */ path: string; } /** File or directory item */ interface ItemInfo { /** Contents of the file */ content?: string; /** Metadata about the file */ meta?: ItemMeta; } /** * Item metadata file. * * Intentionally using an `Array` instead of a map to keep the tab order. */ export type ItemMetaFile = Array< { /** Relative path */ path: string; /** Whether the file is in tabs */ isTabs?: boolean; /** Whether the file is the current file */ isCurrent?: boolean; } & ItemMeta >; /** Item metadata */ interface ItemMeta { /** Position data */ position?: Position; } /** Editor position data */ export interface Position { /** Editor's visible top line number */ topLineNumber: number; /** Editor cursor position */ cursor: { /** Start index */ from: number; /** End index */ to: number; }; } /** Folder content */ export interface Folder { /** Sub file names */ files: string[]; /** Sub folder names */ folders: string[]; } /** Array<[Path, Content]> */ export type TupleFiles = TupleString[];
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/explorer/events.ts
import { PgCommon } from "../common"; import type { FullFile } from "./types"; export class PgExplorerEvent { /** `onDidCreateItem` event name */ static readonly ON_DID_INIT = "explorerondidinit"; /** `onDidCreateItem` event name */ static readonly ON_DID_CREATE_ITEM = "explorerondidcreateitem"; /** `onDidRenameItem` event name */ static readonly ON_DID_RENAME_ITEM = "explorerondidrenameitem"; /** `onDidDeleteItem` event name */ static readonly ON_DID_DELETE_ITEM = "explorerondiddeleteitem"; /** `onDidOpenFile` event name */ static readonly ON_DID_OPEN_FILE = "explorerondidopenfile"; /** `onDidCloseFile` event name */ static readonly ON_DID_CLOSE_FILE = "explorerondidclosefile"; /** `onDidSetTabs` event name */ static readonly ON_DID_SET_TABS = "explorerondidsettabs"; /** `onDidCreateWorkspace` event name */ static readonly ON_DID_CREATE_WORKSPACE = "explorerondidcreateworkspace"; /** `onDidRenameWorkspace` event name */ static readonly ON_DID_RENAME_WORKSPACE = "explorerondidrenameworkspace"; /** `onDidDeleteWorkspace` event name */ static readonly ON_DID_DELETE_WORKSPACE = "explorerondiddeleteworkspace"; /** `onDidSwitchWorkspace` event name */ static readonly ON_DID_SWITCH_WORKSPACE = "explorerondidswitchworkspace"; /** Dispatch an `onDidInit` event. */ static dispatchOnDidInit() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_INIT); } /** Dispatch an `onDidCreateItem` event. */ static dispatchOnDidCreateItem() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_CREATE_ITEM); } /** Dispatch an `onDidRenameItem` event. */ static dispatchOnDidRenameItem(path: string) { PgCommon.createAndDispatchCustomEvent(this.ON_DID_RENAME_ITEM, path); } /** Dispatch an `onDidDeleteItem` event. */ static dispatchOnDidDeleteItem(path: string) { PgCommon.createAndDispatchCustomEvent(this.ON_DID_DELETE_ITEM, path); } /** Dispatch an `onDidOpenFile` event. */ static dispatchOnDidOpenFile(file: FullFile | null) { PgCommon.createAndDispatchCustomEvent(this.ON_DID_OPEN_FILE, file); } /** Dispatch an `onDidCloseFile` event. */ static dispatchOnDidCloseFile() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_CLOSE_FILE); } /** Dispatch an `onDidSetTabs` event. */ static dispatchOnDidSetTabs() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_SET_TABS); } /** Dispatch an `onDidCreateWorkspace` event. */ static dispatchOnDidCreateWorkspace() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_CREATE_WORKSPACE); } /** Dispatch an `onDidRenameWorkspace` event. */ static dispatchOnDidRenameWorkspace() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_RENAME_WORKSPACE); } /** Dispatch an `onDidDeleteWorkspace` event. */ static dispatchOnDidDeleteWorkspace() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_DELETE_WORKSPACE); } /** Dispatch an `onDidSwitchWorkspace` event. */ static dispatchOnDidSwitchWorkspace() { PgCommon.createAndDispatchCustomEvent(this.ON_DID_SWITCH_WORKSPACE); } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/explorer/index.ts
export * from "./explorer"; export * from "./types";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tx/tx.ts
import { ExplorerLink } from "./ExplorerLink"; import { PgCommon } from "../common"; import { PgPlaynet } from "../playnet"; import { PgSettings } from "../settings"; import { PgView } from "../view"; import { ConnectionOption, PgConnection } from "../connection"; import { CurrentWallet, PgWallet, WalletOption } from "../wallet"; import { PgWeb3 } from "../web3"; type WithTimeStamp<T> = T & { /** UNIX timestamp of the last cache */ timestamp: number; }; type BlockhashInfo = WithTimeStamp<{ /** Latest blockhash */ blockhash: string; }>; type PriorityFeeInfo = WithTimeStamp<{ /** Average priority fee paid in the latest slots */ average: number; /** Median priority fee paid in the latest slots */ median: number; /** Minimum priority fee paid in the latest slots */ min: number; /** Maximum priority fee paid in the latest slots */ max: number; }>; export class PgTx { /** * Send a transaction with additional signer optionality. * * This method caches the latest blockhash in order to minimize the amount of * RPC requests. * * @returns the transaction signature */ static async send( tx: PgWeb3.Transaction, opts?: { keypairSigners?: PgWeb3.Signer[]; walletSigners?: CurrentWallet[]; forceFetchLatestBlockhash?: boolean; } & ConnectionOption & WalletOption ): Promise<string> { const wallet = opts?.wallet ?? PgWallet.current; if (!wallet) throw new Error("Wallet not connected"); const connection = opts?.connection ?? PgConnection.current; // Set priority fees if the transaction doesn't already have it const existingsetComputeUnitPriceIx = tx.instructions.find( (ix) => ix.programId.equals(PgWeb3.ComputeBudgetProgram.programId) && ix.data.at(0) === 3 // setComputeUnitPrice ); if (!existingsetComputeUnitPriceIx) { const priorityFeeInfo = await this._getPriorityFee(connection); const priorityFeeSetting = PgSettings.connection.priorityFee; const priorityFee = typeof priorityFeeSetting === "number" ? priorityFeeSetting : priorityFeeInfo[priorityFeeSetting]; if (priorityFee) { const setComputeUnitPriceIx = PgWeb3.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityFee, }); tx.instructions = [setComputeUnitPriceIx, ...tx.instructions]; } } tx.recentBlockhash = await this._getLatestBlockhash( connection, opts?.forceFetchLatestBlockhash ); tx.feePayer = wallet.publicKey; // Add keypair signers if (opts?.keypairSigners?.length) tx.partialSign(...opts.keypairSigners); // Add wallet signers if (opts?.walletSigners) { for (const walletSigner of opts.walletSigners) { tx = await walletSigner.signTransaction(tx); } } // Sign with the current wallet as it's always the fee payer tx = await wallet.signTransaction(tx); // Caching the blockhash will result in getting the same tx signature when // using the same tx data. // https://github.com/solana-playground/solana-playground/issues/116 let txHash; try { txHash = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: !PgSettings.connection.preflightChecks, }); } catch (e: any) { if ( e.message.includes("This transaction has already been processed") || e.message.includes("Blockhash not found") ) { // Reset signatures tx.signatures = []; return await this.send(tx, { ...opts, forceFetchLatestBlockhash: true, }); } throw e; } return txHash; } /** * Confirm a transaction. * * @throws if rpc request fails * @returns an object with `err` property if the rpc request succeeded but tx failed */ static async confirm( txHash: string, opts?: { commitment?: PgWeb3.Commitment } & ConnectionOption ) { const connection = opts?.connection ?? PgConnection.current; // Don't confirm on playnet if (PgPlaynet.isUrlPlaynet(connection.rpcEndpoint)) return; const result = await connection.confirmTransaction( txHash, opts?.commitment ); if (result?.value.err) return { err: result.value.err }; } /** * Show a notification toast with explorer links for the transaction. * * @param txHash transaction signature */ static notify(txHash: string) { // Check setting if (!PgSettings.notification.showTx) return; // Don't show on playnet if (PgPlaynet.isUrlPlaynet()) return; PgView.setToast(ExplorerLink, { componentProps: { txHash }, options: { toastId: txHash }, }); } /** Cached blockhash to reduce the amount of requests to the RPC endpoint */ private static _cachedBlockhashInfo: BlockhashInfo | null = null; /** Cached priority fee to reduce the amount of requests to the RPC endpoint */ private static _cachedPriorityFee: PriorityFeeInfo | null = null; /** * Get the latest blockhash from the cache or fetch the latest if the cached * blockhash has expired. * * @param conn `Connection` object to use * @param force whether to force fetch the latest blockhash * * @returns the latest blockhash */ private static async _getLatestBlockhash( conn: PgWeb3.Connection, force?: boolean ) { // Check whether the latest saved blockhash is still valid const timestamp = PgCommon.getUnixTimstamp(); // Blockhashes are valid for 150 slots, optimal block time is ~400ms // For finalized: (150 - 32) * 0.4 = 47.2s ~= 45s (to be safe) if ( force || !this._cachedBlockhashInfo || timestamp > this._cachedBlockhashInfo.timestamp + 45 ) { this._cachedBlockhashInfo = { blockhash: (await conn.getLatestBlockhash()).blockhash, timestamp, }; } return this._cachedBlockhashInfo.blockhash; } /** * Get the priority fee information from the cache or fetch the latest if the * cache has expired. * * @param conn `Connection` object to use * @returns the priority fee information */ private static async _getPriorityFee(conn: PgWeb3.Connection) { // Check whether the priority fee info has expired const timestamp = PgCommon.getUnixTimstamp(); // There is not a perfect way to estimate for how long the priority fee will // be valid since it's a guess about the future based on the past data if ( !this._cachedPriorityFee || timestamp > this._cachedPriorityFee.timestamp + 60 ) { const result = await conn.getRecentPrioritizationFees(); const fees = result.map((fee) => fee.prioritizationFee).sort(); this._cachedPriorityFee = { min: Math.min(...fees), max: Math.max(...fees), average: Math.ceil(fees.reduce((acc, cur) => acc + cur) / fees.length), median: fees[Math.floor(fees.length / 2)], timestamp, }; } return this._cachedPriorityFee; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tx/ExplorerLink.tsx
import { FC } from "react"; import styled from "styled-components"; import Link from "../../../components/Link"; import { useBlockExplorer } from "../../../hooks"; interface ExplorerLinkProps { txHash: string; } export const ExplorerLink: FC<ExplorerLinkProps> = ({ txHash }) => { const blockExplorer = useBlockExplorer(); return ( <Wrapper> <Link href={blockExplorer.getTxUrl(txHash)}>{blockExplorer.name}</Link> </Wrapper> ); }; const Wrapper = styled.div` display: flex; justify-content: space-around; & > a:hover { text-decoration: underline; } `;
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/tx/index.ts
export * from "./tx";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/theme/interface.ts
import { StandardProperties } from "csstype"; import { ITerminalOptions as XtermOptions } from "xterm"; import { ButtonKind } from "../../../components/Button"; import { MenuKind } from "../../../components/Menu"; import { TextKind } from "../../../components/Text"; import { AllRequired, ChildRequired, NestedRequired } from "../types"; /** Playground theme */ export interface Theme { /** Whether the theme is a dark theme */ isDark: boolean; /** * Colors of the theme. * * NOTE: Optional theme properties will be derived from the following colors * if they are not specified during creation. */ colors: { /** Default colors */ default: { primary: string; secondary: string; bgPrimary: string; bgSecondary: string; textPrimary: string; textSecondary: string; border: string; }; /** State colors */ state: { hover: StateColor; disabled: StateColor; error: StateColor; success: StateColor; warning: StateColor; info: StateColor; }; }; /** Default theme values */ default?: { /** Default backdrop */ backdrop?: DefaultStyles; /** Default border radius */ borderRadius?: StandardProperties["borderRadius"]; /** Default box shadow */ boxShadow?: StandardProperties["boxShadow"]; /** Default scrollbar */ scrollbar?: { thumb: { color: Color; hoverColor: Color; }; }; /** Default transparency values as hex string(00-ff) */ transparency?: { low: string; medium: string; high: string; }; /** Default transition settings */ transition?: { /** Timing function */ type: StandardProperties["transitionTimingFunction"]; /** Transition durations */ duration: { [K in | "short" | "medium" | "long"]: StandardProperties["transitionDuration"]; }; }; }; /** Override the component defaults */ components?: { /** Bottom bar component */ bottom?: ExtendibleComponent< "connect" | "endpoint" | "address" | "balance" >; /** Button component */ button?: OverridableComponent<ButtonKind>; /** Editor component */ editor?: { /** Editor defaults */ default?: BgAndColor & { cursorColor?: Color; activeLine?: BgAndColor & Pick<StandardProperties, "borderColor">; selection?: BgAndColor; searchMatch?: BgAndColor & { selectedBg?: Bg; selectedColor?: Color; }; } & Pick<StandardProperties, "fontFamily" | "fontSize">; /** Gutter component */ gutter?: BgAndColor & { activeBg?: Bg; activeColor?: Color; } & Pick<StandardProperties, "borderRight">; /** Inlay hints */ inlayHint?: BgAndColor & { parameterBg?: Bg; parameterColor?: Color; typeBg?: Bg; typeColor?: Color; }; /** Minimap component */ minimap?: { bg?: Bg; selectionHighlight?: Color; }; /** Peek view component */ peekView?: { /** Peek view title */ title?: { bg?: Bg; labelColor?: Color; descriptionColor?: Color; }; /** Peek view editor */ editor?: { bg?: Bg; matchHighlightBg?: Bg; gutterBg?: Bg; }; /** Peek view result(right side) */ result?: { bg?: Bg; lineColor?: Color; fileColor?: Color; selectionBg?: Bg; selectionColor?: Color; matchHighlightBg?: Bg; }; } & Pick<StandardProperties, "borderColor">; /** Tooltip or widget component */ tooltip?: BgAndColor & { selectedBg?: Bg; selectedColor?: Color; } & Pick<StandardProperties, "borderColor">; /** Editor wrapper component */ wrapper?: DefaultComponent; }; /** Input component */ input?: DefaultComponent; /** Main component */ main?: ExtendibleComponent<{ /** Main primary component */ primary?: ExtendibleComponent<{ /** Home component */ home?: ExtendibleComponent<{ /** Playground title */ title?: DefaultComponent; /** Resources section */ resources?: ExtendibleComponent<{ /** Resources title */ title?: DefaultComponent; /** Resource card */ card?: ExtendibleComponent< "image" | "title" | "description" | "button" >; }>; /** Tutorials section */ tutorials?: ExtendibleComponent<"title" | "card">; }>; /** Tutorial component */ tutorial?: ExtendibleComponent<"aboutPage" | "tutorialPage">; /** Tutorials page component */ tutorials?: ExtendibleComponent<{ /** Tutorials top section */ top?: DefaultComponent; /** Tutorials main section */ main?: ExtendibleComponent<{ /** Side section (left filters) */ side?: DefaultComponent; /** Content section (right tutorials) */ content?: ExtendibleComponent<{ /** Tutorial card component */ card?: ExtendibleComponent<"gradient">; /** Featured tutorial component */ featured?: DefaultComponent; }>; }>; }>; /** Programs page component */ programs?: ExtendibleComponent<{ /** Programs top section */ top?: DefaultComponent; /** Programs main section */ main?: ExtendibleComponent<{ /** Program main content component */ content?: ExtendibleComponent<"card">; }>; }>; }>; /** Main secondary component */ secondary?: ExtendibleComponent<{}>; }>; /** Markdown component */ markdown?: DefaultComponent & { subtleBg?: Bg }; /** Menu component */ menu?: OverridableComponent<MenuKind>; /** Modal component */ modal?: ExtendibleComponent<"backdrop" | "top" | "content" | "bottom">; /** Progress bar component */ progressbar?: ExtendibleComponent<"indicator">; /** Select component */ select?: ExtendibleComponent< | "control" | "menu" | "option" | "singleValue" | "input" | "groupHeading" | "dropdownIndicator" | "indicatorSeparator" >; /** Sidebar component */ sidebar?: ExtendibleComponent<{ /** Left side of the side panel(icon panel) */ left?: ExtendibleComponent<{ /** Left sidebar icon button */ button?: ExtendibleComponent<"selected">; }>; /** Right side of the side panel */ right?: ExtendibleComponent< "title", { otherBg?: Bg; initialWidth?: StandardProperties["width"] } >; }>; /** Skeleton component */ skeleton?: DefaultComponent & { highlightColor?: Color; }; /** Tabs component */ tabs?: ExtendibleComponent<{ tab?: ExtendibleComponent< "selected" | "current" | "drag" | "dragOverlay" >; }>; /** Terminal component */ terminal?: ExtendibleComponent<{ xterm?: { [K in | "textPrimary" | "textSecondary" | "primary" | "secondary" | "success" | "error" | "warning" | "info"]?: Color; } & { selectionBg?: Bg; cursor?: { color?: Color; accentColor?: Color; blink?: XtermOptions["cursorBlink"]; kind?: XtermOptions["cursorStyle"]; }; }; }>; /** Text component */ text?: OverridableComponent<TextKind>; /** Notification toast component */ toast?: ExtendibleComponent<"progress" | "closeButton">; /** Tooltip component */ tooltip?: DefaultStyles & { bgSecondary?: Bg }; /** Upload area component */ uploadArea?: ExtendibleComponent<{ /** Upload icon */ icon?: DefaultComponent; /** Upload message */ text?: ExtendibleComponent<"error" | "success">; }>; /** Wallet component */ wallet?: ExtendibleComponent<{ /** Top side of the wallet component */ top?: ExtendibleComponent<{ /** Wallet title component */ title?: ExtendibleComponent<"icon" | "text">; }>; /** Main side of the wallet component */ main?: ExtendibleComponent<{ /** Backdrop is made with `::after` pseudo class */ backdrop?: DefaultStyles; /** Balance section */ balance?: DefaultComponent; /** Send section */ send?: ExtendibleComponent<{ /** Send section foldable title text */ title?: DefaultComponent; /** Expanded send component */ expanded?: ExtendibleComponent<"input" | "sendButton">; }>; /** Transaction history section */ transactions?: ExtendibleComponent<{ /** Transactions title */ title?: ExtendibleComponent<"text" | "refreshButton">; /** Transactions table */ table?: ExtendibleComponent<{ /** Transactions table header */ header?: DefaultComponent; /** Transactions table row */ row?: ExtendibleComponent<"signature" | "slot" | "time">; }>; }>; }>; }>; }; /** Code highlight styles */ highlight: Highlight; } /** Syntax highlighting styles */ export interface Highlight { // const x: _bool_ = true; typeName: HighlightToken; // let _x_: bool = true; variableName: HighlightToken; // _String_::new(); namespace: HighlightToken; // _println!_() macroName: HighlightToken; // _myFn_() functionCall: HighlightToken; // a._to_lowercase_() functionDef: HighlightToken; // myFn(_arg_: bool) functionArg: HighlightToken; // const macro_rules struct union enum type fn impl trait let static definitionKeyword: HighlightToken; // mod use crate moduleKeyword: HighlightToken; // pub unsafe async mut extern default move modifier: HighlightToken; // for if else loop while match continue break return await controlKeyword: HighlightToken; // as in ref operatorKeyword: HighlightToken; // where crate super dyn keyword: HighlightToken; // self self: HighlightToken; // true bool: HighlightToken; // 5 integer: HighlightToken; // 5.5 literal: HighlightToken; // "" + b"" + r#""# string: HighlightToken; // ' character: HighlightToken; // & operator: HighlightToken; // * derefOperator: HighlightToken; // Lifetime &_'a_ specialVariable: HighlightToken; // Comment with // lineComment: HighlightToken; // Comment with /* */ blockComment: HighlightToken; // # meta: HighlightToken; invalid: HighlightToken; // const _x_: bool = true; constant: HighlightToken; regexp: HighlightToken; tagName: HighlightToken; attributeName: HighlightToken; attributeValue: HighlightToken; annotion: HighlightToken; } /** Syntax highlighting token */ type HighlightToken = Pick<StandardProperties, "color" | "fontStyle">; /** Playground font */ export interface Font { family: NonNullable<StandardProperties["fontFamily"]>; size: { [K in "xsmall" | "small" | "medium" | "large" | "xlarge"]: NonNullable< StandardProperties["fontSize"] >; }; } /** Importable(lazy) theme */ export interface ImportableTheme { /** Name of the theme that's displayed in theme settings */ name: string; /** Import promise for the theme to lazy load */ importTheme: () => Promise<{ default: Theme; }>; } /** Components that use `DefaultComponent` type */ type DefaultComponents = "input" | "skeleton" | "tooltip"; /** Components that use `ExtendibleComponent` type */ type ExtendibleComponents = | "bottom" | "editor" | "main" | "markdown" | "modal" | "progressbar" | "select" | "sidebar" | "tabs" | "terminal" | "toast" | "uploadArea" | "wallet"; /** Components that use `OverridableComponent` type */ type OverridableComponents = "button" | "menu" | "text"; /** Theme to be used while setting the defaults internally */ export type ThemeInternal = Partial<Pick<ImportableTheme, "name">> & Theme & { /** Default font */ font?: { /** Code font */ code?: Font; /** Any font other than code(e.g Markdown) */ other?: Font; }; }; /** * Ready to be used theme. Some of the optional properties will be overridden * with default values. */ export type ThemeReady< T extends ThemeInternal = ThemeInternal, C extends NonNullable<T["components"]> = NonNullable<T["components"]> > = NestedRequired<T> & { // Default components components: Pick<C, DefaultComponents>; } & { // Extendible components components: AllRequired<Pick<C, ExtendibleComponents>>; } & { // Overridable components components: ChildRequired< Pick<C, OverridableComponents>, OverridableComponents, "default" >; }; /** Properties that are allowed to be specified from theme objects */ type DefaultStyles = { bg?: Bg; } & AnyProperty & { [key: string]: any }; // & StandardProperties // FIXME: Using `StandardProperties` makes TypeScript extremely slow. /** StandardProperties pseudo classes */ type PseudoClass = | "hover" | "active" | "focus" | "focusWithin" | "before" | "after"; /** Default component pseudo classes */ type DefaultComponentState<T extends PseudoClass = PseudoClass> = { [K in T]?: DefaultComponent; }; /** * Specify any property that starts with `&`. * * NOTE: Usage of this should be avoided when possible because expressions such * as `& > div:nth-child(3)` will break if the layout of of the component changes * and TypeScript will not catch the error. */ type AnyProperty<T extends string = string> = { [K in `&${T}`]?: DefaultComponent; }; /** Default component with pseudo classes */ export type DefaultComponent = DefaultStyles & DefaultComponentState; /** Extendible component */ type ExtendibleComponent< T extends string | object, D = {}, U = T extends string ? { [K in T]?: DefaultComponent; } : T > = { default?: DefaultComponent & D; } & (T extends string ? { [K in U extends any ? keyof U : never]?: DefaultComponent } : U); /** A component with multiple kinds */ type OverridableComponent<T extends string> = { /** Default StandardProperties values of the Button component */ default?: DefaultComponent; /** Override the defaults with specificity */ overrides?: { [K in T]?: DefaultComponent; }; }; /** StandardProperties background */ type Bg = string; /** StandardProperties color */ type Color = NonNullable<StandardProperties["color"]>; /** Optional background and color */ type BgAndColor = { bg?: Bg } & { color?: Color }; /** Required color, optional background */ type StateColor = { color: Color; } & { bg?: Bg; }; /** Theme color names */ export type ThemeColor = | keyof Pick< ThemeReady["colors"]["default"], "primary" | "secondary" | "textPrimary" | "textSecondary" > | keyof Omit<ThemeReady["colors"]["state"], "hover" | "disabled">;
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/theme/index.ts
export { PgTheme } from "./theme"; export * from "./interface";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/theme/theme.ts
import type { StandardProperties } from "csstype"; import { PgCommon } from "../common"; import { EventName } from "../../../constants"; import type { DefaultComponent, ImportableTheme, Font, ThemeInternal, ThemeReady, ThemeColor, Highlight, } from "./interface"; import type { ValueOf } from "../types"; export class PgTheme { /** Current theme */ private static _theme: ThemeInternal; /** Current font */ private static _font: Font; /** All themes */ private static _themes: ImportableTheme[]; /** All fonts */ private static _fonts: Font[]; /** Theme key in localStorage */ private static readonly _THEME_KEY = "theme"; /** Font key in localStorage */ private static readonly _FONT_KEY = "font"; /** All available themes */ static get themes() { return this._themes; } /** All available fonts */ static get fonts() { return this._fonts; } /** * Create the initial theme and font from `localStorage`. * * @param themes all importable themes * @param fonts all fonts */ static async create(themes: ImportableTheme[], fonts: Font[]) { this._themes = themes; this._fonts = fonts; await this.set(); } /** * Add fallback fonts. * * @param family font family * @returns the font family with fallback fonts appended */ static addFallbackFont(family: string) { return `${family}, Monospace, Courier`; } /** * Set theme and font. * * The theme will be imported asynchronously based on the given theme name or * the name in `localStorage`. * * This function is also responsible for setting sensible defaults. * * @param params theme name and font family */ static async set( params: Partial<{ themeName: ThemeInternal["name"]; fontFamily: Font["family"]; }> = {} ) { params.themeName ??= localStorage.getItem(this._THEME_KEY) ?? this._themes[0].name; params.fontFamily ??= localStorage.getItem(this._FONT_KEY) ?? this._fonts[0].family; let importableTheme = this._themes.find((t) => t.name === params.themeName); // This could happen when: // 1. The theme name was updated/deleted // 2. The theme key was overridden by another app when running locally // 3. The user manually edited `localStorage` theme value if (!importableTheme) { importableTheme = this._themes[0]; params.themeName = importableTheme.name; params.fontFamily = this._fonts[0].family; } const font = this._fonts.find((f) => f.family === params.fontFamily)!; // Cloning the object because override functions expect the theme to be // uninitialized. Keeping a reference to an old theme may cause unwanted // side effects. this._theme = structuredClone( (await importableTheme.importTheme()).default ); this._theme.name = importableTheme.name; this._font = font; // Set defaults(order matters) this._theme_fonts() ._default() ._stateColors() ._components() ._skeleton() ._button() ._menu() ._text() ._input() ._select() ._tooltip() ._progressBar() ._uploadArea() ._toast() ._modal() ._markdown() ._terminal() ._wallet() ._bottom() ._sidebar() ._main() ._tabs() ._editor() ._home() ._tutorial() ._tutorials() ._programs(); // Set theme localStorage.setItem(this._THEME_KEY, params.themeName); PgCommon.createAndDispatchCustomEvent(EventName.THEME_SET, this._theme); // Set font localStorage.setItem(this._FONT_KEY, params.fontFamily); PgCommon.createAndDispatchCustomEvent(EventName.THEME_FONT_SET, this._font); } /** * Convert the component object styles into CSS styles. * * @param component Component to convert to CSS * @returns the converted CSS */ static convertToCSS(component: DefaultComponent): string { return Object.keys(component).reduce((acc, key) => { const value = component[key]; // Check for `&` if (key.startsWith("&")) { return `${acc}${key}{${this.convertToCSS(value)}}`; } // Handle non-standard properties let prop = key.startsWith("-") ? key : PgCommon.toKebabFromCamel(key); switch (key) { case "bg": prop = "background"; break; case "hover": case "active": case "focus": case "focusWithin": return `${acc}&:${prop}{${this.convertToCSS(value)}}`; case "before": case "after": return `${acc}&::${prop}{${this.convertToCSS(value)}}`; } // Only allow string and number values if (typeof value === "string" || typeof value === "number") { return `${acc}${prop}:${value};`; } return acc; }, ""); } /** * Override default component styles with the given overrides * * @param component default component to override * @param overrides override properties * @returns the overridden component */ static overrideDefaults<T extends DefaultComponent>( component: T, overrides?: T ) { if (!overrides) { return component; } for (const key in overrides) { const value = overrides[key]; if (typeof value === "object") { component[key] = { ...component[key], ...value }; } else { component[key] = value; } } return component; } /** * Get the color value from the given theme color name. * * @param color theme color * @returns the color value from theme */ static getColor(color: ThemeColor = "textSecondary") { const theme = this._themeReady; switch (color) { case "primary": return theme.colors.default.primary; case "secondary": return theme.colors.default.secondary; case "error": return theme.colors.state.error.color; case "success": return theme.colors.state.success.color; case "warning": return theme.colors.state.warning.color; case "info": return theme.colors.state.info.color; case "textPrimary": return theme.colors.default.textPrimary; case "textSecondary": return theme.colors.default.textSecondary; default: throw new Error(`Unknown color '${color}'`); } } /** * Get a different background than the one given based on the current theme. * * @param bg background to compare to * @returns a different background based on the current theme */ static getDifferentBackground(bg: string) { const theme = this._themeReady; const textBg = theme.components.text.default.bg!; if (!PgCommon.isColorsEqual(bg, textBg)) return textBg; const { bgPrimary, bgSecondary } = theme.colors.default; if (PgCommon.isColorsEqual(bg, bgPrimary)) return bgSecondary; return bgPrimary; } /** * Create CSS for scrollbar. * * @param opts - * `allChildren`: Whether to add the scrollbar changes to all children components * @returns the scrollbar CSS */ static getScrollbarCSS( opts?: { allChildren?: boolean; } & Pick<StandardProperties, "width" | "height" | "borderRadius"> ) { const theme = this._themeReady; const scrollbar = theme.default.scrollbar; const { allChildren, borderRadius, height, width } = PgCommon.setDefault( opts, { allChildren: false, borderRadius: theme.default.borderRadius, height: "0.5rem", width: "0.5rem", } ); const prefix = allChildren ? "& " : "&"; return ` /* Scrollbar */ /* Chromium */ ${prefix}::-webkit-scrollbar { width: ${width}; height: ${height}; } ${prefix}::-webkit-scrollbar-track { background-color: transparent; } ${prefix}::-webkit-scrollbar-thumb { border: 0.25rem solid transparent; border-radius: ${borderRadius}; background-color: ${scrollbar.thumb.color}; } ${prefix}::-webkit-scrollbar-thumb:hover { background-color: ${scrollbar.thumb.hoverColor}; } /* Firefox */ ${prefix} * { scrollbar-color: ${scrollbar.thumb.color}; } `; } /** * Clamp the lines i.e. hide all lines after `max` and append "..." to the * text. * * @param max maximum number of lines * @returns the CSS string */ static getClampLinesCSS(max: number) { return ` display: -webkit-box; -webkit-line-clamp: ${max}; -webkit-box-orient: vertical; overflow: hidden; `; } /** * Convert playground theme to a TextMate theme. * * @param theme ready theme * @returns the converted TextMate theme */ static convertToTextMateTheme(theme: ThemeReady) { const editorStyles = theme.components.editor; const hl = theme.highlight; const createSettings = (token: ValueOf<Highlight>) => ({ foreground: token.color, fontStyle: token.fontStyle, }); return { name: theme.name, settings: [ //////////////////////////////// Default /////////////////////////////// { // Can't directly set scrollbar background. // See https://github.com/microsoft/monaco-editor/issues/908#issuecomment-433739458 name: "Defaults", settings: { background: // Transparent background results with a full black background editorStyles.default.bg === "transparent" ? theme.colors.default.bgPrimary : editorStyles.default.bg, foreground: editorStyles.default.color, }, }, //////////////////////////////// Boolean /////////////////////////////// { name: "Boolean", scope: [ "constant.language.bool", "constant.language.boolean", "constant.language.json", ], settings: createSettings(hl.bool), }, /////////////////////////////// Integer //////////////////////////////// { name: "Integers", scope: "constant.numeric", settings: createSettings(hl.integer), }, //////////////////////////////// String //////////////////////////////// { name: "Strings", scope: [ "string.quoted.single", "string.quoted.double", "string.template.ts", ], settings: createSettings(hl.string), }, ///////////////////////////////// Regex //////////////////////////////// { name: "Regular expressions", scope: ["string.regexp.ts"], settings: createSettings(hl.regexp), }, /////////////////////////////// Function /////////////////////////////// { name: "Functions", scope: ["entity.name.function", "meta.function-call.generic.python"], settings: createSettings(hl.functionCall), }, { name: "Function parameter", scope: [ "variable.parameter", "variable.parameter.ts", "entity.name.variable.parameter", "variable.other.jsdoc", ], settings: createSettings(hl.functionArg), }, /////////////////////////////// Constant /////////////////////////////// { name: "Constants", scope: [ "variable.other.constant.ts", "variable.other.constant.property.ts", ], settings: createSettings(hl.constant), }, /////////////////////////////// Variable /////////////////////////////// { name: "Variables", scope: [ "variable.other", "variable.object.property.ts", "meta.object-literal.key.ts", ], settings: createSettings(hl.variableName), }, { name: "Special variable", scope: [ "variable.language.self.rust", "variable.language.super.rust", "variable.language.this.ts", ], settings: createSettings(hl.specialVariable), }, //////////////////////////////// Keyword /////////////////////////////// { name: "Storage types", scope: "storage.type", settings: createSettings(hl.keyword), }, { name: "Storage modifiers", scope: "storage.modifier", settings: createSettings(hl.modifier), }, { name: "Control keywords", scope: "keyword.control", settings: createSettings(hl.controlKeyword), }, { name: "Other", scope: ["keyword.other", "keyword.operator.new.ts"], settings: createSettings(hl.keyword), }, /////////////////////////////// Operator /////////////////////////////// { name: "Operators", scope: [ "keyword.operator", "punctuation.separator.key-value", "storage.type.function.arrow.ts", ], settings: createSettings(hl.operator), }, ///////////////////////////////// Type ///////////////////////////////// { name: "Types", scope: [ "entity.name.type", "support.type", "entity.other.inherited-class.python", ], settings: createSettings(hl.typeName), }, ////////////////////////////// Punctuation ///////////////////////////// { name: ".", scope: ["punctuation.accessor", "punctuation.separator.period"], settings: createSettings(hl.operator), }, { name: ",", scope: "punctuation.separator.comma", settings: createSettings(hl.variableName), }, { name: ";", scope: "punctuation.terminator.statement", settings: createSettings(hl.variableName), }, { name: "${}", scope: [ "punctuation.definition.template-expression.begin.ts", "punctuation.definition.template-expression.end.ts", ], settings: createSettings(hl.modifier), }, //////////////////////////////// Import //////////////////////////////// { name: "`import`", scope: "keyword.control.import.ts", settings: createSettings(hl.keyword), }, { name: "import `*`", scope: "constant.language.import-export-all.ts", settings: createSettings(hl.constant), }, { name: "import * `as`", scope: "keyword.control.as.ts", settings: createSettings(hl.controlKeyword), }, { name: "import * as `alias`", scope: "variable.other.readwrite.alias.ts", settings: createSettings(hl.variableName), }, { name: "import * as alias `from`", scope: "keyword.control.from.ts", settings: createSettings(hl.keyword), }, //////////////////////////////// Macros //////////////////////////////// { name: "Macros", scope: [ "meta.attribute.rust", "entity.name.function.decorator.python", ], settings: createSettings(hl.meta), }, //////////////////////////////// Comment /////////////////////////////// { name: "Comments", scope: [ "comment.line", "comment.block", "punctuation.definition.comment.ts", ], settings: createSettings(hl.lineComment), }, { name: "JSDoc comments", scope: [ "punctuation.definition.block.tag.jsdoc", "storage.type.class.jsdoc", ], settings: createSettings(hl.keyword), }, ///////////////////////////////// Rust ///////////////////////////////// { name: "Lifetimes", scope: [ "punctuation.definition.lifetime.rust", "entity.name.type.lifetime.rust", ], settings: createSettings(hl.specialVariable), }, ], }; } /** Get the theme with default types set */ private static get _themeReady() { return this._theme as ThemeReady; } /** Get and initialize component and return it with the correct type */ private static _getComponent< T extends keyof NonNullable<ThemeInternal["components"]> >(component: T): NonNullable<NonNullable<ThemeInternal["components"]>[T]> { const components = this._theme.components!; components[component] ??= {}; return components[component]!; } /** Set default fonts */ private static _theme_fonts() { this._theme.font ??= {}; this._theme.font.code ??= { ...this._font, family: this.addFallbackFont(this._font.family), }; this._theme.font.other ??= { family: `-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"`, size: { xsmall: "0.8125rem", small: "0.875rem", medium: "1rem", large: "1.25rem", xlarge: "1.5rem", }, }; return this; } /** Set defaults */ private static _default() { this._theme.default ??= {}; const def = this._theme.default; // Backdrop def.backdrop ??= {}; def.backdrop.bg ??= this._theme.isDark ? "#00000080" : "#00000040"; // Border radius def.borderRadius ??= "4px"; // Box shadow def.boxShadow ??= "rgb(0 0 0 / 25%) -1px 3px 4px"; // Scrollbar if (!def.scrollbar) { if (this._theme.isDark) { def.scrollbar = { thumb: { color: "#ffffff64", hoverColor: "#ffffff32", }, }; } else { def.scrollbar = { thumb: { color: "#00000032", hoverColor: "#00000064", }, }; } } // Transition def.transition ??= { type: "linear", duration: { short: "50ms", medium: "150ms", long: "250ms", }, }; // Transparency def.transparency ??= { low: "16", medium: "64", high: "bb", }; return this; } /** Set default state colors */ private static _stateColors() { const state = this._theme.colors.state; const theme = this._themeReady; state.disabled.bg ??= state.disabled.color + theme.default.transparency.low; state.error.bg ??= state.error.color + theme.default.transparency.low; state.hover.bg ??= state.hover.color + theme.default.transparency.low; state.info.bg ??= state.info.color + theme.default.transparency.low; state.success.bg ??= state.success.color + theme.default.transparency.low; state.warning.bg ??= state.warning.color + theme.default.transparency.low; return this; } /** Set default components */ private static _components() { this._theme.components ??= {}; return this; } /** Set default skeleton component */ private static _skeleton() { const skeleton = this._getComponent("skeleton"); const theme = this._themeReady; skeleton.bg ??= "#44475A"; skeleton.highlightColor ??= "#343746"; skeleton.borderRadius ??= theme.default.borderRadius; return this; } /** Set default button component */ private static _button() { const button = this._getComponent("button"); const theme = this._themeReady; // Default button.default ??= {}; button.default.bg ??= "transparent"; button.default.color ??= "inherit"; button.default.borderColor ??= "transparent"; button.default.borderRadius ??= theme.default.borderRadius; button.default.fontSize ??= theme.font.code.size.medium; button.default.fontWeight ??= "normal"; button.default.hover ??= {}; return this; } /** Set default menu component */ private static _menu() { const menu = this._getComponent("menu"); const theme = this._themeReady; // Default menu.default ??= {}; menu.default.position ??= "absolute"; menu.default.zIndex ??= 2; menu.default.bg ??= theme.colors.default.bgPrimary; menu.default.borderRadius ??= theme.default.borderRadius; menu.default.padding ??= "0.25rem 0"; menu.default.boxShadow ??= theme.default.boxShadow; return this; } /** Set default menu component */ private static _text() { const text = this._getComponent("text"); const theme = this._themeReady; // Default text.default ??= {}; text.default.display ??= "flex"; text.default.justifyContent ??= "center"; text.default.alignItems ??= "center"; text.default.bg ??= theme.colors.default.bgPrimary; text.default.padding ??= "1rem"; text.default.borderRadius ??= theme.default.borderRadius; text.default.fontSize ??= theme.font.code.size.small; text.default.lineHeight ??= 1.5; return this; } /** Set default input component */ private static _input() { const input = this._getComponent("input"); const theme = this._themeReady; input.width ??= "100%"; input.height ??= "2rem"; input.padding ??= "0.375rem 0.5rem"; input.bg ??= theme.colors.default.bgPrimary; input.color ??= theme.colors.default.textPrimary; input.border ??= `1px solid ${theme.colors.default.border}`; input.borderColor ??= theme.colors.default.border; // Monaco inputs also use this input.borderRadius ??= theme.default.borderRadius; input.boxShadow ??= "none"; input.fontWeight ??= "normal"; input.fontSize ??= theme.font.code.size.medium; input.focus ??= {}; input.focus.outline ??= `1px solid ${ theme.colors.default.primary + theme.default.transparency.medium }`; input.focusWithin ??= {}; input.focusWithin.outline ??= `1px solid ${ theme.colors.default.primary + theme.default.transparency.medium }`; return this; } /** Set default select component */ private static _select() { const select = this._getComponent("select"); const theme = this._themeReady; const input = theme.components.input; // Default select.default ??= {}; select.default.fontSize ??= theme.font.code.size.small; // Control select.control ??= {}; select.control.bg ??= input.bg; select.control.borderColor ??= theme.colors.default.border; select.control.borderRadius ??= theme.default.borderRadius; select.control.minHeight ??= "fit-content"; select.control.hover ??= {}; select.control.hover.borderColor ??= theme.colors.state.hover.color; select.control.hover.cursor ??= "pointer"; select.control.focusWithin ??= {}; select.control.focusWithin.boxShadow ??= `0 0 0 1px ${ theme.colors.default.primary + theme.default.transparency.high }`; // Menu select.menu ??= {}; select.menu.bg ??= input.bg; select.menu.color ??= input.color; select.menu.borderRadius ??= input.borderRadius; // Option select.option ??= {}; select.option.bg ??= input.bg; select.option.color ??= theme.colors.default.textSecondary; select.option.cursor ??= "pointer"; // Option::before select.option.before ??= {}; select.option.before.color ??= theme.colors.default.primary; // Option:focus select.option.focus ??= {}; select.option.focus.bg ??= theme.colors.state.hover.bg; select.option.focus.color ??= theme.colors.default.primary; // Option:active select.option.active ??= {}; select.option.active.bg ??= theme.colors.state.hover.bg; // Single Value select.singleValue ??= {}; select.singleValue.bg ??= input.bg; select.singleValue.color ??= input.color; // Input select.input ??= {}; select.input.color ??= input.color; // Group Heading select.groupHeading ??= {}; select.groupHeading.color ??= theme.colors.default.textSecondary; // Dropdown Indicator select.dropdownIndicator ??= {}; select.dropdownIndicator.padding ??= "0.25rem"; // Indicator Separator select.indicatorSeparator ??= {}; select.indicatorSeparator.bg ??= theme.colors.default.textSecondary; return this; } /** Set default tooltip component */ private static _tooltip() { const tooltip = this._getComponent("tooltip"); const theme = this._themeReady; tooltip.padding ??= "0.375rem 0.5rem"; tooltip.bg ??= theme.colors.default.bgPrimary; tooltip.bgSecondary ??= theme.colors.default.bgSecondary; tooltip.color ??= theme.colors.default.textPrimary; tooltip.borderRadius ??= theme.default.borderRadius; tooltip.boxShadow ??= theme.default.boxShadow; tooltip.fontFamily ??= theme.font.code.family; tooltip.fontSize ??= theme.font.code.size.small; tooltip.textAlign ??= "center"; return this; } /** Set default progress bar component */ private static _progressBar() { const progressbar = this._getComponent("progressbar"); const theme = this._themeReady; // Default progressbar.default ??= {}; progressbar.default.width ??= "100%"; progressbar.default.height ??= "0.75rem"; progressbar.default.overflow ??= "hidden"; progressbar.default.border ??= `1px solid ${theme.colors.default.border}`; progressbar.default.borderRadius ??= theme.default.borderRadius; // Indicator progressbar.indicator ??= {}; progressbar.indicator.height ??= "100%"; progressbar.indicator.maxWidth ??= "100%"; progressbar.indicator.bg ??= theme.colors.default.primary; progressbar.indicator.borderRadius ??= theme.default.borderRadius; progressbar.indicator.transition ??= `width ${theme.default.transition.duration.long} ${theme.default.transition.type}`; return this; } /** Set default upload area component */ private static _uploadArea() { const uploadArea = this._getComponent("uploadArea"); const theme = this._themeReady; // Default uploadArea.default ??= {}; uploadArea.default.padding ??= "2rem"; uploadArea.default.bg ??= theme.colors.default.primary + theme.default.transparency.low; uploadArea.default.border ??= `2px dashed ${theme.colors.default.primary + theme.default.transparency.medium}`; uploadArea.default.borderRadius ??= theme.default.borderRadius; uploadArea.default.transition ??= `all ${theme.default.transition.duration.short} ${theme.default.transition.type}`; uploadArea.default.hover ??= {}; uploadArea.default.hover.cursor ??= "pointer"; uploadArea.default.hover.borderColor ??= theme.colors.default.primary + theme.default.transparency.high; // Icon uploadArea.icon ??= {}; uploadArea.icon.width ??= "4rem"; uploadArea.icon.height ??= "4rem"; uploadArea.icon.color ??= theme.colors.default.primary; // Text uploadArea.text ??= {}; // Text default uploadArea.text.default ??= {}; uploadArea.text.default.marginTop ??= "1rem"; uploadArea.text.default.color ??= theme.colors.default.textSecondary; uploadArea.text.default.fontWeight ??= "bold"; // Text error uploadArea.text.error ??= {}; uploadArea.text.error.color ??= theme.colors.state.error.color; // Text success uploadArea.text.success ??= {}; uploadArea.text.success.color ??= theme.colors.default.primary; return this; } /** Set default skeleton component */ private static _toast() { const toast = this._getComponent("toast"); const theme = this._themeReady; // Default toast.default ??= {}; toast.default.bg ??= theme.colors.default.bgPrimary; toast.default.color ??= theme.colors.default.textPrimary; toast.default.borderRadius ??= theme.default.borderRadius; toast.default.fontFamily ??= theme.font.code.family; toast.default.fontSize ??= theme.font.code.size.medium; toast.default.cursor ??= "default"; // Progress bar toast.progress ??= {}; toast.progress.bg ??= theme.colors.default.primary; // Close button toast.closeButton ??= {}; toast.closeButton.color ??= theme.colors.default.textSecondary; return this; } /** Set default modal component */ private static _modal() { const modal = this._getComponent("modal"); const theme = this._themeReady; // Default modal.default ??= {}; modal.default.display ??= "flex"; modal.default.flexDirection ??= "column"; modal.default.bg ??= theme.colors.default.bgPrimary; modal.default.border ??= `1px solid ${theme.colors.default.border}`; modal.default.borderRadius ??= theme.default.borderRadius; modal.default.maxWidth ??= "max(40%, 40rem)"; modal.default.maxHeight ??= "max(80%, 40rem)"; // Backdrop modal.backdrop ??= theme.default.backdrop; // Top modal.top ??= {}; modal.top.position ??= "relative"; modal.top.display ??= "flex"; modal.top.justifyContent ??= "center"; modal.top.alignItems ??= "center"; modal.top.padding ??= "0 1.5rem"; modal.top.fontWeight ??= "bold"; // Content modal.content ??= {}; modal.content.padding ??= "1rem 1.5rem"; modal.content.minWidth ??= "23rem"; modal.content.minHeight ??= "3rem"; // Bottom modal.bottom ??= {}; modal.bottom.display ??= "flex"; modal.bottom.justifyContent ??= "flex-end"; modal.bottom.padding ??= "0.25rem 1.5rem 0.75rem"; modal.bottom.marginBottom ??= "0.25rem"; return this; } /** Set default markdown component */ private static _markdown() { const markdown = this._getComponent("markdown"); const theme = this._themeReady; // Default markdown.bg ??= "inherit"; markdown.subtleBg ??= theme.colors.default.bgSecondary; markdown.color ??= theme.colors.default.textPrimary; markdown.fontFamily ??= theme.font.other.family; markdown.fontSize ??= theme.font.other.size.medium; return this; } /** Set default terminal component */ private static _terminal() { const terminal = this._getComponent("terminal"); const theme = this._themeReady; // Default terminal.default ??= {}; terminal.default.padding ??= "0.5rem 1rem"; // Xterm terminal.xterm ??= {}; terminal.xterm.textPrimary ??= theme.colors.default.textPrimary; terminal.xterm.textSecondary ??= theme.colors.default.textSecondary; terminal.xterm.primary ??= theme.colors.default.primary; terminal.xterm.secondary ??= theme.colors.default.secondary; terminal.xterm.success ??= theme.colors.state.success.color; terminal.xterm.error ??= theme.colors.state.error.color; terminal.xterm.warning ??= theme.colors.state.warning.color; terminal.xterm.info ??= theme.colors.state.info.color; terminal.xterm.selectionBg ??= theme.colors.default.textSecondary; // Xterm cursor terminal.xterm.cursor ??= {}; terminal.xterm.cursor.color ??= theme.colors.default.textPrimary; terminal.xterm.cursor.accentColor ??= terminal.default.bg!; return this; } /** Set default wallet component */ private static _wallet() { const wallet = this._getComponent("wallet"); const theme = this._themeReady; // Default wallet.default ??= {}; wallet.default.width ??= "100%"; wallet.default.height ??= "100%"; wallet.default.bg ??= theme.colors.default.bgSecondary; wallet.default.border ??= `1px solid ${theme.colors.default.border}`; wallet.default.borderRadius ??= theme.default.borderRadius; wallet.default.boxShadow ??= theme.default.boxShadow; // Top wallet.top ??= {}; // Top default wallet.top.default ??= {}; wallet.top.default.position ??= "relative"; wallet.top.default.height ??= "2rem"; wallet.top.default.display ??= "flex"; wallet.top.default.justifyContent ??= "center"; wallet.top.default.alignItems ??= "center"; wallet.top.default.padding ??= "0.5rem"; // Top title wallet.top.title ??= {}; // Top title default wallet.top.title.default ??= {}; wallet.top.title.default.display ??= "flex"; wallet.top.title.default.justifyContent ??= "center"; wallet.top.title.default.alignItems ??= "center"; wallet.top.title.default.hover ??= {}; wallet.top.title.default.hover.cursor ??= "pointer"; wallet.top.title.default.hover[`& svg, & span`] = { color: theme.colors.default.textPrimary, }; // Top title icon wallet.top.title.icon ??= {}; wallet.top.title.icon.width ??= "1rem"; wallet.top.title.icon.height ??= "1rem"; wallet.top.title.icon.marginRight ??= "0.25rem"; // Top title text wallet.top.title.text ??= {}; wallet.top.title.text.display ??= "flex"; wallet.top.title.text.alignItems ??= "center"; wallet.top.title.text.padding ??= "0.25rem"; wallet.top.title.text.color ??= theme.colors.default.textSecondary; wallet.top.title.text.fontSize ??= theme.font.code.size.small; wallet.top.title.text.fontWeight ??= "bold"; wallet.top.title.text.transition ??= `all ${theme.default.transition.duration.short} ${theme.default.transition.type}`; // Main wallet.main ??= {}; // Main default wallet.main.default ??= {}; wallet.main.default.position ??= "relative"; wallet.main.default.cursor ??= "auto"; wallet.main.default.padding ??= "1rem"; wallet.main.default.bg ??= `linear-gradient( 0deg, ${wallet.default.bg} 75%, ${theme.colors.default.primary + theme.default.transparency.low} 100% )`; wallet.main.default.borderRadius ??= theme.default.borderRadius; // Main backdrop wallet.main.backdrop ??= theme.default.backdrop; // Main balance wallet.main.balance ??= {}; wallet.main.balance.display ??= "flex"; wallet.main.balance.justifyContent ??= "center"; wallet.main.balance.marginBottom ??= "0.5rem"; wallet.main.balance.color ??= theme.colors.default.textSecondary; wallet.main.balance.fontWeight ??= "bold"; wallet.main.balance.fontSize ??= theme.font.code.size.xlarge; // Main send wallet.main.send ??= {}; // Main send default wallet.main.send.default ??= {}; wallet.main.send.default.marginBottom ??= "1rem"; // Main send title wallet.main.send.title ??= {}; wallet.main.send.title.fontWeight ??= "bold"; // Main send expanded wallet.main.send.expanded ??= {}; // Main send expanded default wallet.main.send.expanded.default ??= {}; wallet.main.send.expanded.default.paddingTop ??= "0.75rem"; // Main send expanded input wallet.main.send.expanded.input ??= {}; wallet.main.send.expanded.input.marginBottom ??= "0.75rem"; // Main send expanded button wallet.main.send.expanded.sendButton ??= {}; wallet.main.send.expanded.sendButton.marginBottom ??= "0.25rem"; // Main transactions wallet.main.transactions ??= {}; // Main transactions default wallet.main.transactions.default ??= {}; // Main transactions title wallet.main.transactions.title ??= {}; // Main transactions title default wallet.main.transactions.title.default ??= {}; wallet.main.transactions.title.default.display ??= "flex"; wallet.main.transactions.title.default.justifyContent ??= "space-between"; wallet.main.transactions.title.default.alignItems ??= "center"; // Main transactions title text wallet.main.transactions.title.text ??= {}; wallet.main.transactions.title.text.fontWeight ??= "bold"; // Main transactions title button wallet.main.transactions.title.refreshButton ??= {}; wallet.main.transactions.title.refreshButton.marginRight ??= "0.5rem"; // Main transactions table wallet.main.transactions.table ??= {}; // Main transactions table default wallet.main.transactions.table.default ??= {}; wallet.main.transactions.table.default.bg ??= theme.colors.default.bgPrimary; wallet.main.transactions.table.default.border ??= `1px solid ${theme.colors.default.border}`; wallet.main.transactions.table.default.borderRadius ??= theme.default.borderRadius; wallet.main.transactions.table.default.marginTop ??= "0.5rem"; wallet.main.transactions.table.default.overflow ??= "hidden"; // Main transactions table header wallet.main.transactions.table.header ??= {}; wallet.main.transactions.table.header.display ??= "flex"; wallet.main.transactions.table.header.padding ??= "0.5rem 1rem"; wallet.main.transactions.table.header.bg ??= theme.colors.default.bgSecondary; wallet.main.transactions.table.header.color ??= theme.colors.default.textSecondary; wallet.main.transactions.table.header.borderBottom ??= `1px solid ${theme.colors.default.border}`; wallet.main.transactions.table.header.fontWeight ??= "bold"; wallet.main.transactions.table.header.fontSize ??= theme.font.code.size.small; // Main transactions table row wallet.main.transactions.table.row ??= {}; // Main transactions table row default wallet.main.transactions.table.row.default ??= {}; wallet.main.transactions.table.row.default.display ??= "flex"; wallet.main.transactions.table.row.default.padding ??= "0.5rem 1rem"; wallet.main.transactions.table.row.default.color ??= theme.colors.default.textSecondary; wallet.main.transactions.table.row.default.fontSize ??= theme.font.code.size.small; wallet.main.transactions.table.row.default.hover ??= {}; wallet.main.transactions.table.row.default.hover.bg ??= theme.colors.state.hover.bg; wallet.main.transactions.table.row.default.hover.color ??= theme.colors.default.textPrimary; // Main transactions table row signature wallet.main.transactions.table.row.signature ??= {}; wallet.main.transactions.table.row.signature.display ??= "flex"; wallet.main.transactions.table.row.signature.alignItems ??= "center"; wallet.main.transactions.table.row.signature.width ??= "40%"; // Main transactions table row slot wallet.main.transactions.table.row.slot ??= {}; wallet.main.transactions.table.row.slot.width ??= "40%"; // Main transactions table row time wallet.main.transactions.table.row.time ??= {}; wallet.main.transactions.table.row.time.display ??= "flex"; wallet.main.transactions.table.row.time.justifyContent ??= "flex-end"; wallet.main.transactions.table.row.time.alignItems ??= "center"; wallet.main.transactions.table.row.time.width ??= "20%"; return this; } /** Set default bottom bar component */ private static _bottom() { const bottom = this._getComponent("bottom"); const theme = this._themeReady; // Default bottom.default ??= {}; bottom.default.height ??= "1.5rem"; bottom.default.padding ??= "0 0.5rem"; bottom.default.bg ??= theme.colors.default.primary; bottom.default.color ??= theme.colors.default.textPrimary; bottom.default.fontSize ??= theme.font.code.size.small; bottom.default.display ??= "flex"; bottom.default.flexWrap ??= "wrap"; bottom.default.alignItems ??= "center"; // Connect button bottom.connect ??= {}; bottom.connect.height ??= "100%"; bottom.connect.padding ??= "0 0.75rem"; bottom.connect.border ??= "none"; bottom.connect.hover ??= {}; bottom.connect.hover.bg ??= bottom.default.color + theme.default.transparency.low; // Endpoint bottom.endpoint ??= {}; // Address bottom.address ??= {}; bottom.address.color ??= bottom.default.color; // Balance bottom.balance ??= {}; return this; } /** Set default sidebar component */ private static _sidebar() { const sidebar = this._getComponent("sidebar"); const theme = this._themeReady; // Default sidebar.default ??= {}; sidebar.default.display ??= "flex"; // Left sidebar.left ??= {}; // Left default sidebar.left.default ??= {}; sidebar.left.default.width ??= "3rem"; sidebar.left.default.bg ??= theme.colors.default.bgPrimary; sidebar.left.default.borderRight ??= `1px solid ${theme.colors.default.border}`; // Left icon button sidebar.left.button ??= {}; // Left icon button default sidebar.left.button.default ??= {}; sidebar.left.button.default.display ??= "flex"; sidebar.left.button.default.justifyContent ??= "center"; sidebar.left.button.default.alignItems ??= "center"; sidebar.left.button.default.width ??= sidebar.left.default.width; sidebar.left.button.default.height ??= "3rem"; sidebar.left.button.default.cursor ??= "pointer"; // Left icon button selected sidebar.left.button.selected ??= {}; sidebar.left.button.selected.bg ??= theme.colors.state.hover.bg; sidebar.left.button.selected.borderLeft ??= `2px solid ${theme.colors.default.secondary}`; sidebar.left.button.selected.borderRight ??= "2px solid transparent"; // Right sidebar.right ??= {}; // Right default sidebar.right.default ??= {}; sidebar.right.default.initialWidth ??= "20rem"; sidebar.right.default.bg ??= theme.colors.default.bgSecondary; sidebar.right.default.otherBg ??= theme.colors.default.bgPrimary; sidebar.right.default.borderRight ??= `1px solid ${theme.colors.default.border}`; // Right title sidebar.right.title ??= {}; sidebar.right.title.height ??= "2rem"; sidebar.right.title.borderBottom ??= `1px solid ${theme.colors.default.border};`; sidebar.right.title.color ??= theme.colors.default.textSecondary; sidebar.right.title.fontSize ??= theme.font.code.size.large; return this; } /** Set default main view */ private static _main() { const main = this._getComponent("main"); const theme = this._themeReady; // Default main.default ??= {}; main.default.display ??= "flex"; main.default.flexDirection ??= "column"; main.default.overflow ??= "hidden"; main.default.bg ??= theme.colors.default.bgSecondary; main.default.color ??= theme.colors.default.textPrimary; main.default.zIndex ??= 1; // To make main view go over the sidebar // Main primary main.primary ??= {}; // Main top default main.primary.default ??= {}; main.primary.default.flex ??= "1"; main.primary.default.minHeight ??= 0; // Main secondary main.secondary ??= {}; // Main secondary default main.secondary.default ??= {}; main.secondary.default.height ??= "100%"; main.secondary.default.bg ??= theme.colors.default.bgPrimary; main.secondary.default.color ??= theme.colors.default.textPrimary; main.secondary.default.borderTop ??= `1px solid ${theme.colors.default.primary};`; return this; } /** Set default tabs component */ private static _tabs() { const tabs = this._getComponent("tabs"); const theme = this._themeReady; // Default tabs.default ??= {}; tabs.default.display ??= "flex"; tabs.default.justifyContent ??= "space-between"; tabs.default.userSelect ??= "none"; tabs.default.bg ??= theme.components.main.default.bg; tabs.default.borderBottom ??= `1px solid ${theme.colors.default.border}`; tabs.default.fontSize ??= theme.font.code.size.small; // Tab tabs.tab ??= {}; // Tab default tabs.tab.default ??= {}; tabs.tab.default.display ??= "flex"; tabs.tab.default.justifyContent ??= "center"; tabs.tab.default.alignItems ??= "center"; tabs.tab.default.width ??= "fit-content"; tabs.tab.default.height ??= theme.components.sidebar.right.title.height; tabs.tab.default.paddingLeft ??= "0.5rem"; tabs.tab.default.color ??= theme.colors.default.textSecondary; tabs.tab.default.border ??= "1px solid transparent"; tabs.tab.default.borderRightColor ??= theme.colors.default.border; // Adding transition for `translate` property cause flickering after sorting tabs.tab.default.transition ??= `all ${theme.default.transition.duration.short} ${theme.default.transition.type}, translate: none`; tabs.tab.default.hover ??= {}; tabs.tab.default.hover.cursor ??= "pointer"; tabs.tab.default.hover.bg ??= theme.colors.state.hover.bg; tabs.tab.default.hover.color ??= theme.colors.default.textPrimary; // Tab selected tabs.tab.selected ??= {}; tabs.tab.selected.borderColor ??= theme.colors.default.secondary + theme.default.transparency.medium; // Tab current tabs.tab.current ??= {}; tabs.tab.current.bg ??= theme.colors.default.bgPrimary; tabs.tab.current.color ??= theme.colors.default.textPrimary; tabs.tab.current.borderTopColor ??= theme.colors.default.secondary; // Tab drag tabs.tab.drag ??= {}; tabs.tab.drag.position ??= "relative"; tabs.tab.drag.borderColor ??= theme.colors.default.secondary + theme.default.transparency.high; tabs.tab.drag.after ??= {}; tabs.tab.drag.after.content ??= '""'; tabs.tab.drag.after.position ??= "absolute"; tabs.tab.drag.after.inset ??= 0; tabs.tab.drag.after.width ??= "100%"; tabs.tab.drag.after.height ??= "100%"; tabs.tab.drag.after.bg ??= tabs.default.bg; // Tab drag overlay tabs.tab.dragOverlay ??= {}; tabs.tab.dragOverlay.opacity ??= 0.6; return this; } /** Set default editor component */ private static _editor() { const editor = this._getComponent("editor"); const theme = this._themeReady; editor.default ??= {}; editor.default.bg ??= theme.colors.default.bgPrimary; editor.default.color ??= theme.colors.default.textPrimary; editor.default.fontFamily ??= theme.font.code.family; editor.default.fontSize ??= theme.font.code.size.large; // Editor cursor color editor.default.cursorColor ??= theme.colors.default.textSecondary; // Editor active line editor.default.activeLine ??= {}; editor.default.activeLine.bg ??= "inherit"; editor.default.activeLine.borderColor ??= theme.colors.default.border; // Editor selection editor.default.selection ??= {}; editor.default.selection.bg ??= theme.colors.default.primary + theme.default.transparency.medium; editor.default.selection.color ??= "inherit"; // Editor search match editor.default.searchMatch ??= {}; editor.default.searchMatch.bg ??= theme.colors.default.textSecondary + theme.default.transparency.medium; editor.default.searchMatch.color ??= "inherit"; editor.default.searchMatch.selectedBg ??= "inherit"; editor.default.searchMatch.selectedColor ??= "inherit"; // Editor gutter editor.gutter ??= {}; editor.gutter.bg ??= editor.default.bg; editor.gutter.color ??= theme.colors.default.textSecondary; editor.gutter.activeBg ??= "inherit"; editor.gutter.activeColor ??= theme.colors.default.textPrimary; editor.gutter.borderRight ??= "none"; // Editor inlay hint editor.inlayHint ??= {}; editor.inlayHint.bg ??= "#262730aa"; editor.inlayHint.color ??= theme.colors.default.textSecondary; editor.inlayHint.parameterBg ??= editor.inlayHint.bg; editor.inlayHint.parameterColor ??= editor.inlayHint.color; editor.inlayHint.typeBg ??= editor.inlayHint.bg; editor.inlayHint.typeColor ??= editor.inlayHint.color; // Editor minimap editor.minimap ??= {}; editor.minimap.bg ??= editor.default.bg; editor.minimap.selectionHighlight ??= theme.colors.default.secondary; // Editor peek view editor.peekView ??= {}; editor.peekView.borderColor ??= theme.colors.default.primary; // Editor peek view title editor.peekView.title ??= {}; editor.peekView.title.bg ??= theme.colors.default.bgSecondary; editor.peekView.title.labelColor ??= theme.colors.default.textPrimary; editor.peekView.title.descriptionColor ??= theme.colors.default.textSecondary; // Editor peek view editor editor.peekView.editor ??= {}; editor.peekView.editor.bg ??= theme.colors.default.bgSecondary; editor.peekView.editor.matchHighlightBg ??= theme.colors.state.warning.color + theme.default.transparency.medium; editor.peekView.editor.gutterBg ??= editor.peekView.editor.bg; // Editor peek view result editor.peekView.result ??= {}; editor.peekView.result.bg ??= theme.colors.default.bgPrimary; editor.peekView.result.lineColor ??= theme.colors.default.textSecondary; editor.peekView.result.fileColor ??= theme.colors.default.textSecondary; editor.peekView.result.selectionBg ??= theme.colors.default.primary + theme.default.transparency.low; editor.peekView.result.selectionColor ??= theme.colors.default.textPrimary; editor.peekView.result.matchHighlightBg ??= theme.colors.state.warning.color + theme.default.transparency.medium; // Editor tooltip/widget editor.tooltip ??= {}; editor.tooltip.bg ??= theme.colors.default.bgSecondary; editor.tooltip.color ??= theme.colors.default.textPrimary; editor.tooltip.selectedBg ??= theme.colors.default.primary + theme.default.transparency.medium; editor.tooltip.selectedColor ??= theme.colors.default.textPrimary; editor.tooltip.borderColor ??= theme.colors.default.border; // Editor wrapper editor.wrapper ??= {}; return this; } /** Set default home view */ private static _home() { const main = this._getComponent("main"); const theme = this._themeReady; main.primary!.home ??= {}; const home = main.primary!.home; // Default home.default ??= {}; home.default.height ??= "100%"; home.default.padding ??= "0 8%"; // Title home.title ??= {}; home.title.color ??= theme.colors.default.textSecondary; home.title.padding ??= "2rem"; home.title.fontWeight ??= "bold"; home.title.fontSize ??= "2rem"; home.title.textAlign ??= "center"; // Resources home.resources ??= {}; // Resources default home.resources.default ??= {}; home.resources.default.maxWidth ??= "53rem"; // Resources title home.resources.title ??= {}; home.resources.title.marginBottom ??= "1rem"; home.resources.title.fontWeight ??= "bold"; home.resources.title.fontSize ??= "1.25rem"; // Resources card home.resources.card ??= {}; // Resources card default home.resources.card.default ??= {}; home.resources.card.default.bg ??= theme.colors.default.bgPrimary; home.resources.card.default.color ??= theme.colors.default.textPrimary; home.resources.card.default.border ??= `1px solid ${ theme.colors.default.border + theme.default.transparency.medium }`; home.resources.card.default.borderRadius ??= theme.default.borderRadius; home.resources.card.default.width ??= "15rem"; home.resources.card.default.height ??= "15rem"; home.resources.card.default.padding ??= "1rem 1.5rem 1.5rem 1.5rem"; home.resources.card.default.marginRight ??= "2rem"; home.resources.card.default.marginBottom ??= "2rem"; // Resources card image home.resources.card.image ??= {}; home.resources.card.image.width ??= "1.25rem"; home.resources.card.image.height ??= "1.25rem"; home.resources.card.image.marginRight ??= "0.5rem"; // Resources card title home.resources.card.title ??= {}; home.resources.card.title.display ??= "flex"; home.resources.card.title.alignItems ??= "center"; home.resources.card.title.height ??= "20%"; home.resources.card.title.fontWeight ??= "bold"; home.resources.card.title.fontSize ??= theme.font.code.size.xlarge; // Resources card description home.resources.card.description ??= {}; home.resources.card.description.color ??= theme.colors.default.textSecondary; home.resources.card.description.height ??= "60%"; // Resources card button home.resources.card.button ??= {}; home.resources.card.button.width ??= "100%"; // Tutorials home.tutorials ??= {}; // Tutorials default home.tutorials.default ??= {}; home.tutorials.default.minWidth ??= "16rem"; home.tutorials.default.maxWidth ??= "27rem"; // Tutorials title home.tutorials.title ??= {}; home.tutorials.title.marginBottom ??= "1rem"; home.tutorials.title.fontWeight ??= "bold"; home.tutorials.title.fontSize ??= "1.25rem"; // Tutorials card home.tutorials.card ??= {}; home.tutorials.card.bg ??= theme.colors.default.bgPrimary; home.tutorials.card.color ??= theme.colors.default.textPrimary; home.tutorials.card.border ??= `1px solid ${theme.colors.default.border + theme.default.transparency.medium}`; home.tutorials.card.borderRadius ??= theme.default.borderRadius; home.tutorials.card.padding ??= "1rem"; home.tutorials.card.marginBottom ??= "1rem"; home.tutorials.card.transition ??= `all ${theme.default.transition.duration.medium} ${theme.default.transition.type}`; home.tutorials.card.display ??= "flex"; home.tutorials.card.alignItems ??= "center"; home.tutorials.card.hover ??= {}; home.tutorials.card.hover.bg ??= theme.colors.state.hover.bg; return this; } /** Set default tutorial view */ private static _tutorial() { const main = this._getComponent("main"); const theme = this._themeReady; main.primary!.tutorial ??= {}; const tutorial = main.primary!.tutorial; // Default tutorial.default ??= {}; tutorial.default.flex ??= 1; tutorial.default.overflow ??= "auto"; tutorial.default.opacity ??= 0; tutorial.default.transition ??= `opacity ${theme.default.transition.duration.medium} ${theme.default.transition.type}`; // About page tutorial.aboutPage ??= {}; tutorial.aboutPage.bg ??= theme.colors.default.bgPrimary; tutorial.aboutPage.borderBottomRightRadius ??= theme.default.borderRadius; tutorial.aboutPage.borderTopRightRadius ??= theme.default.borderRadius; tutorial.aboutPage.fontFamily ??= theme.font.other.family; tutorial.aboutPage.fontSize ??= theme.font.other.size.medium; tutorial.aboutPage.padding ??= "2rem"; tutorial.aboutPage.maxWidth ??= "60rem"; // Tutorial page tutorial.tutorialPage ??= {}; tutorial.tutorialPage.bg ??= theme.colors.default.bgPrimary; tutorial.tutorialPage.fontFamily ??= theme.font.other.family; tutorial.tutorialPage.fontSize ??= theme.font.other.size.medium; tutorial.tutorialPage.padding ??= "2rem"; return this; } /** Set default tutorials view */ private static _tutorials() { const main = this._getComponent("main"); const theme = this._themeReady; main.primary!.tutorials ??= {}; const tutorials = main.primary!.tutorials; // Default tutorials.default ??= {}; tutorials.default.display ??= "flex"; tutorials.default.flexDirection ??= "column"; tutorials.default.bg ??= theme.components.main.default.bg; tutorials.default.fontFamily ??= theme.font.other.family; tutorials.default.fontSize ??= theme.font.other.size.medium; // Top tutorials.top ??= {}; tutorials.top.display = "flex"; tutorials.top.justifyContent = "space-between"; tutorials.top.padding = "1rem 2.5rem"; tutorials.top.bg ??= this.getDifferentBackground(tutorials.default.bg); tutorials.top.borderBottom ??= `1px solid ${theme.colors.default.border}`; tutorials.top["& > div"] ??= {}; tutorials.top["& > div"].width ??= "max(12rem, 50%)"; // Main tutorials.main ??= {}; // Main default tutorials.main.default ??= {}; tutorials.main.default.display ??= "flex"; tutorials.main.default.height ??= "100%"; tutorials.main.default.bg ??= this.getDifferentBackground( theme.components.main.default.bg ); tutorials.main.default.borderRadius ??= theme.default.borderRadius; // Main side (filters) tutorials.main.side ??= {}; tutorials.main.side.width ??= "14.5rem"; tutorials.main.side.flexShrink ??= 0; tutorials.main.side.padding ??= "0.5rem"; tutorials.main.side.borderRight ??= `1px solid ${theme.colors.default.border}`; tutorials.main.side.borderTopLeftRadius ??= theme.components.main.primary.tutorials.main.default.borderRadius; tutorials.main.side.borderBottomLeftRadius ??= theme.components.main.primary.tutorials.main.default.borderRadius; // Main content (tutorials) tutorials.main.content ??= {}; // Main content default tutorials.main.content.default ??= {}; tutorials.main.content.default.padding ??= "1.5rem"; tutorials.main.content.default.display ??= "flex"; tutorials.main.content.default.flexDirection ??= "column"; tutorials.main.content.default.flexGrow ??= 1; tutorials.main.content.default.gap ??= "2rem"; tutorials.main.content.default.overflow ??= "auto"; tutorials.main.content.default.bg ??= tutorials.main.default.bg; tutorials.main.content.default.borderTopRightRadius ??= theme.components.main.primary.tutorials.main.default.borderRadius; tutorials.main.content.default.borderBottomRightRadius ??= theme.components.main.primary.tutorials.main.default.borderRadius; //Main content card tutorials.main.content.card ??= {}; const card = tutorials.main.content.card; //Main content card default card.default ??= {}; card.default.width ??= "100%"; card.default.height ??= "100%"; card.default.overflow ??= "hidden"; card.default.bg ??= theme.components.main.primary.tutorials.main.default.bg; card.default.color ??= theme.colors.default.textPrimary; card.default.border ??= `1px solid ${ theme.colors.default.border + theme.default.transparency.medium }`; card.default.borderRadius ??= theme.default.borderRadius; card.default.boxShadow ??= theme.default.boxShadow; card.default.transition ??= `all ${theme.default.transition.duration.medium} ${theme.default.transition.type}`; //Main content card gradient card.gradient ??= {}; // Main content featured tutorial tutorials.main.content.featured ??= {}; const featured = tutorials.main.content.featured; featured.height ??= "20rem"; featured.display ??= "flex"; featured.border ??= `1px solid ${theme.colors.default.border}`; featured.borderRadius ??= theme.default.borderRadius; featured.boxShadow ??= theme.default.boxShadow; featured.overflow ??= "hidden"; return this; } /** Set default programs view */ private static _programs() { const main = this._getComponent("main"); const theme = this._themeReady; main.primary!.programs ??= {}; const programs = main.primary!.programs; // Default programs.default ??= {}; programs.default.bg ??= theme.components.main.default.bg; programs.default.fontFamily ??= theme.font.other.family; programs.default.fontSize ??= theme.font.other.size.medium; // Top programs.top ??= {}; programs.top.position ??= "sticky"; programs.top.top ??= 0; programs.top.display ??= "flex"; programs.top.justifyContent ??= "space-between"; programs.top.alignItems ??= "center"; programs.top.width ??= "100%"; programs.top.height ??= "4.5rem"; programs.top.padding ??= "1rem 2.5rem"; programs.top.bg ??= this.getDifferentBackground(programs.default.bg); programs.top.borderBottom ??= `1px solid ${theme.colors.default.border}`; programs.top["& > div"] ??= {}; programs.top["& > div"].width ??= "max(12rem, 50%)"; // Main programs.main ??= {}; // Main default programs.main.default ??= {}; programs.main.default.display ??= "flex"; programs.main.default.minHeight ??= `calc(100% - ${programs.top.height})`; programs.main.default.padding ??= "2rem 2.5rem"; // Main content programs.main.content ??= {}; // Main content default programs.main.content.default ??= {}; programs.main.content.default.display ??= "flex"; programs.main.content.default.flexWrap ??= "wrap"; programs.main.content.default.flexGrow ??= 1; programs.main.content.default.gap ??= "1.5rem"; // Main content card programs.main.content.card ??= {}; programs.main.content.card.flexGrow ??= 1; programs.main.content.card.flexBasis ??= "50%"; programs.main.content.card.display ??= "flex"; programs.main.content.card.flexDirection ??= "column"; programs.main.content.card.gap ??= "0.5rem"; programs.main.content.card.maxWidth ??= "44.95rem"; programs.main.content.card.height ??= "fit-content"; programs.main.content.card.padding ??= "1rem"; programs.main.content.card.border ??= `1px solid ${theme.colors.default.border}`; programs.main.content.card.borderRadius ??= theme.default.borderRadius; return this; } }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/wallet/wallet.ts
import * as ed25519 from "@noble/ed25519"; import { PgCommon } from "../common"; import { createDerivable, declareDerivable, declareUpdatable, derivable, migratable, updatable, } from "../decorators"; import { PgWeb3 } from "../web3"; import type { AnyTransaction, CurrentWallet, SerializedWallet, StandardWallet, StandardWalletProps, Wallet, WalletAccount, } from "./types"; import type { RequiredKey } from "../types"; const defaultState: Wallet = { state: "setup", accounts: [], currentIndex: -1, balance: null, show: false, standardWallets: [], standardName: null, }; const storage = { /** Relative path to program info */ KEY: "wallet", /** Read from storage and deserialize the data. */ read(): Wallet { const serializedStateStr = localStorage.getItem(this.KEY); if (!serializedStateStr) return defaultState; const serializedState: SerializedWallet = JSON.parse(serializedStateStr); return { ...serializedState, balance: defaultState.balance, show: defaultState.show, standardWallets: defaultState.standardWallets, }; }, /** Serialize the data and write to storage. */ write(wallet: Wallet) { // Don't use spread operator(...) because of the extra derived state const serializedState: SerializedWallet = { accounts: wallet.accounts, currentIndex: wallet.currentIndex, state: wallet.state, standardName: wallet.standardName, }; localStorage.setItem(this.KEY, JSON.stringify(serializedState)); }, }; const derive = () => ({ /** A Wallet Standard wallet adapter */ standard: createDerivable({ derive: (): StandardWallet | null => { const otherWallet = PgWallet.standardWallets.find( (wallet) => wallet.adapter.name === PgWallet.standardName ); return otherWallet?.adapter ?? null; }, onChange: ["standardWallets", "standardName"], }), /** * The current active wallet. * * It will be one of the following: * - The Playground Wallet * - A Wallet Standard wallet * - `null` if not connected. */ current: createDerivable({ derive: async (): Promise<CurrentWallet | null> => { switch (PgWallet.state) { case "pg": { // Check whether the current account exists const currentAccount = PgWallet.accounts[PgWallet.currentIndex]; if (!currentAccount) { if (!PgWallet.accounts.length) PgWallet.add(); else PgWallet.switch(0); return null; } return PgWallet.create(currentAccount); } case "sol": if (!PgWallet.standard || PgWallet.standard.connecting) return null; if (!PgWallet.standard.connected) await PgWallet.standard.connect(); return PgWallet.standard as StandardWalletProps; case "disconnected": case "setup": return null; } }, onChange: ["state", "accounts", "currentIndex", "standard"], }), }); // TODO: Remove in 2024 const migrate = () => { const walletStr = localStorage.getItem(storage.KEY); if (!walletStr) return; interface OldWallet { setupCompleted: boolean; connected: boolean; sk: Array<number>; } const oldOrNewWallet: OldWallet | Wallet = JSON.parse(walletStr); if ((oldOrNewWallet as Wallet).accounts) return; const oldWallet = oldOrNewWallet as OldWallet; const newWallet: Wallet = { ...defaultState, state: oldWallet.setupCompleted ? oldWallet.connected ? "pg" : "disconnected" : "setup", accounts: [{ kp: oldWallet.sk, name: "Wallet 1" }], }; // Set the new wallet format localStorage.setItem(storage.KEY, JSON.stringify(newWallet)); // Remove wallet adapter key localStorage.removeItem("walletName"); }; @migratable(migrate) @derivable(derive) @updatable({ defaultState, storage }) class _PgWallet { /** * Add a new account. * * @param name name of the account * @param keypair optional keypair, default to a random keypair */ static add(params?: { name?: string; keypair?: PgWeb3.Keypair }) { const { name, keypair } = PgCommon.setDefault(params, { name: PgWallet.getNextAvailableAccountName(), keypair: PgWeb3.Keypair.generate(), }); // Validate name PgWallet.validateAccountName(name); // Check if account exists const accountIndex = PgWallet.accounts.findIndex((acc) => { return ( (name && acc.name === name) || PgWallet.create(acc).publicKey.equals(keypair.publicKey) ); }); if (accountIndex !== -1) { // Account exists, switch to the account PgWallet.switch(accountIndex); return; } // Add the account PgWallet.accounts.push({ kp: Array.from(keypair.secretKey), name, }); // Update the accounts PgWallet.update({ state: "pg", accounts: PgWallet.accounts, currentIndex: PgWallet.accounts.length - 1, }); } /** * Remove the account at the given index. * * @param index account index */ static remove(index: number = PgWallet.currentIndex) { PgWallet.accounts.splice(index, 1); // Update the accounts PgWallet.update({ accounts: PgWallet.accounts, currentIndex: PgWallet.accounts.length - 1, }); } /** * Rename the account. * * @param name new name of the account * @param index account index */ static rename(name: string, index: number = PgWallet.currentIndex) { // Validate name PgWallet.validateAccountName(name); PgWallet.accounts[index].name = name; // Update the accounts PgWallet.update({ accounts: PgWallet.accounts }); } /** * Import a keypair from the user's file system. * * @param name name of the account * @returns the imported keypair if importing was successful */ static async import(name?: string) { return await PgCommon.import( async (ev) => { const files = ev.target.files; if (!files?.length) return; try { const file = files[0]; const arrayBuffer = await file.arrayBuffer(); const decodedString = PgCommon.decodeBytes(arrayBuffer); const keypairBytes = Uint8Array.from(JSON.parse(decodedString)); if (keypairBytes.length !== 64) throw new Error("Invalid keypair"); const keypair = PgWeb3.Keypair.fromSecretKey(keypairBytes); PgWallet.add({ name, keypair }); return keypair; } catch (err: any) { console.log(err.message); } }, { accept: ".json" } ); } /** * Export the given or the existing keypair to the user's file system. * * @param keypair optional keypair, defaults to the current wallet's keypair */ static export(keypair?: PgWeb3.Keypair) { if (!keypair) { if (!PgWallet.current) throw new Error("Not connected"); if (!PgWallet.current.isPg) throw new Error("Not Playground Wallet"); keypair = PgWallet.current.keypair; } return PgCommon.export( `${PgWallet.current?.name ?? "wallet"}-keypair.json`, Array.from(keypair.secretKey) ); } /** * Switch to the given account index. * * @param index account index to switch to */ static switch(index: number) { if (!PgWallet.accounts[index]) { throw new Error(`Account index '${index}' not found`); } PgWallet.update({ state: "pg", currentIndex: index, }); } /** * Get the default name of the wallet account. * * @param index account index * @returns the wallet account name */ static getDefaultAccountName(index: number = PgWallet.currentIndex) { return `Wallet ${index + 1}`; } /** * Get the next available default account name. * * This method recurses until it founds an available wallet account name. * * @param index account index * @returns the next available default account name */ static getNextAvailableAccountName( index: number = PgWallet.accounts.length ): string { try { const name = PgWallet.getDefaultAccountName(index); PgWallet.validateAccountName(name); return name; } catch { return PgWallet.getNextAvailableAccountName(index + 1); } } /** * Get all of the connected standard wallet adapters. * * @returns the connected standard wallet adapters */ static getConnectedStandardWallets() { return PgWallet.standardWallets .map((wallet) => wallet.adapter) .filter((adapter) => adapter.connected) as RequiredKey< typeof PgWallet["standardWallets"][number]["adapter"], "publicKey" >[]; } /** * Create a Playground Wallet instance from the given account. * * @param account wallet account to derive the instance from * @returns a Playground Wallet instance */ static create(account: WalletAccount): CurrentWallet { const keypair = PgWeb3.Keypair.fromSecretKey(Uint8Array.from(account.kp)); return { isPg: true, keypair, name: account.name, publicKey: keypair.publicKey, async signTransaction<T extends AnyTransaction>(tx: T) { if ((tx as PgWeb3.VersionedTransaction).version) { (tx as PgWeb3.VersionedTransaction).sign([keypair]); } else { (tx as PgWeb3.Transaction).partialSign(keypair); } return tx; }, async signAllTransactions<T extends AnyTransaction>(txs: T[]) { for (const tx of txs) { this.signTransaction(tx); } return txs; }, async signMessage(message: Uint8Array) { return await ed25519.sign(message, keypair.secretKey.slice(0, 32)); }, }; } /** * Check whether the given wallet account name is valid. * * @param name wallet account name * @throws if the name is not valid */ static validateAccountName(name: string) { name = name.trim(); // Empty check if (!name) throw new Error("Account name can't be empty"); // Check whether the name exists const nameExists = PgWallet.accounts.some((acc) => acc.name === name); if (nameExists) throw new Error(`Account '${name}' already exists`); } } export const PgWallet = declareDerivable( declareUpdatable(_PgWallet, { defaultState }), derive );
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/wallet/types.ts
import type { Adapter, MessageSignerWalletAdapterProps, SignerWalletAdapterProps, WalletAdapter, WalletAdapterProps, } from "@solana/wallet-adapter-base"; import type { Wallet as SolanaWallet } from "@solana/wallet-adapter-react"; import type { PgWeb3 } from "../web3"; /** Wallet state */ export interface Wallet { /** Wallet connection state */ state: "setup" | "disconnected" | "pg" | "sol"; /** All accounts */ accounts: WalletAccount[]; /** Current wallet index */ currentIndex: number; /** Balance of the current wallet, `null` by default */ balance: number | null; /** Whether to show the `Wallet` component */ show: boolean; /** Wallet Standard wallets */ standardWallets: SolanaWallet[]; /** Name of the standard wallet */ standardName: string | null; } /** Playground wallet accounts (with keypair) */ export interface WalletAccount { /** * ed25519 keypair of the account. * * First 32 bytes are the private key, last 32 bytes are the public key. */ kp: number[]; /** Name of the account */ name: string; } /** Serialized wallet that's used in storage */ export type SerializedWallet = Pick< Wallet, "state" | "accounts" | "currentIndex" | "standardName" >; /** Legacy or versioned transaction */ export type AnyTransaction = PgWeb3.Transaction | PgWeb3.VersionedTransaction; /** * The current wallet which can be a Playground Wallet, a Wallet Standard Wallet * or `null` if disconnected. */ export type CurrentWallet = PgWalletProps | StandardWalletProps; /** Wallet Standard wallet */ export type StandardWallet = StandardWalletProps | Adapter; /** Playground Wallet props */ interface PgWalletProps extends DefaultWalletProps { /** The wallet is Playground Wallet */ isPg: true; /** Keypair of the Playground Wallet account */ keypair: PgWeb3.Keypair; } /** All wallets other than Playground Wallet */ export interface StandardWalletProps extends DefaultWalletProps, DefaultAdapter { /** The wallet is not Playground Wallet */ isPg: false; } /** Wallet adapter without `publicKey` prop */ type DefaultAdapter = Omit<WalletAdapter, "publicKey" | "name">; /** Common props for both Playground Wallet and other wallets */ type DefaultWalletProps<PublicKeyProp = Pick<WalletAdapterProps, "publicKey">> = Pick< SignerWalletAdapterProps & MessageSignerWalletAdapterProps, "signMessage" | "signTransaction" | "signAllTransactions" > & { [K in keyof PublicKeyProp]: NonNullable<PublicKeyProp[K]>; } & { /** Name of the account */ name: string; }; /** Optional `wallet` prop */ export interface WalletOption { /** Wallet to use */ wallet?: CurrentWallet; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/wallet/index.ts
export { PgWallet } from "./wallet"; export * from "./types";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/client/client.ts
import { ScriptTarget, transpile } from "typescript"; import * as mocha from "mocha"; import * as util from "util"; import * as anchor from "@coral-xyz/anchor"; import { ClientPackageName, PgClientPackage } from "./package"; import { PgCommon } from "../common"; import { PgConnection } from "../connection"; import { PgProgramInfo } from "../program-info"; import { PgProgramInteraction } from "../program-interaction"; import { PgTerminal } from "../terminal"; import { CurrentWallet, PgWallet, StandardWallet } from "../wallet"; import type { MergeUnion, OrString } from "../types"; import type { PgWeb3 } from "../web3"; /** Options to use when running a script/test */ interface ClientParams { /** Name of the file to execute */ fileName: string; /** JS/TS code to execute */ code: string; /** Whether to run the script as a test */ isTest: boolean; } export class PgClient { /** * Run or test JS/TS code. * * @param params client parameters */ static async execute({ fileName, code, isTest }: ClientParams) { await this._executeBlocking( async () => { PgTerminal.log(` ${fileName}:`); // Get Iframe window const iframeWindow = this._getIframeWindow(); // Remove everything from the iframe window object for (const key in iframeWindow) { try { delete iframeWindow[key]; } catch { // Not every key can be deleted from the window object } } // Get globals const { globals, endCode } = await this._getGlobals({ isTest }); // Handle imports const importResult = await this._getImports(code); globals.push(...importResult.imports); code = importResult.code; // Set iframe globals for (const [name, pkg] of globals) { // @ts-ignore iframeWindow[name] = pkg; } // `describe` is only available when as test if (isTest && !code.includes("describe")) { throw new Error( `Tests must use '${PgTerminal.bold( "describe" )}' function. Use '${PgTerminal.bold( "run" )}' command to run the script.` ); } // Handle blacklisted globals for (const keyword of BLACKLISTED_GLOBALS) { if (code.includes(keyword)) { throw new Error(`'${keyword}' is not allowed`); } } // Handle globals to set `undefined` to for (const keyword of UNDEFINED_GLOBALS) { code = `${keyword} = undefined;` + code; } // This approach: // 1- Wraps the code in a class to block window access from `this` // 2- Allows top-level async // 3- Helps detecting when tests finish code = `(async () => { class __Pg { async __run() {\n${code}\n} } const __pg = new __Pg(); try { await __pg.__run(); } catch (e) { console.log("Uncaught error:", e.message); } finally { ${endCode} } })()`; // Transpile the code code = transpile(code, { target: ScriptTarget.ES5, removeComments: true, }); // Create script element in the iframe const iframeDocument = iframeWindow.document; const scriptEls = iframeDocument.getElementsByTagName("script"); if (scriptEls.length) iframeDocument.head.removeChild(scriptEls[0]); const scriptEl = document.createElement("script"); iframeDocument.head.appendChild(scriptEl); return new Promise<void>((res) => { if (isTest) { const intervalId = setInterval(() => { // @ts-ignore if (mocha._state === "init") { clearInterval(intervalId); res(); } }, 1000); } else { const { dispose } = PgCommon.onDidChange({ cb: () => { PgTerminal.log(""); dispose(); res(); }, eventName: CLIENT_ON_DID_FINISH_RUNNING, }); } // Inject the script to the iframe element scriptEl.textContent = code; }); }, { isTest } ); } /** * Wrapper method to control client running state. * * @param cb callback function to run * @param isTest whether to execute as a test */ private static async _executeBlocking( cb: () => Promise<void>, { isTest }: Pick<ClientParams, "isTest"> ) { // Block creating multiple client/test instances at the same time if (this._isClientRunning) { if (isTest) throw new Error("Please wait for client to finish."); throw new Error("Client is already running!"); } // @ts-ignore if (mocha._state === "running") { if (!isTest) throw new Error("Please wait for tests to finish."); throw new Error("Tests are already running!"); } try { if (!isTest) this._isClientRunning = true; await cb(); } catch (e) { throw e; } finally { if (!isTest) this._isClientRunning = false; } } /** * Get or create the window object of the `Iframe` element. * * @returns `Iframe`'s window element */ private static _getIframeWindow() { if (this._IframeWindow) return this._IframeWindow; const iframeEl = document.createElement("iframe"); iframeEl.style.display = "none"; document.body.appendChild(iframeEl); const iframeWindow = iframeEl.contentWindow; if (!iframeWindow) throw new Error("No iframe window"); // Non runtime errors e.g. syntax iframeWindow.addEventListener("error", (ev) => { PgTerminal.log(` ${ev.message}`); // This kind of error requires custom event dispatch to indicate the // client has finished running, otherwise client will stay in the running // state indefinitely. PgCommon.createAndDispatchCustomEvent(CLIENT_ON_DID_FINISH_RUNNING); }); // Promise/async errors iframeWindow.addEventListener("unhandledrejection", (ev) => { PgTerminal.log(` ${`Uncaught error: ${ev.reason.message}`}`); // Does not require custom event dispatch to indicate running has finished }); this._IframeWindow = iframeWindow; return this._IframeWindow; } /** * Get global variables. * * @param isTest whether to execute as a test * @returns the globals and the end code to indicate when the execution is over */ private static async _getGlobals({ isTest }: Pick<ClientParams, "isTest">) { // Redefine console inside the iframe to log in the terminal const log = (cb?: (text: string) => string) => { return (...args: any[]) => { return PgTerminal.log( " " + (cb ? cb(util.format(...args)) : util.format(...args)) ); }; }; const iframeConsole = { log: log(), info: log(PgTerminal.info), warn: log(PgTerminal.warning), error: log(PgTerminal.error), }; const globals: [string, object][] = [ // Playground global ["pg", this._getPg()], // Namespaces ["console", iframeConsole], // https://github.com/solana-playground/solana-playground/issues/82 ["Uint8Array", Uint8Array], // Functions ["sleep", PgCommon.sleep], ]; // Set global packages await Promise.all( PgCommon.entries(PACKAGES.global).map( async ([packageName, importStyle]) => { const style = importStyle as Partial<MergeUnion<typeof importStyle>>; const pkg: { [name: string]: any } = await PgClientPackage.import( packageName ); this._overridePackage(packageName, pkg); let global: typeof globals[number]; if (style.as) global = [style.as, pkg]; else if (style.named) global = [style.named, pkg[style.named]]; else if (style.default) global = [style.default, pkg.default ?? pkg]; else throw new Error("Unreachable"); globals.push(global); } ) ); let endCode: string; if (isTest) { endCode = "_run()"; // Setup mocha try { if (describe !== undefined) { // Reset suite // @ts-ignore mocha.suite.suites = []; // @ts-ignore mocha.suite.tests = []; } } catch {} // @ts-ignore mocha.setup({ ui: "bdd", timeout: "30000", // Mocha disposes itself after the `run` function without this option cleanReferencesAfterRun: false, // Logs the test output to the browser console reporter: "spec", }); // Set mocha globals globals.push( ["after", after], ["afterEach", afterEach], ["before", before], ["beforeEach", beforeEach], ["context", context], ["describe", describe], ["it", it], ["specify", specify], ["xcontext", xcontext], ["xdescribe", xdescribe], ["xit", xit], ["xspecify", xspecify], ["_run", mocha.run] ); } else { // Run only endCode = "__end()"; globals.push([ "__end", () => { PgCommon.createAndDispatchCustomEvent(CLIENT_ON_DID_FINISH_RUNNING); }, ]); } return { globals, endCode }; } /** * Handle user specified imports. * * @param code script/test code * @returns the imported packages and the code without the import statements */ private static async _getImports(code: string) { const importRegex = /import\s+(?:((\*\s+as\s+(\w+))|({[\s+\w+\s+,]*})|(\w+))\s+from\s+)?["|'](.+)["|']/gm; let importMatch: RegExpExecArray | null; const imports: [string, object][] = []; const setupImport = (pkg: { [key: string]: any }) => { // `import as *` syntax if (importMatch?.[3]) { imports.push([importMatch[3], pkg]); } // `import {}` syntax else if (importMatch?.[4]) { const namedImports = importMatch[4] .substring(1, importMatch[4].length - 1) .replace(/\n?/g, "") .split(",") .map((statement) => statement.trim()) .filter(Boolean) .map((statement) => { const result = /(\w+)(\s+as\s+(\w+))?/.exec(statement)!; return { named: result[1], renamed: result[3] }; }); for (const { named, renamed } of namedImports) { imports.push([renamed ?? named, pkg[named]]); } } // `import Default` syntax else if (importMatch?.[5]) { imports.push([importMatch[5], pkg.default ?? pkg]); } }; do { importMatch = importRegex.exec(code); if (!importMatch) continue; const importPath = importMatch[6]; const getPackage = importPath.startsWith(".") ? this._importFromPath : PgClientPackage.import; const pkg = await getPackage(importPath); this._overridePackage(importPath, pkg); setupImport(pkg); } while (importMatch); // Remove import statements // Need to do this after we setup all the imports because of the internal // cursor index state the `regex.exec` has. code = code.replace(importRegex, ""); return { code, imports }; } /** * Import module from the given path. * * @param path import path * @returns the imported module */ private static async _importFromPath(path: string) { // TODO: Remove after adding general support for local imports. // Add a special case for Anchor's `target/types` if (path.includes("target/types")) { if (PgProgramInfo.idl) return { IDL: PgProgramInfo.idl }; throw new Error("IDL not found, build the program to create the IDL."); } throw new Error("File imports are not yet supported."); } /** * Override the package. * * NOTE: This method mutates the given `pkg` in place. * * @param name package name * @param pkg package * @returns the overridden package */ private static _overridePackage(name: OrString<ClientPackageName>, pkg: any) { // Anchor if (name === "@coral-xyz/anchor" || name === "@project-serum/anchor") { const providerName = name === "@coral-xyz/anchor" ? "AnchorProvider" : "Provider"; // Add `AnchorProvider.local()` pkg[providerName].local = ( url?: string, opts: PgWeb3.ConfirmOptions = anchor.AnchorProvider.defaultOptions() ) => { const connection = PgConnection.create({ endpoint: url ?? "http://localhost:8899", commitment: opts.commitment, }); const wallet = this._getPg().wallet; if (!wallet) throw new Error("Wallet not connected"); const provider = new anchor.AnchorProvider(connection, wallet, opts); return setAnchorWallet(provider); }; // Add `AnchorProvider.env()` pkg[providerName].env = () => { const provider = this._getPg().program?.provider; if (!provider) throw new Error("Provider not ready"); return setAnchorWallet(provider); }; /** * Override `provider.wallet` to have `payer` field with the wallet * keypair in order to have the same behavior as local. */ const setAnchorWallet = (provider: any) => { if (provider.wallet.isPg) { provider.wallet = { ...provider.wallet, payer: provider.wallet.keypair, }; } return provider; }; // Add `anchor.workspace` if (PgProgramInfo.idl) { const snakeCaseName = PgProgramInfo.idl.name; const names = [ PgCommon.toPascalFromSnake(snakeCaseName), // default before 0.29.0 PgCommon.toCamelFromSnake(snakeCaseName), PgCommon.toKebabFromSnake(snakeCaseName), snakeCaseName, ]; pkg.workspace = {}; for (const name of names) { if (pkg.workspace[name]) continue; Object.defineProperty(pkg.workspace, name, { get: () => { let program = this._getPg().program; if (program) { const { idl, programId } = program; program = new anchor.Program(idl, programId, pkg.getProvider()); } return program; }, }); } } } return pkg; } /** * Get `pg` global object. * * @returns the `pg` global object */ private static _getPg() { /** Utilities to be available under the `pg` namespace */ interface Pg { /** Playground connection instance */ connection: PgWeb3.Connection; /** Current connected wallet */ wallet?: CurrentWallet; /** All available wallets, including the standard wallets */ wallets?: Record<string, CurrentWallet | StandardWallet>; /** Current project's program public key */ PROGRAM_ID?: PgWeb3.PublicKey; /** Anchor program instance of the current project */ program?: anchor.Program; } // Playground utils namespace const pg: Pg = { connection: PgConnection.current }; // Wallet if (PgWallet.current) pg.wallet = PgWallet.current; // Wallets if (pg.wallet) { pg.wallets = {}; const pgWallets = PgWallet.accounts.map(PgWallet.create); const standardWallets = PgWallet.getConnectedStandardWallets(); const wallets = [...pgWallets, ...standardWallets]; for (const wallet of wallets) { pg.wallets[PgCommon.toCamelCase(wallet.name)] = wallet; } } // Program ID if (PgProgramInfo.pk) pg.PROGRAM_ID = PgProgramInfo.pk; // Anchor Program if (pg.wallet && PgProgramInfo.idl) { pg.program = PgProgramInteraction.getAnchorProgram(); } return pg; } /** Whether a script is currently running */ private static _isClientRunning: boolean; /** Cached `Iframe` `Window` object */ private static _IframeWindow: Window; } /** Keywords that are not allowed to be in the user code */ const BLACKLISTED_GLOBALS = [ "window", "globalThis", "document", "location", "top", "chrome", ]; /** Globals that will be set to `undefined` */ const UNDEFINED_GLOBALS = ["eval", "Function"]; /** Event name that will be dispatched when client code completes executing */ const CLIENT_ON_DID_FINISH_RUNNING = "clientondidfinishrunning";
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/client/client-importer.ts
import { PgTerminal } from "../terminal"; export class PgClientImporter { /** * Redefine `console.log` to show mocha logs in the terminal and asynchronously * import `PgClient`. */ static async import() { if (!this._isOverridden) { // Override the `console.log` before the initial `PgClient` import console.log = PgTerminal.consoleLog; this._isOverridden = true; } return await import("./client"); } /** Whether `console.log` is overridden */ private static _isOverridden: boolean; }
0
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg
solana_public_repos/solana-playground/solana-playground/client/src/utils/pg/client/index.ts
export { PgClientImporter } from "./client-importer"; export type { ClientPackageName } from "./package";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/languages/rust.ts
import { PgLanguage } from "../utils/pg"; export const rust = PgLanguage.create({ name: "Rust", extension: "rs", });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/languages/json.ts
import { PgLanguage } from "../utils/pg"; export const json = PgLanguage.create({ name: "JSON", extension: "json", });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/languages/languages.ts
export * from "./javascript"; export * from "./json"; export * from "./python"; export * from "./rust"; export * from "./typescript";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/languages/javascript.ts
import { PgLanguage } from "../utils/pg"; export const javascript = PgLanguage.create({ name: "JavaScript", extension: "js", });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/languages/python.ts
import { PgLanguage } from "../utils/pg"; export const python = PgLanguage.create({ name: "Python", extension: "py", });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/languages/typescript.ts
import { PgLanguage } from "../utils/pg"; export const typescript = PgLanguage.create({ name: "TypeScript", extension: "ts", });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/languages/index.ts
import * as _LANGUAGES from "./languages"; /** All programming languages */ export const LANGUAGES = Object.values(_LANGUAGES);
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/SearchBar/SearchBar.tsx
import { Dispatch, FC, ReactNode, SetStateAction, useEffect, useRef, useState, } from "react"; import styled, { css } from "styled-components"; import Button from "../Button"; import Input, { InputProps } from "../Input"; import { Close, PointedArrow, Search } from "../Icons"; import { SpinnerWithBg } from "../Loading"; import { useKeybind, useOnClickOutside } from "../../hooks"; import { Arrayable, Getable, PgCommon, PgTheme } from "../../utils/pg"; export interface SearchBarProps extends InputProps { items?: Item[] | null; initialSelectedItems?: Arrayable<Item>; showSearchOnMount?: boolean; labelToSelectOnPaste?: string; restoreIfNotSelected?: boolean; searchButton?: { position?: "left" | "right"; width?: string; }; onSearch?: (ev: { input: InputProps["value"]; item: NormalizedItem }) => void; filter?: (args: { input: InputProps["value"]; item: NormalizedItem; items: NormalizedItem[]; }) => boolean; setSelectedItems?: Dispatch<SetStateAction<NormalizedItem[]>>; } export type NormalizedItem = Exclude<Item, string> & { isSelected?: boolean }; type Item = string | (CommonItemProps & (NestableItem | DropdownableItem)); type CommonItemProps = { label: string; matches?: Array<string | RegExp> | ((value: string) => boolean); onlyShowIfValid?: boolean; closeButton?: boolean; element?: ReactNode; onSelect?: (item: Item) => void; }; type NestableItem = { value?: string | ((value: string) => string) | { current: true }; data?: any; items?: Getable<Item[]> | (() => Promise<Item[]>) | null; DropdownComponent?: never; }; type DropdownableItem = { value?: never; data?: never; items?: never; DropdownComponent: (props: DropdownProps) => JSX.Element; }; export type DropdownProps = { search: (item: Item) => void; }; const SearchBar: FC<SearchBarProps> = ({ items, initialSelectedItems, showSearchOnMount, labelToSelectOnPaste, restoreIfNotSelected, searchButton, onSearch, filter, setSelectedItems: _setSelectedItems, onClick, onPaste, ...props }) => { const searchButtonPosition = searchButton?.position ?? "left"; const searchButtonWidth = searchButton?.width ?? "2rem"; const inputRef = useRef<HTMLInputElement>(null); const lastValue = useRef(props.value); const setInputValue = (value: string, opts?: { focus: boolean }) => { const input = inputRef.current!; PgCommon.changeInputValue(input, value); // Last value should only be updated when `setInputValue` function runs and // not when `onChange` callback runs because we want to restore to the last // valid value when the user clicks outside of the search bar. lastValue.current = value; if (opts?.focus) input.focus(); }; const getItemValue = (item: NormalizedItem) => { const currentValue = inputRef.current?.value ?? props.value; return item.value !== undefined ? typeof item.value === "string" ? item.value : typeof item.value === "function" ? item.value(currentValue) : currentValue : item.label; }; const [isVisible, setIsVisible] = useState(showSearchOnMount); const wrapperRef = useRef<HTMLDivElement>(null); const reset = () => { // Hide search results setIsVisible(false); // Reset back to the original items setItemState({ items, isInSubSearch: false }); // Reset the input to its last saved value if (restoreIfNotSelected) setInputValue(lastValue.current); }; useKeybind("Escape", () => { if (document.activeElement === inputRef.current) reset(); }); const [itemState, setItemState] = useState<{ items: typeof items; isInSubSearch: boolean; closeButton?: boolean; Component?: (props: DropdownProps) => JSX.Element; }>({ items, isInSubSearch: false, }); const [selectedItems, setSelectedItems] = useState<{ pending: NormalizedItem[]; completed: NormalizedItem[]; }>({ pending: [], completed: PgCommon.toArray(initialSelectedItems ?? []).map(normalizeItem), }); const selectedItemRef = useRef<HTMLDivElement>(null); // Sync changes useEffect(() => { setItemState((itemState) => { if (itemState.isInSubSearch) return itemState; return { ...itemState, items }; }); }, [items]); useEffect(() => { _setSelectedItems?.(selectedItems.completed); }, [selectedItems, _setSelectedItems]); const normalizedItems = isVisible && itemState.items?.map(normalizeItem).map((item) => { const isSelected = selectedItems.completed.some((selectedItem) => { return selectedItem.label === item.label; }); return { ...item, isSelected }; }); const filteredItems = normalizedItems ? filter ? normalizedItems.filter((item) => filter({ input: props.value, item, items: normalizedItems, }) ) : normalizedItems.filter((item) => { if (item.onlyShowIfValid) { return props.validator?.(getItemValue(item)); } // Show all optinos if the input is valid if (props.validator?.(props.value)) return true; if (typeof item.matches === "function") { return item.matches(props.value); } const matches = item.matches ?? [item.label]; const lowerCaseValue = props.value.toLowerCase(); return matches.some((match) => { return typeof match === "string" ? match.toLowerCase().includes(lowerCaseValue) : match.test(lowerCaseValue); }); }) : null; const [loading, setLoading] = useState(false); const searchCommon = async (_item: Item) => { const item = normalizeItem(_item); let isInSubSearch = false; let isCompleted = false; if (item.items) { setLoading(true); try { setItemState({ items: await PgCommon.callIfNeeded(item.items), isInSubSearch: true, closeButton: item.closeButton, }); isInSubSearch = true; } catch (e: any) { console.log("Failed to get items:", e.message); return; } finally { setLoading(false); } setInputValue("", { focus: true }); } else if (item.DropdownComponent) { setItemState({ items: null, isInSubSearch: true, closeButton: item.closeButton, Component: item.DropdownComponent, }); isInSubSearch = true; } else { setInputValue(getItemValue(item)); isCompleted = true; } item.onSelect?.(item); if (isCompleted) { setSelectedItems((items) => { if (!items.pending.length) return { ...items, completed: [item] }; return { completed: [...items.pending, item], pending: [] }; }); onSearch?.({ input: props.value, item }); } else { setSelectedItems((items) => ({ ...items, pending: [item] })); } if (isInSubSearch) { setKeyboardSelectionIndex(null); selectedItemRef.current?.scrollIntoView({ block: "center" }); } else reset(); }; const searchTopResult = () => { if (filteredItems && keyboardSelectionIndex !== null) { const selectedItem = filteredItems.at(keyboardSelectionIndex); if (selectedItem) searchCommon(selectedItem); } else setIsVisible(true); }; useKeybind("Enter", { handle: () => { if (document.activeElement === inputRef.current) searchTopResult(); }, opts: { noPreventDefault: true }, }); // Keyboard navigation const [keyboardSelectionIndex, setKeyboardSelectionIndex] = useState< number | null >(null); // Handle the keyboard selection index useEffect(() => { if (!filteredItems) { // No `filteredItems` means dropdown is not visible so the keyboard // selection should not exist setKeyboardSelectionIndex(null); } else if (keyboardSelectionIndex === null) { // If the selection index was set to `null`, it means the dropdown has // just got mounted, therefore, either set the selection index to the // actual selected item, or if the selected item doesn't exist, select // the first item const index = filteredItems.findIndex((item) => item.isSelected); setKeyboardSelectionIndex(index === -1 ? 0 : index); } else { // If there is a selection, check whether the selected item exists in the // `filteredItems`, if it doesn't exist, select the first item const keyboardSelectedItem = filteredItems.at(keyboardSelectionIndex); if (!keyboardSelectedItem) setKeyboardSelectionIndex(0); } }, [filteredItems, keyboardSelectionIndex]); useKeybind( [ { keybind: "ArrowDown", handle: () => { if (!filteredItems?.length) { if (document.activeElement === inputRef.current) setIsVisible(true); return; } setKeyboardSelectionIndex((i) => { if (i === null || !filteredItems.length) return null; if (i === filteredItems.length - 1) return 0; return i + 1; }); }, }, { keybind: "ArrowUp", handle: () => { if (!filteredItems?.length) { if (document.activeElement === inputRef.current) setIsVisible(true); return; } setKeyboardSelectionIndex((i) => { if (i === null || !filteredItems.length) return null; if (i === 0) return filteredItems.length - 1; return i - 1; }); }, }, ], [filteredItems?.length] ); // Close on outside click useOnClickOutside(wrapperRef, reset, isVisible && !itemState.closeButton); return ( <Wrapper ref={wrapperRef}> <SearchInputWrapper width={searchButtonWidth}> <SearchInput ref={inputRef} position={searchButtonPosition} autoFocus={showSearchOnMount} onClick={(ev) => { onClick?.(ev); setIsVisible(true); }} onPaste={(ev) => { onPaste?.(ev); // Default to the pasted text if the label to select is not specified const clipboardText = ev.clipboardData.getData("text"); // Intentionally use `itemState.items` instead of `filteredItems` //`normalizedItems` because they could be in an invalid state // when the paste events, e.g. `normalizedItems` values only // exist when `isVisible` is truthy. const item = itemState.items?.find((item) => { const { label } = normalizeItem(item); return label === labelToSelectOnPaste || label === clipboardText; }); if (item) { // `item.value` can be an empty string because it's not updated as // soon as `onPaste` executes. if (typeof item === "object") item.value ||= clipboardText; // Include a timeout otherwise the pasted text is appended to the // value we set instead of overriding it setTimeout(() => searchCommon(item)); } }} {...props} /> {props.value && ( <InputCloseButton kind="no-border" onClick={() => { setInputValue("", { focus: true }); setSelectedItems({ completed: [], pending: [] }); setIsVisible(true); }} position={searchButtonPosition} > <Close /> </InputCloseButton> )} <SearchButton kind="icon" onClick={searchTopResult} position={searchButtonPosition} > <Search /> </SearchButton> </SearchInputWrapper> {(filteredItems || itemState.Component) && ( <DropdownWrapper isCustomComponent={!!itemState.Component}> { <SpinnerWithBg loading={loading}> {itemState.isInSubSearch && ( <SubSearchTopWrapper> <GoBackButton onClick={() => { setItemState({ items, isInSubSearch: false }); setSelectedItems((items) => ({ ...items, pending: [] })); inputRef.current?.focus(); }} kind="no-border" > <PointedArrow rotate="180deg" /> </GoBackButton> {itemState.closeButton && ( <SubSearchCloseButton kind="icon" onClick={reset}> <Close /> </SubSearchCloseButton> )} </SubSearchTopWrapper> )} {itemState.Component ? ( <itemState.Component search={searchCommon} /> ) : filteredItems?.length ? ( filteredItems.map((item, i) => ( <DropdownItem key={item.label} ref={item.isSelected ? selectedItemRef : null} onClick={() => searchCommon(item)} onMouseEnter={() => setKeyboardSelectionIndex(i)} isSelected={item.isSelected} isKeyboardSelected={keyboardSelectionIndex === i} > {item.element ?? item.label} </DropdownItem> )) ) : ( <NoMatch>No match</NoMatch> )} </SpinnerWithBg> } </DropdownWrapper> )} </Wrapper> ); }; const normalizeItem = (item: Item): NormalizedItem => { return typeof item === "object" ? item : { label: item }; }; type SearchButtonProps = NonNullable<SearchBarProps["searchButton"]>; type SearchButtonPosition = Pick<SearchButtonProps, "position">; type SearchButtonPositionWidth = Pick<SearchButtonProps, "width">; const Wrapper = styled.div``; const SearchInputWrapper = styled.div<SearchButtonPositionWidth>` display: flex; position: relative; --search-button-width: ${({ width }) => width}; `; const SearchInput = styled(Input)<SearchButtonPosition>` ${({ theme, position }) => css` padding: ${theme.components.input.padding}; ${position === "left" ? `padding-left: var(--search-button-width); padding-right: var(--search-button-width);` : `padding-right: calc(2 * var(--search-button-width))`} `} `; const InputCloseButton = styled(Button)<SearchButtonPosition>` position: absolute; top: 0; bottom: 0; margin: auto; padding: 0.25rem; right: ${({ position }) => { return position === "left" ? "0.25rem" : "calc(var(--search-button-width) + 0.25rem)"; }}; `; const SearchButton = styled(Button)<SearchButtonPosition>` position: absolute; width: var(--search-button-width); height: 100%; ${({ position }) => { const opposite = position === "left" ? "right" : "left"; return `${position}: 0; border-top-${opposite}-radius: 0; border-bottom-${opposite}-radius: 0;`; }} `; const DropdownWrapper = styled.div<{ isCustomComponent: boolean }>` ${({ isCustomComponent, theme }) => css` flex: 1; padding: 0.5rem 0; background: ${theme.components.input.bg}; border-radius: ${theme.default.borderRadius}; outline: 1px solid ${theme.colors.default.primary + theme.default.transparency.medium}; user-select: none; ${!isCustomComponent && ` max-height: 15rem; overflow: auto; ${PgTheme.getScrollbarCSS({ width: "0.25rem" })}; `}; `} `; const SubSearchTopWrapper = styled.div` ${({ theme }) => css` position: sticky; top: -0.5rem; padding: 0.25rem 0.5rem; display: flex; justify-content: space-between; align-items: center; background: ${theme.components.input.bg}; `} `; const GoBackButton = styled(Button)` & svg { width: 1.25rem; height: 1.25rem; } `; const SubSearchCloseButton = styled(Button)``; const DropdownItem = styled.div<{ isSelected: boolean; isKeyboardSelected: boolean; }>` ${({ isSelected, isKeyboardSelected, theme }) => css` padding: 0.5rem 1rem; color: ${theme.colors.default.textSecondary}; font-weight: bold; transition: all ${theme.default.transition.type} ${theme.default.transition.duration.short}; &:hover { background: ${theme.colors.state.hover.bg}; color: ${theme.colors.default.textPrimary}; cursor: pointer; } ${isKeyboardSelected && `background: ${theme.colors.state.hover.bg}; color: ${theme.colors.default.textPrimary}`}; ${isSelected && `color: ${theme.colors.default.primary} !important`}; `} `; const NoMatch = styled.div` padding: 0.5rem; text-align: center; `; export default SearchBar;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/SearchBar/index.ts
export { default } from "./SearchBar"; export type { DropdownProps as SearchBarDropdownProps, NormalizedItem as SearchBarItem, SearchBarProps, } from "./SearchBar";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tabs/Tabs.tsx
import { SetStateAction, useCallback } from "react"; import styled, { css } from "styled-components"; import Tab from "./Tab"; import Button from "../Button"; import Dnd from "../Dnd"; import Img from "../Img"; import { Id } from "../../constants"; import { PgExplorer, PgTheme, PgWallet } from "../../utils/pg"; import { useExplorer, useKeybind, useRenderOnChange, useWallet, } from "../../hooks"; export const Tabs = () => { // Without this, tabs flicker after reorder useRenderOnChange(PgExplorer.onDidSetTabs); const { explorer } = useExplorer(); const setItems = useCallback((action: SetStateAction<string[]>) => { const newTabs = typeof action === "function" ? action(PgExplorer.tabs as string[]) : action; PgExplorer.setTabs(newTabs); }, []); // Close the current tab with keybind useKeybind( "Alt+W", () => { if (PgExplorer.currentFilePath) { PgExplorer.closeFile(PgExplorer.currentFilePath); } }, [] ); if (!explorer.tabs.length) return null; return ( <Wrapper id={Id.TABS}> <TabsWrapper> <Dnd.Sortable items={explorer.tabs as string[]} setItems={setItems} Item={Tab} getItemProps={(path, index) => ({ path, index })} strategy="horizontal" /> </TabsWrapper> <Wallet /> </Wrapper> ); }; const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.tabs.default)}; `} `; const TabsWrapper = styled.div` display: flex; width: 100%; overflow-x: auto; overflow-y: hidden; ${PgTheme.getScrollbarCSS({ height: "0.25rem !important" })}; `; const Wallet = () => { const { wallet } = useWallet(); if (!wallet) return null; return ( <WalletWrapper> <Button onClick={() => (PgWallet.show = !PgWallet.show)} kind="icon" fontWeight="bold" > <Img src="/icons/sidebar/wallet.png" alt="Wallet" /> Wallet </Button> </WalletWrapper> ); }; const WalletWrapper = styled.div` ${({ theme }) => css` display: flex; align-items: center; & > button { background: ${theme.colors.default.bgPrimary}; border-top-left-radius: ${theme.default.borderRadius}; border-bottom-left-radius: ${theme.default.borderRadius}; border-top-right-radius: 0; border-bottom-right-radius: 0; & img { filter: invert(0.5); margin-right: 0.375rem; } &:hover img { filter: invert(${theme.isDark ? 1 : 0}); } } `} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tabs/Tab.tsx
import { ComponentPropsWithoutRef, forwardRef, MouseEvent, useCallback, useMemo, useRef, useState, } from "react"; import styled, { css } from "styled-components"; import Button from "../Button"; import LangIcon from "../LangIcon"; import Menu from "../Menu"; import { Close } from "../Icons"; import { PgExplorer, PgTheme } from "../../utils/pg"; import type { SortableItemProvidedProps } from "../Dnd/Sortable"; interface TabProps extends ComponentPropsWithoutRef<"div"> { path: string; index: number; } const Tab = forwardRef<HTMLDivElement, TabProps>( ({ path, index, ...props }, ref) => { const [isSelected, setIsSelected] = useState(false); const fileName = useMemo( () => PgExplorer.getItemNameFromPath(path), [path] ); const closeButtonRef = useRef<HTMLButtonElement>(null); const changeTab = useCallback( (ev: MouseEvent<HTMLDivElement>) => { if (!closeButtonRef.current?.contains(ev.target as Node)) { PgExplorer.openFile(path); } }, [path] ); const closeFile = useCallback(() => PgExplorer.closeFile(path), [path]); const closeOthers = useCallback(() => { PgExplorer.tabs .filter((tabPath) => tabPath !== path) .forEach((tabPath) => PgExplorer.closeFile(tabPath)); }, [path]); const closeToTheRight = useCallback(() => { const tabIndex = PgExplorer.tabs.findIndex((tabPath) => tabPath === path); PgExplorer.tabs .slice(tabIndex + 1) .forEach((tabPath) => PgExplorer.closeFile(tabPath)); }, [path]); const closeAll = useCallback(() => { // Clone the tabs before closing because `PgExplorer.closeFile` mutates // the existing tabs array [...PgExplorer.tabs].forEach((tabPath) => PgExplorer.closeFile(tabPath)); }, []); return ( <Menu.Context items={[ { name: "Close", onClick: closeFile, keybind: "ALT+W", }, { name: "Close Others", onClick: closeOthers, showCondition: PgExplorer.tabs.length > 1, }, { name: "Close To The Right", onClick: closeToTheRight, showCondition: PgExplorer.tabs.length - 1 > index, }, { name: "Close All", onClick: closeAll, }, ]} onShow={() => setIsSelected(true)} onHide={() => setIsSelected(false)} > <Wrapper isSelected={isSelected} isCurrent={path === PgExplorer.currentFilePath} onClick={changeTab} title={path} ref={ref} {...(props as SortableItemProvidedProps)} > <LangIcon path={path} /> <Name>{fileName}</Name> <Button ref={closeButtonRef} kind="icon" onClick={closeFile} title="Close (Alt+W)" > <Close /> </Button> </Wrapper> </Menu.Context> ); } ); const Wrapper = styled.div<{ isSelected: boolean; isCurrent: boolean; isDragging: boolean; isDragOverlay: boolean; }>` ${({ theme, isSelected, isCurrent, isDragging, isDragOverlay }) => css` & button { ${!isCurrent && "opacity: 0;"} margin: 0 0.25rem 0 0.5rem; & svg { width: 0.875rem; height: 0.875rem; } } &:hover button { opacity: 1; } ${PgTheme.convertToCSS(theme.components.tabs.tab.default)}; ${isSelected && PgTheme.convertToCSS(theme.components.tabs.tab.selected)}; ${isCurrent && PgTheme.convertToCSS(theme.components.tabs.tab.current)}; ${isDragging && PgTheme.convertToCSS(theme.components.tabs.tab.drag)}; ${isDragOverlay && PgTheme.convertToCSS(theme.components.tabs.tab.dragOverlay)}; `} `; const Name = styled.span` margin-left: 0.375rem; white-space: nowrap; `; export default Tab;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tabs/index.ts
export { Tabs } from "./Tabs";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/CopyButton/CopyButton.tsx
import { FC } from "react"; import styled, { css } from "styled-components"; import Button from "../Button"; import Tooltip from "../Tooltip"; import { Copy } from "../Icons"; import { useCopy } from "../../hooks"; interface CopyButtonProps { copyText: string; } const CopyButton: FC<CopyButtonProps> = ({ copyText }) => { const [copied, setCopied] = useCopy(copyText); return ( <Tooltip element={ <TooltipElement copied={copied}> {copied ? "Copied" : "Copy"} </TooltipElement> } > <StyledButton onClick={setCopied} kind="icon" copied={copied}> <Copy /> </StyledButton> </Tooltip> ); }; const StyledButton = styled(Button)<{ copied: boolean }>` ${({ theme, copied }) => css` ${copied && `color: ${theme.colors.state.success.color}`}; &:hover { background: transparent; ${copied && `color: ${theme.colors.state.success.color}`}; } `}; `; const TooltipElement = styled.span<{ copied: boolean }>` ${({ copied, theme }) => css` ${copied && `color: ${theme.colors.state.success.color}`}; `} `; export default CopyButton;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/CopyButton/index.ts
export { default } from "./CopyButton";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tooltip/Tooltip.tsx
import { FC, ReactNode } from "react"; import styled, { css } from "styled-components"; import Popover, { PopoverProps } from "../Popover"; import { QuestionMarkOutlined } from "../Icons"; import { PgTheme } from "../../utils/pg"; export type TooltipProps = Omit<PopoverProps, "showOnHover" | "popEl"> & { /** Tooltip element to show on hover */ element: ReactNode; /** Whether to show it as a help tooltip */ help?: boolean; }; const Tooltip: FC<TooltipProps> = ({ children, element, help, ...props }) => ( <StyledPopover {...props} popEl={element} showOnHover> {help ? <StyledQuestionMarkOutlined color="textSecondary" /> : children} </StyledPopover> ); const StyledPopover = styled(Popover)<Pick<TooltipProps, "bgSecondary">>` ${({ bgSecondary, theme }) => css` ${PgTheme.convertToCSS(theme.components.tooltip)}; background: ${bgSecondary ? theme.components.tooltip.bgSecondary : theme.components.tooltip.bg}; `} `; const StyledQuestionMarkOutlined = styled(QuestionMarkOutlined)` &:hover { cursor: help; color: ${({ theme }) => theme.colors.default.textPrimary}; } `; export default Tooltip;
0