/// /// /// /// /// /// /// /// /// declare namespace pxt { function aiTrackEvent(id: string, data?: any, measures?: any): void; function aiTrackException(err: any, kind: string, props: any): void; function setInteractiveConsent(enabled: boolean): void; } declare namespace pxt.analytics { enum ConsoleTickOptions { Off = 0, Short = 1, Verbose = 2 } let consoleTicks: ConsoleTickOptions; function addDefaultProperties(props: Map): void; function enable(lang: string): void; function trackPerformanceReport(): void; } declare namespace pxt { let appTarget: TargetBundle; let appTargetVariant: string; let hwVariant: string; let hwName: string; } declare namespace pxt.AudioContextManager { function mute(mute: boolean): void; function stop(): void; function frequency(): number; function tone(frequency: number): void; } declare namespace pxt.auth { type ApiResult = { resp: T; statusCode: number; success: boolean; err: any; }; type UserProfile = { id?: string; idp?: { provider?: pxt.IdentityProviderId; username?: string; displayName?: string; picture?: { mimeType?: string; width?: number; height?: number; encoded?: string; dataUrl?: string; }; pictureUrl?: string; }; }; type UserSkillmapState = { mapProgress: any; completedTags: any; }; type UserBadgeState = { badges: Badge[]; }; /** * Mapping of target id to preferred color theme id. */ type ColorThemeIdsState = { [targetId: string]: string; }; type SetPrefResult = { success: boolean; res: UserPreferences; }; /** * User preference state that should be synced with the cloud. */ type UserPreferences = { language?: string; highContrast?: boolean; accessibleBlocks?: boolean; colorThemeIds?: ColorThemeIdsState; reader?: string; skillmap?: UserSkillmapState; badges?: UserBadgeState; email?: boolean; }; const DEFAULT_USER_PREFERENCES: () => UserPreferences; /** * Cloud-synced user state. */ type UserState = { profile?: UserProfile; preferences?: UserPreferences; }; function client(): AuthClient; let cachedHasAuthToken: boolean; function getAuthTokenAsync(): Promise; function hasAuthTokenAsync(): Promise; let cachedUserState: Readonly; function getUserStateAsync(): Promise>; function getAuthHeadersAsync(authToken?: string): Promise>; abstract class AuthClient { constructor(); initAsync(): Promise; protected abstract onSignedIn(): Promise; protected abstract onSignedOut(): Promise; protected abstract onSignInFailed(): Promise; protected abstract onUserProfileChanged(): Promise; protected abstract onUserPreferencesChanged(diff: ts.pxtc.jsonPatch.PatchOperation[]): Promise; protected abstract onProfileDeleted(userId: string): Promise; protected abstract onApiError(err: any): Promise; protected abstract onStateCleared(): Promise; /** * Starts the process of authenticating the user against the given identity * provider. Upon success the backend will write an http-only session cookie * to the response, containing the authorization token. This cookie is not * accessible in code, but will be included in all subsequent http requests. * @param idp The id of the identity provider. * @param persistent Whether or not to remember this login across sessions. * @param callbackState The URL hash and params to return to after the auth * flow completes. */ loginAsync(idp: pxt.IdentityProviderId, persistent: boolean, callbackState?: CallbackState): Promise; /** * Sign out the user and clear the auth token cookie. */ logoutAsync(continuationHash?: string): Promise; /** * Sign out the user and clear the auth token cookie. */ static staticLogoutAsync(continuationHash?: string): Promise; deleteProfileAsync(): Promise; private initialUserPreferences_; initialUserPreferencesAsync(): Promise; userProfileAsync(): Promise; userPreferencesAsync(): Promise; private initialAuthCheck_; /** * Checks to see if we're already logged in by trying to fetch user info from * the backend. If we have a valid auth token cookie, it will succeed. */ authCheckAsync(): Promise; loggedInAsync(): Promise; updateUserProfileAsync(opts: { username?: string; avatarUrl?: string; }): Promise; private patchQueue; patchUserPreferencesAsync(patchOps: ts.pxtc.jsonPatch.PatchOperation | ts.pxtc.jsonPatch.PatchOperation[], opts?: { immediate?: boolean; filter?: (op: ts.pxtc.jsonPatch.PatchOperation) => boolean; }): Promise; private hasUserIdAsync; private fetchUserAsync; private setUserProfileAsync; private setUserPreferencesAsync; private fetchUserPreferencesAsync; /** * Updates user profile state and writes it to local storage. */ private transformUserProfileAsync; /** * Updates user preference state and writes it to local storage. */ protected transformUserPreferencesAsync(preferences: UserPreferences): Promise; /** * Clear local auth state then call the onStateCleared callback. */ private clearAuthStateAsync; apiAsync(url: string, data?: any, method?: string, authToken?: string): Promise>; static staticApiAsync(url: string, data?: any, method?: string, authToken?: string): Promise>; } type CallbackState = { hash?: string; params?: pxt.Map; }; function loginCallbackAsync(qs: pxt.Map): Promise; function identityProviders(): pxt.AppCloudProvider[]; function identityProvider(id: pxt.IdentityProviderId): pxt.AppCloudProvider; function hasIdentity(): boolean; function enableAuth(enabled?: boolean): void; function userName(user: pxt.auth.UserProfile): string; function identityProviderId(user: pxt.auth.UserProfile): pxt.IdentityProviderId | undefined; function firstName(user: pxt.auth.UserProfile): string; function userInitials(user: pxt.auth.UserProfile): string; function generateUserProfilePicDataUrl(profile: pxt.auth.UserProfile): void; /** * Checks only the ID and sourceURL */ function badgeEquals(badgeA: pxt.auth.Badge, badgeB: pxt.auth.Badge): boolean; function hasBadge(preferences: pxt.auth.UserBadgeState, badge: pxt.auth.Badge): boolean; } declare namespace pxt { interface TelemetryEventOptions { interactiveConsent: boolean; } /** * Track an event. */ let tickEvent: (id: string, data?: Map, opts?: TelemetryEventOptions) => void; } declare namespace pxt { interface Logger { info(...args: any[]): void; log(...args: any[]): void; debug(...args: any[]): void; error(...args: any[]): void; warn(...args: any[]): void; setLogLevel(level: LogLevel): void; getLogLevel(): LogLevel; } enum LogLevel { Debug = 0, Info = 1, Log = 1, Warning = 2, Error = 3 } class ConsoleLogger implements Logger { protected logLevel: LogLevel; constructor(); setLogLevel(level: LogLevel): void; getLogLevel(): LogLevel; info(...args: any[]): void; log(...args: any[]): void; debug(...args: any[]): void; error(...args: any[]): void; warn(...args: any[]): void; protected shouldLog(level: LogLevel): boolean; } function info(...args: any[]): void; function log(...args: any[]): void; function debug(...args: any[]): void; function error(...args: any[]): void; function warn(...args: any[]): void; function setLogger(impl: Logger): void; function setLogLevel(level: LogLevel): void; } declare namespace ts.pxtc { let __dummy: number; } import pxtc = ts.pxtc; declare namespace ts.pxtc.Util { function assert(cond: boolean, msg?: string): void; function flatClone(obj: T): T; function clone(v: T): T; function htmlEscape(_input: string): string; function htmlUnescape(_input: string): string; function jsStringQuote(s: string): string; function jsStringLiteral(s: string): string; function initials(username: string): string; function enableLiveLocalizationUpdates(): void; function liveLocalizationEnabled(): boolean; /** * Returns the current user language, prepended by "live-" if in live mode */ function localeInfo(): string; /** * Returns current user language iSO-code. Default is `en`. */ function userLanguage(): string; function normalizeLanguageCode(code: string): string[]; function setUserLanguage(localizeLang: string): void; function isUserLanguageRtl(): boolean; const TRANSLATION_LOCALE = "pxt"; function isTranslationMode(): boolean; function _localize(s: string): string; function getLocalizedStrings(): pxt.Map; function setLocalizedStrings(strs: pxt.Map): void; function translationsCache(): pxt.Map>; function fmt_va(f: string, args: any[]): string; function fmt(f: string, ...args: any[]): string; function dumpLocStats(): void; function lf_va(format: string, args: any[]): string; function lf(format: string, ...args: any[]): string; /** * Similar to lf but the string do not get extracted into the loc file. */ function rlf(format: string, ...args: any[]): string; /** * Same as lf except the strings are not replaced in translation mode. This is used * exclusively for blockly JSON block definitions as the crowdin in-context translation * script doesn't handle the SVG text fields. Instead, they are translated via a context * menu item on the block. */ function blf(format: string): string; function lookup(m: pxt.Map, key: string): T; function isoTime(time: number): string; function userError(msg: string): never; function deq(a: any, b: any): string; function deepEqual(a: any, b: any): boolean; } declare const lf: typeof pxtc.U.lf; declare namespace ts.pxtc { /** * atob replacement * @param s */ let decodeBase64: (s: string) => string; /** * bota replacement * @param s */ let encodeBase64: (s: string) => string; } declare namespace ts.pxtc.Util { export class CancellationToken { private pending; private cancelled; private resolve; private deferred; private progressHandler; startOperation(): void; isRunning(): boolean; onProgress(progressHandler: (completed: number, total: number) => void): void; reportProgress(completed: number, total: number): void; cancel(): void; cancelAsync(): Promise; isCancelled(): boolean; throwIfCancelled(): void; resolveCancel(): void; } export function codalHash16(s: string): number; export function bufferSerial(buffers: pxt.Map, data?: string, source?: string, maxBufLen?: number): void; export function blobReadAsDataURL(blob: Blob): Promise; export function fileReadAsBufferAsync(f: File): Promise; export function fileReadAsTextAsync(f: File): Promise; export function sanitizeFileName(name: string): string; export function repeatMap(n: number, fn: (index: number) => T): T[]; export function listsEqual(a: T[], b: T[]): boolean; export function oops(msg?: string): Error; export function reversed(arr: T[]): T[]; export function arrayEquals(a: U[], b: U[], compare?: (c: U, d: U) => boolean): boolean; export function iterMap(m: pxt.Map, f: (k: string, v: T) => void): void; export function mapMap(m: pxt.Map, f: (k: string, v: T) => S): pxt.Map; export function values(m: pxt.Map): T[]; export function pushRange(trg: T[], src: ArrayLike): void; export function concatArrayLike(arrays: ArrayLike>): T[]; export function concat(arrays: T[][]): T[]; export function memcpy(trg: Uint8Array, trgOff: number, src: ArrayLike, srcOff?: number, len?: number): void; export function uint8ArrayConcat(chunks: Uint8Array[]): Uint8Array; export function jsonTryParse(s: string): any; export function jsonMergeFrom(trg: any, src: any): void; export function jsonCopyFrom(trg: T, src: T): void; export function jsonFlatten(v: any): pxt.Map; export function jsonUnFlatten(v: pxt.Map): any; export function strcmp(a: string, b: string): 0 | 1 | -1; export function stringMapEq(a: pxt.Map, b: pxt.Map): boolean; export function endsWith(str: string, suffix: string): boolean; export function startsWith(str: string, prefix: string): boolean; export function contains(str: string, contains: string): boolean; export function replaceAll(str: string, old: string, new_: string): string; export function snakify(s: string): string; export function sortObjectFields(o: T): T; export function chopArray(arr: T[], chunkSize: number): T[][]; export function unique(arr: T[], f: (t: T) => string): T[]; export function groupBy(arr: T[], f: (t: T) => string): pxt.Map; export function toDictionary(arr: T[], f: (t: T) => string): pxt.Map; export function toSet(arr: T[], f: (t: T) => string): pxt.Map; export function deepCopy(src: any): any; export interface ArrayLike { [index: number]: T; length: number; } export function toArray(a: ArrayLike | ReadonlyArray): T[]; export function indexOfMatching(arr: T[], f: (t: T) => boolean): number; export function nextTick(f: () => void): void; export function delay(duration: number, value: T | Promise): Promise; export function delay(duration: number): Promise; export function promiseMapAll(values: T[], mapper: (obj: T) => Promise): Promise; export function promiseMapAllSeries(values: T[], mapper: (obj: T) => Promise): Promise; export function promisePoolAsync(maxConcurrent: number, inputValues: T[], handler: (input: T) => Promise): Promise; export function memoizeString(createNew: (id: string) => T): (id: string) => T; export function promiseTimeout(ms: number, promise: T | Promise, msg?: string): Promise; export interface DeferredPromise { resolve: (value: T) => void; reject: (reason: any) => void; promise: Promise; } export function defer(): DeferredPromise; export function memoize(getId: (v: S) => string, createNew: (v: S) => T): (id: S) => T; export function debounce(func: (...args: any[]) => any, wait: number, immediate?: boolean): any; export class AdaptiveDebouncer { func: () => void; minDelay: number; maxDelay: number; slowdownFactor: number; private lastPoke; private recentGaps; private timeout; private wrapped; constructor(func: () => void, minDelay?: number, maxDelay?: number, slowdownFactor?: number); poke(): void; trigger(): void; } export function throttle(func: (...args: any[]) => any, wait: number, immediate?: boolean): any; export function randomPermute(arr: T[]): void; export function randomPick(arr: T[]): T; export function timeSince(time: number): string; export function unicodeToChar(text: string): string; export function escapeForRegex(str: string): string; export function stripUrlProtocol(str: string): string; export function normalizePath(path: string): string; export function pathJoin(a: string, b: string): string; export let isNodeJS: boolean; export interface HttpRequestOptions { url: string; method?: string; data?: any; headers?: pxt.Map; allowHttpErrors?: boolean; allowGzipPost?: boolean; responseArrayBuffer?: boolean; forceLiveEndpoint?: boolean; successCodes?: number[]; withCredentials?: boolean; } export interface HttpResponse { statusCode: number; headers: pxt.Map; buffer?: any; text?: string; json?: any; } export function requestAsync(options: HttpRequestOptions): Promise; export function httpGetTextAsync(url: string): Promise; export function httpGetJsonAsync(url: string): Promise; export function httpPostJsonAsync(url: string, data: any): Promise; export function stringToUint8Array(input: string): Uint8Array; export function uint8ArrayToString(input: ArrayLike): string; export function fromUTF8(binstr: string): string; export function toUTF8(str: string, cesu8?: boolean): string; export function toHex(bytes: ArrayLike): string; export function fromHex(hex: string): Uint8Array; export class PromiseQueue { promises: pxt.Map<(() => Promise)[]>; enqueue(id: string, f: () => Promise): Promise; } export class PromiseBuffer { private waiting; private available; drain(): void; pushError(v: Error): void; push(v: T): void; shiftAsync(timeout?: number): Promise; } export function now(): number; export function nowSeconds(): number; export function timeout(ms: number): Promise; /** * Utility function to run an action with exponential backoff until a condition is met or a timeout occurs. * @param action - The main action to run. * @param isComplete - A function that checks if the result of the action indicates completion. * @param initialDelayMs - The starting delay to use between the initial attempt and any retry. * @param maxDelayMs - The maximum delay between retries. * @param timeoutMs - The total timeout for the operation. * @param timeoutErrorMsg - The error message to throw if the operation times out. * @param backoffFactor - The factor by which to increase the delay after each retry (default is 1.5). */ export function runWithBackoffAsync(action: () => Promise, isComplete: (result: T) => boolean, initialDelayMs: number, maxDelayMs: number, timeoutMs: number, timeoutErrorMsg: string, backoffFactor?: number): Promise; export let cpuUs: () => number; export function getMime(filename: string): "text/plain" | "text/html" | "text/css" | "application/javascript" | "image/jpeg" | "image/png" | "image/x-icon" | "text/cache-manifest" | "application/manifest+json" | "application/json" | "image/svg+xml" | "application/vnd.ms-fontobject" | "font/ttf" | "application/font-woff" | "application/font-woff2" | "text/markdown" | "application/xml" | "audio/m4a" | "audio/mp3" | "application/wasm" | "application/octet-stream"; export function randomUint32(): number; export function guidGen(): string; export function downloadLiveTranslationsAsync(lang: string, filename: string, etag?: string): Promise>; export const pxtLangCookieId = "PXT_LANG"; export const langCookieExpirationDays = 30; export interface Language { englishName: string; localizedName: string; } export const allLanguages: pxt.Map; export function isLocaleEnabled(code: string): boolean; interface LocalizationUpdateOptions { targetId: string; baseUrl: string; code: string; force?: boolean; } export function updateLocalizationAsync(opts: LocalizationUpdateOptions): Promise; export enum TranslationsKind { Editor = 0, Sim = 1, Apis = 2, SkillMap = 3 } export function downloadTranslationsAsync(targetId: string, baseUrl: string, code: string, live: boolean, translationKind?: TranslationsKind): Promise>; export let httpRequestCoreAsync: (options: HttpRequestOptions) => Promise; export let sha256: (hashData: string) => string; export let getRandomBuf: (buf: Uint8Array) => void; export function capitalize(n: string): string; export function uncapitalize(n: string): string; export function camelCaseToLowercaseWithSpaces(n: string): string; export function snakeCaseToLowercaseWithSpaces(n: string): string; export function range(len: number): number[]; export function multipartPostAsync(uri: string, data?: any, filename?: string, filecontents?: string): Promise; export function toDataUri(data: string, mimetype?: string): string; export const imageMagic = 1496611453; export const imageHeaderSize = 36; export function encodeBlobAsync(canvas: HTMLCanvasElement, blob: Uint8Array): HTMLCanvasElement; export function decodeBlobAsync(dataURL: string): Promise; export function parseQueryString(qs: string): pxt.Map; export function stringifyQueryString(url: string, qs: any): string; export function cloneTargetBundle(target: pxt.TargetBundle): pxt.TargetBundle; export function cloneApis(byQName: pxt.Map): pxt.Map; export function cloneSymbolInfo(sym: pxtc.SymbolInfo): pxtc.SymbolInfo; export function toUTF8Array(s: string): Uint8Array; export function fromUTF8Array(s: Uint8Array): string; export function getHomeUrl(): string; export function isExperienceSupported(experienceId: string): boolean; export function ocvEnabled(): string; export function bresenhamLine(x0: number, y0: number, x1: number, y1: number, handler: (x: number, y: number) => void): void; /** * Check if the specified feature is enabled for the user (based on pxtarget configuration and region). */ export function isFeatureEnabled(featureKey: string): boolean; /** * Remove potentially sensitive info from the given data to avoid logging it. * Currently only supports string data. */ export function cleanData(data: string): string; export function cleanData(data: pxt.Map): pxt.Map; export {}; } declare namespace ts.pxtc.BrowserImpl { function sha256buffer(buf: Uint8Array): string; function sha256string(s: string): string; } declare namespace ts.pxtc.jsonPatch { type AddOperation = { op: 'add'; path: (string | number)[]; value: string | number | boolean | object; }; type ReplaceOperation = { op: 'replace'; path: (string | number)[]; value: string | number | boolean | object; }; type RemoveOperation = { op: 'remove'; path: (string | number)[]; }; type PatchOperation = AddOperation | ReplaceOperation | RemoveOperation; /** * Returns the diff of two objects as a set of change operations, following the * "JSON Patch" format: https://datatracker.ietf.org/doc/html/rfc6902 (with a * small difference to the way paths are encoded). */ function diff(oldObj: any, newObj: any): PatchOperation[]; /** * Applies a set of JSON Patch operations to the object. */ function patchInPlace(obj: any, ops: PatchOperation[]): void; function opsAreEqual(a: PatchOperation, b: PatchOperation): boolean; } declare namespace ts.pxtc.jsonPatch.tests { function diffTests(): void; function patchTests(): void; } declare namespace pxt.perf { type EventSource = { subscribe(listener: (ev: T) => void): () => void; }; function isEnabled(): boolean; let perfReportLogged: boolean; function report(): { milestones: { [index: string]: number; }; durations: { [index: string]: number; }; } | undefined; function recordMilestone(msg: string, params?: Map): void; function measureStart(name: string): void; function measureEnd(name: string, params?: Map): void; let measurementThresholdMs: number; const stats: { milestones: EventSource<{ milestone: string; time: number; params?: Map; }>; durations: EventSource<{ name: string; start: number; duration: number; params?: Map; }>; }; } declare namespace pxt { export import U = pxtc.Util; export import Util = pxtc.Util; interface TCPIO { onData: (v: Uint8Array) => void; onError: (e: Error) => void; connectAsync(): Promise; sendPacketAsync(pkt: Uint8Array): Promise; error(msg: string): any; disconnectAsync(): Promise; } let mkTCPSocket: (host: string, port: number) => TCPIO; function setAppTarget(trg: TargetBundle): void; function setBundledApiInfo(inf: Map): void; function getBundledApiInfo(): Map; function savedAppTheme(): AppTheme; function setCompileSwitch(name: string, value: boolean): void; function setCompileSwitches(names: string): void; function bundledSvg(id: string): string; function replaceStringsInJsonBlob(blobPart: any, matcher: RegExp, matchHandler: (matchingString: string) => string): any; function reloadAppTargetVariant(temporary?: boolean): void; function setAppTargetVariant(variant: string, opts?: { force?: boolean; temporary?: boolean; }): void; let onAppTargetChanged: () => void; function setHwVariant(variant: string, name?: string): void; function hasHwVariants(): boolean; function getHwVariants(): PackageConfig[]; function getActiveHwVariant(): string; interface PxtOptions { debug?: boolean; light?: boolean; wsPort?: number; } let options: PxtOptions; let reportException: (err: any, data?: Map) => void; let reportError: (cat: string, msg: string, data?: Map) => void; interface WebConfig { relprefix: string; workerjs: string; monacoworkerjs: string; gifworkerjs: string; serviceworkerjs: string; typeScriptWorkerJs: string; pxtVersion: string; pxtRelId: string; pxtCdnUrl: string; commitCdnUrl: string; blobCdnUrl: string; cdnUrl: string; targetUrl: string; targetVersion: string; targetRelId: string; targetId: string; simUrl: string; simserviceworkerUrl: string; simworkerconfigUrl: string; partsUrl?: string; runUrl?: string; docsUrl?: string; multiUrl?: string; asseteditorUrl?: string; skillmapUrl?: string; authcodeUrl?: string; multiplayerUrl?: string; kioskUrl?: string; teachertoolUrl?: string; isStatic?: boolean; verprefix?: string; ocv?: OcvConfig; } interface OcvConfig { appId: number; iframeEndpoint: string; } function localWebConfig(): WebConfig; let webConfig: WebConfig; function getOnlineCdnUrl(): string; function setupWebConfig(cfg: WebConfig): void; interface Host { readFile(pkg: Package, filename: string, skipAdditionalFiles?: boolean): string; writeFile(pkg: Package, filename: string, contents: string, force?: boolean): void; downloadPackageAsync(pkg: Package, deps?: string[]): Promise; getHexInfoAsync(extInfo: pxtc.ExtensionInfo): Promise; cacheStoreAsync(id: string, val: string): Promise; cacheGetAsync(id: string): Promise; } interface FsFile { name: string; mtime: number; content?: string; prevContent?: string; } interface FsPkg { path: string; config: pxt.PackageConfig; header: pxt.workspace.Header; files: FsFile[]; icon?: string; isDeleted?: boolean; } interface FsPkgs { pkgs: FsPkg[]; } interface ICompilationOptions { } function getEmbeddedScript(id: string): Map; function targetConfigAsync(): Promise; function packagesConfigAsync(): Promise; const CONFIG_NAME = "pxt.json"; const SIMSTATE_JSON = ".simstate.json"; const SERIAL_EDITOR_FILE = "serial.txt"; const README_FILE = "README.md"; const GITIGNORE_FILE = ".gitignore"; const ASSETS_FILE = "assets.json"; const CLOUD_ID = "pxt/"; const BLOCKS_PROJECT_NAME = "blocksprj"; const JAVASCRIPT_PROJECT_NAME = "tsprj"; const PYTHON_PROJECT_NAME = "pyprj"; const MAIN_BLOCKS = "main.blocks"; const MAIN_TS = "main.ts"; const MAIN_PY = "main.py"; const DEFAULT_GROUP_NAME = "other"; const TILEMAP_CODE = "tilemap.g.ts"; const TILEMAP_JRES = "tilemap.g.jres"; const IMAGES_CODE = "images.g.ts"; const IMAGES_JRES = "images.g.jres"; const TUTORIAL_CODE_START = "_onCodeStart.ts"; const TUTORIAL_CODE_STOP = "_onCodeStop.ts"; const TUTORIAL_INFO_FILE = "tutorial-info-cache.json"; const TUTORIAL_CUSTOM_TS = "tutorial.custom.ts"; const BREAKPOINT_TABLET = 991; const PALETTES_FILE = "_palettes.json"; const HISTORY_FILE = "_history"; const MAX_DESCRIPTION_LENGTH = 5000; function outputName(trg?: pxtc.CompileTarget): "binary.uf2" | "binary.bin" | "binary.pxt64" | "binary.elf" | "binary.hex"; function isOutputText(trg?: pxtc.CompileTarget): boolean; } declare namespace pxt.blocks { let showBlockIdInTooltip: boolean; interface PxtBlockly { } interface BlocklyModule { } let requirePxtBlockly: () => PxtBlockly; let requireBlockly: () => BlocklyModule; let registerFieldEditor: (selector: string, proto: any, validator?: any) => void; const MATH_FUNCTIONS: { unary: string[]; binary: string[]; infix: string[]; }; const ROUNDING_FUNCTIONS: string[]; interface BlockParameter { actualName: string; type?: string; definitionName: string; definitionIndex?: number; shadowBlockId?: string; defaultValue?: string; isOptional?: boolean; fieldEditor?: string; fieldOptions?: Map; shadowOptions?: Map; range?: { min: number; max: number; }; } interface BlockCompileInfo { parameters: ReadonlyArray; actualNameToParam: Map; definitionNameToParam: Map; handlerArgs?: HandlerArg[]; thisParameter?: BlockParameter; } interface HandlerArg { name: string; type: string; inBlockDef: boolean; localizationKey: string; } const builtinFunctionInfo: pxt.Map<{ params: string[]; blockId: string; }>; function normalizeBlock(b: string, err?: (msg: string) => void): string; function compileInfo(fn: pxtc.SymbolInfo): BlockCompileInfo; function hasHandler(fn: pxtc.SymbolInfo): boolean; function getHelpUrl(fn: pxtc.SymbolInfo): string; /** * Returns which Blockly block type to use for an argument reporter based * on the specified TypeScript type. * @param varType The variable's TypeScript type * @return The Blockly block type of the reporter to be used */ function reporterTypeForArgType(varType: string): string; function defaultIconForArgType(typeName?: string): "calculator" | "text width" | "random" | "list" | "align justify"; interface FieldDescription { n: string; pre?: string; p?: string; ni: number; } function parseFields(b: string): FieldDescription[]; interface BlockDefinition { name: string; category: string; url: string; tooltip?: string | Map; operators?: Map; block?: Map; blockTextSearch?: string; tooltipSearch?: string; translationIds?: string[]; } function blockDefinitions(): Map; function getBlockDefinition(blockId: string): BlockDefinition; } declare namespace pxt.BrowserUtils { export function isDocumentVisible(): boolean; export function isIFrame(): boolean; export function hasNavigator(): boolean; export function hasWindow(): boolean; export function isWindows(): boolean; export function isWindows10(): boolean; export function isMobile(): boolean; export function isIOS(): boolean; export function isAndroid(): boolean; export function isMac(): boolean; export function isLinux(): boolean; export function isARM(): boolean; export function isEdge(): boolean; export function isChromiumEdge(): boolean; export function isIE(): boolean; export function isChrome(): boolean; export function isSafari(): boolean; export function isFirefox(): boolean; export function isOpera(): boolean; export function isMidori(): boolean; export function isEpiphany(): boolean; export function isTouchEnabled(): boolean; export function isPxtElectron(): boolean; export function isIpcRenderer(): boolean; export function isElectron(): boolean; export let isWinRT: () => boolean; export function isLocalHost(ignoreFlags?: boolean): boolean; export function isLocalHostDev(): boolean; export function isSkillmapEditor(): boolean; export function isTabletSize(): boolean; export function isComputerSize(): boolean; export function isInGame(): boolean; export function hasFileAccess(): boolean; export function noSharedLocalStorage(): boolean; export function useOldTutorialLayout(): boolean; export function hasPointerEvents(): boolean; export function os(): string; export function browser(): string; export function browserVersion(): string; export function isBrowserSupported(): boolean; export function devicePixelRatio(): number; export function browserDownloadBinText(text: string, name: string, opt?: BrowserDownloadOptions): string; export function browserDownloadText(text: string, name: string, opt?: BrowserDownloadOptions): string; export function isBrowserDownloadInSameWindow(): boolean; export function isBrowserDownloadWithinUserContext(): boolean; export function browserDownloadDataUri(uri: string, name: string, userContextWindow?: Window): void; export function browserDownloadUInt8Array(buf: Uint8Array, name: string, opt?: BrowserDownloadOptions): string; export function toDownloadDataUri(b64: string, contentType: string): string; export interface BrowserDownloadOptions { contentType?: string; userContextWindow?: Window; onError?: (err: any) => void; maintainObjectURL?: boolean; } export function browserDownloadBase64(b64: string, name: string, opt?: BrowserDownloadOptions): string; export function loadImageAsync(data: string): Promise; export function loadCanvasAsync(url: string): Promise; export function scaleImageData(img: ImageData, scale: number): ImageData; export function imageDataToPNG(img: ImageData, scale?: number): string; export function encodeToPngAsync(uri: string, options?: { width?: number; height?: number; pixelDensity?: number; maxSize?: number; text?: string; }): Promise; export function resolveCdnUrl(path: string): string; export function loadStyleAsync(path: string, rtl?: boolean): Promise; export function loadScriptAsync(path: string): Promise; export function loadAjaxAsync(url: string): Promise; export function loadBlocklyAsync(): Promise; export function patchCdn(url: string): string; export function initTheme(): void; /** * Utility method to change the hash. * Pass keepHistory to retain an entry of the change in the browser history. */ export function changeHash(hash: string, keepHistory?: boolean): void; /** * Simple utility method to join urls. */ export function urlJoin(urlPath1: string, urlPath2: string): string; /** * Simple utility method to join multiple urls. */ export function joinURLs(...parts: string[]): string; export function storageEstimateAsync(): Promise<{ quota?: number; usage?: number; }>; export const scheduleStorageCleanup: any; export function stressTranslationsAsync(): Promise; export interface ITranslationDbEntry { id?: string; etag: string; time: number; strings?: pxt.Map; md?: string; } export interface ITranslationDb { getAsync(lang: string, filename: string): Promise; setAsync(lang: string, filename: string, etag: string, strings?: pxt.Map, md?: string): Promise; clearAsync(): Promise; } export type IDBUpgradeHandler = (ev: IDBVersionChangeEvent, request: IDBRequest) => void; export class IDBWrapper { private name; private version; private upgradeHandler?; private quotaExceededHandler?; private skipErrorLog; private _db; constructor(name: string, version: number, upgradeHandler?: IDBUpgradeHandler, quotaExceededHandler?: () => void, skipErrorLog?: boolean); private throwIfNotOpened; private errorHandler; private getObjectStore; static deleteDatabaseAsync(name: string): Promise; openAsync(): Promise; getAsync(storeName: string, id: string): Promise; getAllAsync(storeName: string): Promise; setAsync(storeName: string, data: any): Promise; deleteAsync(storeName: string, id: string): Promise; deleteAllAsync(storeName: string): Promise; getObjectStoreWrapper(storeName: string): IDBObjectStoreWrapper; } export class IDBObjectStoreWrapper { protected db: IDBWrapper; protected storeName: string; constructor(db: IDBWrapper, storeName: string); getAsync(id: string): Promise; getAllAsync(): Promise; setAsync(data: T): Promise; deleteAsync(id: string): Promise; deleteAllAsync(): Promise; } export function translationDbAsync(): Promise; export function clearTranslationDbAsync(): Promise; export function getTutorialCodeHash(code: string[]): string; interface TutorialInfoIndexedDbEntry { id: string; time: number; hash: string; blocks: Map; snippets: Map>; highlightBlocks: Map>; validateBlocks: Map>; } export interface ITutorialInfoDb { getAsync(filename: string, code: string[], branch?: string): Promise; setAsync(filename: string, snippets: Map>, code: string[], highlights: Map>, codeValidationMap: Map>, branch?: string): Promise; clearAsync(): Promise; } class TutorialInfoIndexedDb implements ITutorialInfoDb { protected readonly db: pxt.BrowserUtils.IDBWrapper; static TABLE: string; static KEYPATH: string; static dbName(): string; static createAsync(): Promise; private constructor(); getAsync(filename: string, code: string[], branch?: string): Promise; setAsync(filename: string, snippets: Map>, code: string[], highlights: Map>, codeValidationMap: Map>, branch?: string): Promise; setWithHashAsync(filename: string, snippets: Map>, hash: string, highlights: Map>, codeValidationMap: Map>, branch?: string): Promise; clearAsync(): Promise; } export function tutorialInfoDbAsync(): Promise; export function clearTutorialInfoDbAsync(): Promise; export interface IPointerEvents { up: string; down: string[]; move: string; enter: string; leave: string; } export const pointerEvents: IPointerEvents; export function getPageX(event: any): number; export function getPageY(event: any): number; export function getClientX(event: any): number; export function getClientY(event: any): number; export function popupWindow(url: string, title: string, popUpWidth: number, popUpHeight: number): Window; export function containsClass(el: SVGElement | HTMLElement, classes: string): boolean; export function addClass(el: SVGElement | HTMLElement, classes: string): void; export function removeClass(el: SVGElement | HTMLElement, classes: string): void; export function getCookieLang(): string; export function setCookieLang(langId: string, docs?: boolean): void; export function cacheBustingUrl(url: string): string; export function appendUrlQueryParams(url: string, params: URLSearchParams): string; export function legacyCopyText(element: HTMLInputElement | HTMLTextAreaElement): boolean; /** * Sets the theme of the application by adding a class to the body. Themes * are defined in CSS variable packs. The default theme is defined in * `themes/themepacks.less`, in the `:root` pseudoclass. `highcontrast` is * also defined there. Target-specific themes are defined in the target * repo's `theme/themepack.less`. */ export function setApplicationTheme(theme: string | undefined): void; export function isElement(node: Node): node is Element; export {}; } declare namespace pxt.cloud { export type DevBackendType = "default" | "prod" | "staging" | "localhost"; const DEV_BACKEND_PROD = "https://makecode.com"; const DEV_BACKEND_STAGING = "https://staging.pxt.io"; const DEV_BACKEND_LOCALHOST = "http://localhost:8080"; type BackendUrls = typeof DEV_BACKEND_PROD | typeof DEV_BACKEND_STAGING | typeof DEV_BACKEND_LOCALHOST; export const DEV_BACKEND: BackendUrls; export const DEV_REGION = "US"; export function devBackendType(): DevBackendType; export type CloudStatus = "none" | "synced" | "justSynced" | "offline" | "syncing" | "conflict" | "localEdits"; export type CloudStatusInfo = { value: pxt.cloud.CloudStatus; icon?: string; tooltip?: string; shortStatus?: string; longStatus?: string; indicator?: string; }; export const cloudStatus: { [index in pxt.cloud.CloudStatus]: CloudStatusInfo; }; export {}; } declare namespace pxt.commands { enum WebUSBPairResult { Failed = 0, Success = 1, UserRejected = 2 } interface RecompileOptions { recompile: boolean; useVariants: string[]; } interface DeployOptions { reportError: (e: string) => void; showNotification: (msg: string) => void; } type DeployFnAsync = (r: ts.pxtc.CompileResult, d?: DeployOptions) => Promise; let deployCoreAsync: DeployFnAsync; let deployFallbackAsync: DeployFnAsync; let hasDeployFn: () => DeployFnAsync; let deployAsync: DeployFnAsync; let patchCompileResultAsync: (r: pxtc.CompileResult) => Promise; let browserDownloadAsync: (text: string, name: string, contentType: string) => Promise; let saveOnlyAsync: (r: ts.pxtc.CompileResult) => Promise; let renderBrowserDownloadInstructions: (saveOnly?: boolean, redeploy?: () => Promise) => any; let renderUsbPairDialog: (firmwareUrl?: string, failedOnce?: boolean) => any; let renderIncompatibleHardwareDialog: (unsupportedParts: string[]) => any; let renderDisconnectDialog: () => { header: string; jsx: any; helpUrl: string; }; let showUsbDeviceForgottenDialog: (confirmAsync: (options: any) => Promise) => Promise; let showUploadInstructionsAsync: (fn: string, url: string, confirmAsync: (options: any) => Promise, saveOnly?: boolean, redeploy?: () => Promise) => Promise; let showProgramTooLargeErrorAsync: (variants: string[], confirmAsync: (options: any) => Promise, saveOnly?: boolean) => Promise; let saveProjectAsync: (project: pxt.cpp.HexFile) => Promise; let electronDeployAsync: (r: ts.pxtc.CompileResult) => Promise; let electronFileDeployAsync: (deployRequest: pxt.electron.FileDeployRequest) => Promise; let webUsbPairDialogAsync: (pairAsync: () => Promise, confirmAsync: (options: any) => Promise, implicitlyCalled?: boolean) => Promise; let onTutorialCompleted: () => void; let onPostHostMessage: (msg: any) => void; let perfMeasurementThresholdMs: number; let onPerfMilestone: (payload: { milestone: string; time: number; params?: Map; }) => void; let onPerfMeasurement: (payload: { name: string; start: number; duration: number; params?: Map; }) => void; let workspaceLoadedAsync: () => Promise; let getDownloadMenuItems: () => any[]; let notifyProjectCompiled: (headerId: string, compileResult: pxtc.CompileResult) => void; let notifyProjectSaved: (header: pxt.workspace.Header) => void; let onDownloadButtonClick: () => Promise; let getDefaultProjectName: () => string; let onMarkdownActivityLoad: (path: string, title?: string, editorProjectName?: string) => Promise; } declare namespace pxt { function getWhiteContrastingBackground(color: string): string; function contrastRatio(fg: string, bg: string): number; } declare namespace Measurements { const TutorialInfoDbSetAsync = "tutorial info db setAsync"; const ReloadAppTargetVariant = "reloadAppTargetVariant"; const Sha256Buffer = "sha256buffer"; const WebworkerRecvHandler = "webworker recvHandler"; const NetworkRequest = "network.request"; } declare namespace pxt { function lzmaDecompressAsync(buf: Uint8Array): Promise; function lzmaCompressAsync(text: string): Promise; } declare namespace pxt.cpp { function nsWriter(nskw?: string): { setNs: (ns: string, over?: string) => void; clear: () => void; write: (s: string) => void; incrIndent: () => void; decrIndent: () => void; finish: () => string; }; function parseCppInt(v: string): number; class PkgConflictError extends Error { pkg0: Package; pkg1: Package; settingName: string; isUserError: boolean; isVersionConflict: boolean; constructor(msg: string); } function getExtensionInfo(mainPkg: MainPackage): pxtc.ExtensionInfo; interface HexFileMeta { cloudId: string; targetVersions?: pxt.TargetVersions; editor: string; name: string; } interface HexFile { meta?: HexFileMeta; source: string; } function unpackSourceFromHexFileAsync(file: File): Promise; function unpackSourceFromHexAsync(dat: Uint8Array): Promise; } declare namespace pxt.hexloader { let showLoading: (msg: string) => void; let hideLoading: () => void; function storeWithLimitAsync(host: Host, idxkey: string, newkey: string, newval: string, maxLen?: number): Promise; function recordGetAsync(host: Host, idxkey: string, newkey: string): Promise; function getHexInfoAsync(host: Host, extInfo: pxtc.ExtensionInfo, cloudModule?: any): Promise; } declare namespace pxt.crowdin { const KEY_VARIABLE = "CROWDIN_KEY"; let testMode: boolean; function setTestMode(): void; function inContextLoadAsync(text: string): Promise; } declare namespace pxt.diff { export function toLines(file: string, includeNewline?: boolean): string[]; export interface DiffOptions { context?: number; ignoreWhitespace?: boolean; maxDiffSize?: number; full?: boolean; } enum DiffOp { Added = 1, Deleted = -1, Unchanged = 0 } type DiffPart = [DiffOp, string]; interface Patch { diffs: DiffPart[]; length1: number; length2?: number; start1: number; start2?: number; } export function compute(fileA: string, fileB: string, options?: DiffOptions): DiffPart[]; export function computeFormattedDiff(fileA: string, fileB: string, options?: DiffOptions): string[]; export function computePatch(fileA: string, fileB: string): Patch[]; export function applyPatch(file: string, patch: Patch[]): string; export function diff3(fileA: string, fileO: string, fileB: string, lblA: string, lblB: string): { merged: string; numConflicts: number; }; export function removeTrailingSemiColumns(src: string): string; export function split(dualSrc: string, options?: { removeTrailingSemiColumns?: boolean; }): { fileA: string; fileB: string; }; export interface DiffMarker { oldStart: number; oldLength: number; newStart: number; newLength: number; } export function parseDiffMarker(ln: string): DiffMarker; export interface RenderOptions extends DiffOptions { hideMarkerLine?: boolean; hideLineNumbers?: boolean; hideMarker?: boolean; hideRemoved?: boolean; update?: boolean; } export function render(fileA: string, fileB: string, options?: RenderOptions): HTMLElement; export function resolveMergeConflictMarker(content: string, startMarkerLine: number, local: boolean, remote: boolean): string; /** * A naive 3way merge for pxt.json files. It can mostly handle conflicts when adding/removing files concurrently. * - highest version number if kept * - current preferred editor is kept * - conjection of public flag * - files list is merged so that added files are kept and deleted files are removed * @param configA * @param configO * @param configB */ export function mergeDiff3Config(configA: string, configO: string, configB: string): string; export function hasMergeConflictMarker(content: string): boolean; export function reconstructConfig(parsed: pxt.github.ParsedRepo, files: pxt.Map, commit: pxt.github.Commit, tp: pxt.ProjectTemplate): PackageConfig; export {}; } declare namespace pxt.discourse { function extractSharedIdFromPostUrl(url: string): Promise; function topicsByTag(apiUrl: string, tag: string): Promise; } declare namespace pxt.docs { type MarkedRenderFunction = (src: string, options?: any) => string; interface MarkedRenderer { options?: any; parser: { parse: (tokens: any[], loose?: boolean) => string; parseInline: (tokens: any[]) => string; }; code?: (token: any) => string; link?: (token: any) => string; image?: (token: any) => string; listitem?: (token: any) => string; heading?: (token: any) => string; } interface MarkedModule extends MarkedRenderFunction { Renderer: { new (): MarkedRenderer; }; lexer: (src: string, options?: any) => any[]; setOptions: (options: any) => void; parseInline?: (src: string, options?: any) => string; parse?: (src: string, options?: any) => string; } export function htmlQuote(s: string): string; export function html2Quote(s: string): string; export interface BreadcrumbEntry { name: string; href: string; } export let requireMarked: () => MarkedModule | undefined; export let requireDOMSanitizer: () => typeof DOMPurify.sanitize; export interface RenderData { html: string; theme: AppTheme; params: Map; filepath?: string; versionPath?: string; ghEditURLs?: string[]; finish?: () => string; boxes?: Map; macros?: Map; settings?: Map; TOC?: TOCMenuEntry[]; } export function prepTemplate(d: RenderData): void; export interface RenderOptions { template: string; markdown: string; theme?: AppTheme; pubinfo?: Map; filepath?: string; versionPath?: string; locale?: Map; ghEditURLs?: string[]; repo?: { name: string; fullName: string; tag?: string; }; throwOnError?: boolean; TOC?: TOCMenuEntry[]; } export function setupRenderer(renderer: MarkedRenderer, context?: { versionPath?: string; }): void; export function renderConditionalMacros(template: string, pubinfo: Map): string; export function renderMarkdown(opts: RenderOptions): string; export function embedUrl(rootUrl: string, tag: string, id: string, height?: number): string; export function runUrl(url: string, padding: string, id: string): string; export function codeEmbedUrl(rootUrl: string, id: string, height?: number): string; export function translate(html: string, locale: Map): { text: string; missing: Map; }; export function buildTOC(summaryMD: string): pxt.TOCMenuEntry[]; export function visitTOC(toc: TOCMenuEntry[], fn: (e: TOCMenuEntry) => void): void; export function augmentDocs(baseMd: string, childMd: string): string; export function hydrateYouTubeEmbeds(content: HTMLElement, tickEvent: boolean): void; export {}; } declare namespace pxt.dom { function el(name: string, attributes?: pxt.Map, children?: string | HTMLElement | (string | HTMLElement)[]): HTMLElement; } declare namespace pxt.gallery { interface Gallery { name: string; cards: pxt.CodeCard[]; } interface GalleryProject { name: string; snippetType: string; source: string; filesOverride: pxt.Map; dependencies: pxt.Map; features?: string[]; simTheme?: Partial; } function parsePackagesFromMarkdown(md: string): pxt.Map; function parseFeaturesFromMarkdown(md: string): string[]; function parseJResFromMarkdown(md: string): { jres: string; ts: string; }; function parseTemplateProjectJSON(md: string): pxt.Map; function parseSimThemeJSON(md: string): Partial; function parseExampleMarkdown(name: string, md: string): GalleryProject; function parseCodeCards(md: string): pxt.CodeCard[]; function parseCodeCardsHtml(el: HTMLElement): CodeCard[]; function parseGalleryMardown(md: string): Gallery[]; function loadGalleryAsync(name: string): Promise; function codeCardsToMarkdown(cards: pxt.CodeCard[]): string; } declare namespace pxt { class GDBServer { io: pxt.TCPIO; private q; private dataBuf; private numSent; private pktSize; trace: boolean; bmpMode: boolean; targetInfo: string; private onResponse; private onEvent; constructor(io: pxt.TCPIO); private onData; private buildCmd; private decodeResp; sendCmdOKAsync(cmd: string): Promise; error(msg: string): void; sendCmdAsync(cmd: string, respTest?: (resp: string) => boolean): Promise; sendRCmdAsync(cmd: string): Promise; sendMCmdAsync(cmd: string): Promise; write32Async(addr: number, data: number): Promise; writeMemAsync(addr: number, data: Uint8Array): Promise; readMemAsync(addr: number, bytes: number): Promise; private initBMPAsync; initAsync(): Promise; } } declare namespace pxt.github { interface GHRef { ref: string; url: string; object: { sha: string; type: string; url: string; }; } /** * Commit user info */ interface UserInfo { date: string; name: string; email: string; } interface SHAObject { url: string; sha: string; } interface TreeEntry extends SHAObject { path: string; mode: string; type: "blob" | "tree"; size?: number; blobContent?: string; } interface Tree extends SHAObject { tree: TreeEntry[]; truncated: boolean; } interface CommitInfo extends SHAObject { author: UserInfo; committer: UserInfo; message: string; tree: SHAObject; } interface Commit extends SHAObject { author: UserInfo; committer: UserInfo; message: string; tag?: string; parents: SHAObject[]; tree: Tree; } let token: string; interface RefsResult { refs: pxt.Map; head?: string; } interface FileContent { encoding: string; content: string; size: number; sha: string; download_url: string; } interface GHTutorialResponse { path: string; markdown: string | { filename: string; repo: GHTutorialRepoInfo; }; dependencies: GHTutorialRepoInfo[]; } interface GHTutorialRepoInfo { repo: string; files: pxt.Map; sha: string; fileHash: string; subPath?: string; version?: string; latestVersion?: string; } let forceProxy: boolean; /** * Determines if we should use the proxy for a specific repo to avoid SAML SSO issues. * Returns true if the repo is owned by an organization that requires SAML and we have a token. */ function shouldUseProxyForRepo(repoPath: string): boolean; let handleGithubNetworkError: (opts: U.HttpRequestOptions, e: any) => boolean; interface CachedPackage { files: Map; } interface IGithubDb { latestVersionAsync(repopath: string, config: PackagesConfig): Promise; loadConfigAsync(repopath: string, tag: string): Promise; loadPackageAsync(repopath: string, tag: string): Promise; loadTutorialMarkdown(repopath: string, tag?: string): Promise; cacheReposAsync(response: GHTutorialResponse): Promise; } function isOrgAsync(owner: string): Promise; class MemoryGithubDb implements IGithubDb { private latestVersions; private configs; private packages; private proxyWithCdnLoadPackageAsync; private cacheConfig; loadConfigAsync(repopath: string, tag: string): Promise; latestVersionAsync(repopath: string, config: PackagesConfig): Promise; loadPackageAsync(repopath: string, tag: string): Promise; private githubLoadPackageAsync; loadTutorialMarkdown(repopath: string, tag?: string): Promise; cacheReposAsync(resp: GHTutorialResponse): Promise; private cacheRepo; private cacheLatestVersion; } function downloadTextAsync(repopath: string, commitid: string, filepath: string): Promise; function downloadMarkdownTutorialInfoAsync(repopath: string, tag?: string, noCache?: boolean, etag?: string): Promise<{ resp?: GHTutorialResponse; etag?: string; }>; function downloadTutorialMarkdownAsync(repopath: string, tag?: string): Promise; let db: IGithubDb; function authenticatedUserAsync(): Promise; function getCommitsAsync(repopath: string, sha: string): Promise; function getCommitAsync(repopath: string, sha: string): Promise; interface CreateBlobReq { content: string; encoding: "utf-8" | "base64"; } interface CreateTreeReq { base_tree: string; tree: TreeEntry[]; } interface CreateCommitReq { message: string; parents: string[]; tree: string; } function createObjectAsync(repopath: string, type: string, data: any): Promise; function postCommitComment(repopath: string, commitSha: string, body: string, path?: string, position?: number): Promise; function fastForwardAsync(repopath: string, branch: string, commitid: string): Promise; function putFileAsync(repopath: string, path: string, content: string): Promise; function createTagAsync(repopath: string, tag: string, commitid: string): Promise; function createReleaseAsync(repopath: string, tag: string, commitid: string): Promise; function createPRFromBranchAsync(repopath: string, baseBranch: string, headBranch: string, title: string, msg?: string): Promise; function mergeAsync(repopath: string, base: string, head: string, message?: string): Promise; function getRefAsync(repopath: string, branch: string): Promise; function getNewBranchNameAsync(repopath: string, pref?: string): Promise; function createNewBranchAsync(repopath: string, branchName: string, commitid: string): Promise; function forkRepoAsync(repopath: string, commitid: string, pref?: string): Promise; function listRefsAsync(repopath: string, namespace?: string, useProxy?: boolean, noCache?: boolean): Promise; function listRefsExtAsync(repopath: string, namespace?: string, useProxy?: boolean, noCache?: boolean): Promise; function pkgConfigAsync(repopath: string, tag: string, config: pxt.PackagesConfig): Promise; function downloadPackageAsync(repoWithTag: string, config: pxt.PackagesConfig): Promise; function downloadLatestPackageAsync(repo: ParsedRepo, useProxy?: boolean, noCache?: boolean): Promise<{ version: string; config: pxt.PackageConfig; }>; function cacheProjectDependenciesAsync(cfg: pxt.PackageConfig): Promise; interface User { login: string; id: number; avatar_url: string; gravatar_id: string; html_url: string; type: string; name: string; company: string; } interface ParsedRepo { owner?: string; project?: string; slug: string; fullName: string; tag?: string; fileName?: string; } enum GitRepoStatus { Unknown = 0, Approved = 1, Banned = 2 } interface GitRepo extends ParsedRepo { name: string; displayName?: string; description: string; defaultBranch: string; status?: GitRepoStatus; updatedAt?: number; private?: boolean; fork?: boolean; } function isDefaultBranch(branch: string, repo?: GitRepo): boolean; function listUserReposAsync(): Promise; function createRepoAsync(name: string, description: string, priv?: boolean): Promise; function enablePagesAsync(repo: string): Promise; function repoIconUrl(repo: GitRepo): string; function mkRepoIconUrl(repo: ParsedRepo): string; function repoStatus(rr: ParsedRepo, config: pxt.PackagesConfig): GitRepoStatus; function isRepoHidden(repo: ParsedRepo, config: pxt.PackagesConfig): boolean; function repoAsync(repopath: string, config: pxt.PackagesConfig): Promise; function searchAsync(query: string, config: pxt.PackagesConfig): Promise; function parseRepoId(repo: string): ParsedRepo; function toGithubDependencyPath(path: string, tag?: string): string; function isGithubId(id: string): boolean; function stringifyRepo(p: ParsedRepo, ignoreCase?: boolean): string; function normalizeRepoId(id: string, defaultTag?: string): string; function join(...parts: string[]): string; function upgradedPackageReferenceAsync(cfg: PackagesConfig, id: string): Promise; function upgradedPackageId(cfg: PackagesConfig, id: string): string; function latestVersionAsync(repopath: string, config: PackagesConfig, useProxy?: boolean, noCache?: boolean): Promise; function resolveMonoRepoVersions(deps: pxt.Map): pxt.Map; interface GitJson { repo: string; commit: pxt.github.Commit; isFork?: boolean; mergeSha?: string; } const GIT_JSON = ".git.json"; function lookupFile(parsed: ParsedRepo, commit: pxt.github.Commit, path: string): TreeEntry; /** * Executes a GraphQL query against GitHub v4 api * @param query */ function ghGraphQLQueryAsync(query: string): Promise; interface PullRequest { number: number; url?: string; title?: string; base?: string; isDraft?: boolean; state?: "OPEN" | "CLOSED" | "MERGED"; mergeable?: "MERGEABLE" | "CONFLICTING" | "UNKNOWN"; } /** * Finds the first PR associated with a branch * @param reponame * @param headName */ function findPRNumberforBranchAsync(reponame: string, headName: string): Promise; interface GitHubPagesStatus { status: null | "queued" | "building" | "built" | "errored"; html_url?: string; source?: { branch: string; directory: string; }; } function getPagesStatusAsync(repoPath: string): Promise; function normalizeTutorialPath(repopath: string): string; } declare namespace pxt { const REFCNT_FLASH = "0xfffe"; const VTABLE_MAGIC = 249; const ValTypeObject = 4; enum BuiltInType { BoxedString = 1, BoxedNumber = 2, BoxedBuffer = 3, RefAction = 4, RefImage = 5, RefCollection = 6, RefRefLocal = 7, RefMap = 8, RefMImage = 9, MMap = 10, BoxedString_SkipList = 11, BoxedString_ASCII = 12, ZPin = 13, User0 = 16 } } declare namespace pxt.HF2 { interface MutableArrayLike { readonly length: number; [n: number]: T; } const enum VID { ATMEL = 1003, ARDUINO = 9025, ADAFRUIT = 9114, NXP = 3368 } const HF2_CMD_BININFO = 1; const HF2_MODE_BOOTLOADER = 1; const HF2_MODE_USERSPACE = 2; const HF2_CMD_INFO = 2; const HF2_CMD_RESET_INTO_APP = 3; const HF2_CMD_RESET_INTO_BOOTLOADER = 4; const HF2_CMD_START_FLASH = 5; const HF2_CMD_WRITE_FLASH_PAGE = 6; const HF2_CMD_CHKSUM_PAGES = 7; const HF2_CMD_READ_WORDS = 8; const HF2_CMD_WRITE_WORDS = 9; const HF2_CMD_DMESG = 16; const HF2_FLAG_SERIAL_OUT = 128; const HF2_FLAG_SERIAL_ERR = 192; const HF2_FLAG_CMDPKT_LAST = 64; const HF2_FLAG_CMDPKT_BODY = 0; const HF2_FLAG_MASK = 192; const HF2_SIZE_MASK = 63; const HF2_STATUS_OK = 0; const HF2_STATUS_INVALID_CMD = 1; const HF2_STATUS_EXEC_ERR = 2; const HF2_STATUS_EVENT = 128; const HF2_CMD_JDS_CONFIG = 32; const HF2_CMD_JDS_SEND = 33; const HF2_EV_JDS_PACKET = 8388640; const CUSTOM_EV_JACDAC = "jacdac"; const HF2_EV_MASK = 8388608; function write32(buf: MutableArrayLike, pos: number, v: number): void; function write16(buf: MutableArrayLike, pos: number, v: number): void; function read32(buf: ArrayLike, pos: number): number; function read16(buf: ArrayLike, pos: number): number; function encodeU32LE(words: number[]): Uint8Array; function decodeU32LE(buf: Uint8Array): number[]; interface BootloaderInfo { Header: string; Parsed: { Version: string; Features: string; }; Model: string; BoardID: string; } function enableLog(): void; class Wrapper implements pxt.packetio.PacketIOWrapper { readonly io: pxt.packetio.PacketIO; private initialized; private cmdSeq; constructor(io: pxt.packetio.PacketIO); private lock; flashing: boolean; rawMode: boolean; infoRaw: string; info: BootloaderInfo; pageSize: number; flashSize: number; maxMsgSize: number; familyID: number; bootloaderMode: boolean; reconnectTries: number; autoReconnect: boolean; icon: string; msgs: U.PromiseBuffer; eventHandlers: pxt.Map<(buf: Uint8Array) => void>; jacdacAvailable: boolean; onSerial: (buf: Uint8Array, isStderr: boolean) => void; onCustomEvent: (type: string, payload: Uint8Array) => void; onConnectionChanged: () => void; private resetState; onEvent(id: number, f: (buf: Uint8Array) => void): void; sendCustomEventAsync(type: string, payload: Uint8Array): Promise; isConnected(): boolean; isConnecting(): boolean; reconnectAsync(): Promise; disconnectAsync(): Promise; error(m: string): any; talkAsync(cmd: number, data?: Uint8Array): Promise; private sendMsgAsync; sendSerialAsync(buf: Uint8Array, useStdErr?: boolean): Promise; private sendMsgCoreAsync; switchToBootloaderAsync(): Promise; isFlashing(): boolean; reflashAsync(resp: pxtc.CompileResult): Promise; writeWordsAsync(addr: number, words: number[]): Promise; readWordsAsync(addr: number, numwords: number): Promise; pingAsync(): Promise; maybeReconnectAsync(): Promise; flashAsync(blocks: pxtc.UF2.Block[]): Promise; private initAsync; } function mkHF2PacketIOWrapper(io: pxt.packetio.PacketIO): pxt.packetio.PacketIOWrapper; type ReadAsync = (addr: number, len: number) => Promise>; function onlyChangedBlocksAsync(blocks: pxtc.UF2.Block[], readWordsAsync: ReadAsync): Promise; } declare namespace pxt.HWDBG { import H = pxt.HF2; interface StateInfo { numGlobals: number; globalsPtr: number; } const taggedUndefined = 0; const taggedNull: number; const taggedFalse: number; const taggedTrue: number; let postMessage: (msg: pxsim.DebuggerMessage) => void; function decodeValue(n: number): any; function heapExpandAsync(v: any): Promise; function heapExpandMapAsync(vars: pxsim.Variables): Promise; function startDebugAsync(compileRes: pxtc.CompileResult, hidWr: H.Wrapper): Promise; function handleMessage(msg: pxsim.DebuggerMessage): void; function resumeAsync(into?: boolean): Promise; interface HwState { staticState: StateInfo; globals: Uint8Array; } function waitForHaltAsync(): Promise; function getHwStateAsync(): Promise; } declare namespace pxt { class ImageConverter { private palette; private start; logTime(): void; convert(jresURL: string): string; setPalette(paletteArrays: number[][]): void; genMonochrome(data: string, w: number, h: number): string; genColor(data: string, width: number, height: number, intScale: number): string; } function convertUint8BufferToPngUri(palette: Uint8Array, icon: Uint8Array): string; } declare namespace pxt.template { const TS_CONFIG = "{\n \"compilerOptions\": {\n \"target\": \"ES5\",\n \"noImplicitAny\": true,\n \"outDir\": \"built\",\n \"rootDir\": \".\"\n },\n \"exclude\": [\"pxt_modules/**/*test.ts\"]\n}\n"; function defaultFiles(): Map; function targetTemplateFiles(): pxt.Map; const TEMPLATE_PRJ = "template"; function packageFiles(name: string): pxt.Map; function packageFilesFixup(files: Map, options?: pxt.Map): void; } declare namespace pxt.blocks { enum NT { Prefix = 0, Postfix = 1, Infix = 2, Block = 3, NewLine = 4 } interface JsNode { type: NT; children: JsNode[]; op: string; id?: string; glueToBlock?: GlueMode; canIndentInside?: boolean; noFinalNewline?: boolean; } enum GlueMode { None = 0, WithSpace = 1, NoSpace = 2 } function backtickLit(s: string): string; function stringLit(s: string): string; function mkNode(tp: NT, pref: string, children: JsNode[]): JsNode; function mkNewLine(): JsNode; function mkPrefix(pref: string, children: JsNode[]): JsNode; function mkPostfix(children: JsNode[], post: string): JsNode; function mkInfix(child0: JsNode, op: string, child1: JsNode): JsNode; function mkText(s: string): JsNode; function mkBlock(nodes: JsNode[]): JsNode; function mkGroup(nodes: JsNode[]): JsNode; function mkStmt(...nodes: JsNode[]): JsNode; function mkCommaSep(nodes: JsNode[], withNewlines?: boolean): JsNode; namespace Helpers { function mkArrayLiteral(args: JsNode[], withNewlines?: boolean): JsNode; function mkNumberLiteral(x: number): JsNode; function mkBooleanLiteral(x: boolean): JsNode; function mkStringLiteral(x: string): JsNode; function mkPropertyAccess(name: string, thisArg: JsNode): JsNode; function mkCall(name: string, args: JsNode[], externalInputs?: boolean, method?: boolean): JsNode; function stdCall(name: string, args: JsNode[], externalInputs: boolean): JsNode; function extensionCall(name: string, args: JsNode[], externalInputs: boolean): JsNode; function namespaceCall(namespace: string, name: string, args: JsNode[], externalInputs: boolean): JsNode; function mathCall(name: string, args: JsNode[]): JsNode; function mkGlobalRef(name: string): JsNode; function mkSimpleCall(p: string, args: JsNode[]): JsNode; function mkWhile(condition: JsNode, body: JsNode[]): JsNode; function mkComment(text: string): JsNode; function mkMultiComment(text: string): JsNode; function mkAssign(x: JsNode, e: JsNode): JsNode; function mkParenthesizedExpression(expression: JsNode): JsNode; } export import H = Helpers; interface BlockSourceInterval { id: string; startLine: number; startPos: number; endLine: number; endPos: number; } function flattenNode(app: JsNode[]): { output: string; sourceMap: BlockSourceInterval[]; }; function isReservedWord(str: string): boolean; function isParenthesized(fnOutput: string): boolean; } declare namespace pxt.sprite { const BLOCKLY_TILESET_TYPE = "BLOCKLY_TILESET_TYPE"; const TILE_PREFIX = "tile"; const TILE_NAMESPACE = "myTiles"; const IMAGES_NAMESPACE = "myImages"; const IMAGE_PREFIX = "image"; const ANIMATION_NAMESPACE = "myAnimations"; const ANIMATION_PREFIX = "anim"; const SONG_NAMESPACE = "mySongs"; const JSON_NAMESPACE = "myFiles"; const SONG_PREFIX = "song"; const JSON_PREFIX = "file"; interface Coord { x: number; y: number; } interface BitmapData { width: number; height: number; x0: number; y0: number; data: Uint8ClampedArray; } interface AnimationData { interval: number; frames: BitmapData[]; } interface ImageState { bitmap: BitmapData; overlayLayers?: BitmapData[]; floating?: { bitmap: BitmapData; overlayLayers: BitmapData[]; }; layerOffsetX?: number; layerOffsetY?: number; } /** * 16-color sprite */ class Bitmap { width: number; height: number; x0: number; y0: number; protected buf: Uint8ClampedArray; static fromData(data: BitmapData): Bitmap; constructor(width: number, height: number, x0?: number, y0?: number, buf?: Uint8ClampedArray); set(col: number, row: number, value: number): void; get(col: number, row: number): number; copy(col?: number, row?: number, width?: number, height?: number): Bitmap; apply(change: Bitmap, transparent?: boolean): void; equals(other: Bitmap): boolean; data(): BitmapData; resize(width: number, height: number): Bitmap; protected coordToIndex(col: number, row: number): number; protected getCore(index: number): number; protected setCore(index: number, value: number): void; dataLength(): number; } class Tilemap extends Bitmap { static fromData(data: BitmapData): Tilemap; copy(col?: number, row?: number, width?: number, height?: number): Tilemap; resize(width: number, height: number): Tilemap; protected getCore(index: number): number; protected setCore(index: number, value: number): void; dataLength(): number; } class TilemapData { tilemap: Tilemap; tileset: TileSet; layers: BitmapData; nextId: number; projectReferences: string[]; tileOrder: string[]; editedTiles: string[]; deletedTiles: string[]; constructor(tilemap: Tilemap, tileset: TileSet, layers: BitmapData); cloneData(includeEditorData?: boolean): TilemapData; equals(other: TilemapData): boolean; } class Bitmask { width: number; height: number; protected mask: Uint8Array; constructor(width: number, height: number); set(col: number, row: number): void; get(col: number, row: number): number; } function encodeTilemap(t: TilemapData, fileType: "typescript" | "python", idMap?: { [index: string]: string; }): string; function decodeTilemap(literal: string, fileType: "typescript" | "python", proj: TilemapProject): TilemapData; function trimTilemapTileset(t: TilemapData): void; function isEmptyTilemap(t: TilemapData): boolean; function computeAverageColor(bitmap: Bitmap, colors: string[]): string; interface GalleryItem { qName: string; src: string; alt: string; tags: string[]; } function getBitmap(blocksInfo: pxtc.BlocksInfo, qName: string): Bitmap; function getBitmapFromJResURL(jresURL: string): Bitmap; function hexToBitmap(data: string): Bitmap; function filterItems(target: GalleryItem[], tags: string[]): GalleryItem[]; function getGalleryItems(blocksInfo: pxtc.BlocksInfo, qName: string): GalleryItem[]; function base64EncodeBitmap(data: BitmapData): string; function tilemapLiteralToTilemap(text: string, defaultPattern?: string): Tilemap; function hexEncodeTilemap(t: Tilemap): string; function formatByte(value: number, bytes: number): string; function resizeBitmap(img: Bitmap, width: number, height: number): Bitmap; function resizeTilemap(img: Tilemap, width: number, height: number): Tilemap; function imageLiteralToBitmap(text: string, templateLiteral?: string): Bitmap; function encodeAnimationString(frames: BitmapData[], interval: number): string; function addMissingTilemapTilesAndReferences(project: TilemapProject, asset: ProjectTilemap): void; function updateTilemapReferencesFromResult(project: TilemapProject, assetResult: ProjectTilemap): void; function isTilemapEmptyOrUnused(asset: ProjectTilemap, project: TilemapProject, projectFiles: pxt.Map<{ content: string; }>): boolean; function imageLiteralFromDimensions(width: number, height: number, color: number, fileType: "typescript" | "python"): string; function bitmapToImageLiteral(bitmap: Bitmap, fileType: "typescript" | "python", templateLiteral?: string): string; function bitmapEquals(a: pxt.sprite.BitmapData, b: pxt.sprite.BitmapData): boolean; function tilesetEquals(a: TileSet, b: TileSet): boolean; function tileWidthToTileScale(tileWidth: number): string; function tileScaleToTileWidth(tileScale: string): number; function hexToUint8Array(hex: string): Uint8ClampedArray; function uint8ArrayToHex(data: Uint8ClampedArray | Uint8Array): string; function colorStringToRGB(color: string): number[]; } declare namespace pxt.sprite.legacy { interface LegacyTileInfo { data: BitmapData; qualifiedName?: string; projectId?: number; } interface LegacyTileSet { tileWidth: number; tiles: LegacyTileInfo[]; } class LegacyTilemapData { tilemap: Tilemap; tileset: LegacyTileSet; layers: BitmapData; nextId: number; projectReferences: number[]; constructor(tilemap: Tilemap, tileset: LegacyTileSet, layers: BitmapData); } function decodeTilemap(literal: string, fileType: "typescript" | "python"): LegacyTilemapData; function tileToBlocklyVariable(info: LegacyTileInfo): string; function blocklyVariableToTile(name: string): LegacyTileInfo; } declare namespace pxt.storage { function storageId(): string; function setLocal(key: string, value: string): void; function getLocal(key: string): string; function removeLocal(key: string): void; function clearLocal(): void; } /** * Storage that will be shared across localhost frames when developing locally. Uses regular browser storage in production. * One side effect: Localhost storage will be shared between different browsers and incognito tabs as well. To disable this * behavior, set the `routingEnabled` switch below to `false`. */ declare namespace pxt.storage.shared { function getAsync(container: string, key: string): Promise; function setAsync(container: string, key: string, val: any): Promise; function delAsync(container: string, key: string): Promise; } declare namespace pxt { interface MarkdownSection { headerKind: "single" | "double" | "triple"; header: string; attributes: pxt.Map; listAttributes?: pxt.Map; codeBlocks?: MarkdownCodeBlock[]; } interface MarkdownCodeBlock { content: string; languageCode?: string; } interface MarkdownList { key: string; items: (string | MarkdownList)[]; } function getSectionsFromMarkdownMetadata(text: string): MarkdownSection[]; } declare namespace pxt.multiplayer { const ABSOLUTE_LINKS: { PROD_BETA: string; STAGING_BETA: string; LOCAL: string; }; const RELATIVE_LINKS: { PROD: string; BETA: string; }; const SHORT_LINKS: { PROD: string; PROD_BETA: string; STAGING: string; STAGING_BETA: string; }; const RELATIVE_LINK: () => string; const SHORT_LINK: () => string; function makeHostLink(shareUrlOrCode: string, shortLink: boolean): string; function makeJoinLink(joinCode: string, shortLink: boolean): string; } declare namespace pxt.assets.music { function encodeSongToHex(song: Song): string; function decodeSongFromHex(hex: string): Song; function cloneSong(song: Song): Song; function songEquals(a: Song, b: Song): boolean; function inflateSong(song: pxt.assets.music.Song): void; function getSongInfo(song: pxt.assets.music.Song): SongInfo; function getEmptySong(measures: number): pxt.assets.music.Song; } declare namespace pxt { class Package { id: string; _verspec: string; parent: MainPackage; depName: string; static stringifyConfig(config: pxt.PackageConfig): string; static parseAndValidConfig(configStr: string): pxt.PackageConfig; static getConfigAsync(pkgTargetVersion: string, id: string, fullVers: string): Promise; static corePackages(): pxt.PackageConfig[]; addedBy: Package[]; config: PackageConfig; level: number; isLoaded: boolean; private resolvedVersion; ignoreTests: boolean; cppOnly: boolean; installedVersion: string; protected assetPackFiles: pxt.Map; constructor(id: string, _verspec: string, parent: MainPackage, addedBy: Package, depName: string); disablesVariant(v: string): boolean; invalid(): boolean; version(): string; verProtocol(): string; verArgument(): string; targetVersion(): string; commonDownloadAsync(): Promise>; writeAssetPackFiles(): void; protected getNamespaceName(): string; host(): Host; readFile(fn: string): string; writeFile(fn: string, content: string): void; readGitJson(): pxt.github.GitJson; resolveDep(id: string): Package; saveConfig(): void; setPreferredEditor(editor: string): void; getPreferredEditor(): string; parseJRes(allres?: Map): Map; isAssetPack(): boolean; private resolveVersionAsync; private downloadAsync; loadConfig(): void; protected validateConfig(): void; isPackageInUse(pkgId: string, ts?: string): boolean; private upgradePackagesAsync; private getMissingPackages; /** * For the given package config or ID, looks through all the currently installed packages to find conflicts in * Yotta settings and version spec */ findConflictsAsync(pkgOrId: string | PackageConfig, version: string): Promise; configureAsInvalidPackage(reason: string): void; private parseConfig; private patchCorePackage; resolvedDependencies(): Package[]; dependencies(includeCpp?: boolean): pxt.Map; loadAsync(isInstall?: boolean, targetVersion?: string): Promise; static depWarnings: Map; getFiles(): string[]; addSnapshot(files: Map, exts?: string[]): void; /** * Returns localized strings qName (+ some additional identification data) -> translation */ packageLocalizationStringsAsync(lang: string): Promise>; bundledStringsForFile(lang: string, filename: string): Map; patchAppTargetPalette(): void; } class MainPackage extends Package { _host: Host; deps: Map; private _jres; constructor(_host: Host); installAllAsync(targetVersion?: string): Promise; sortedDeps(includeCpp?: boolean): Package[]; localizationStringsAsync(lang: string): Promise>; getTargetOptions(): pxtc.CompileTarget; getJRes(): Map; updateJRes(): void; private _resolvedBannedCategories; resolveBannedCategories(): string[]; getCompileOptionsAsync(target?: pxtc.CompileTarget): Promise; private prepareConfigToBePublished; filesToBePublishedAsync(allowPrivate?: boolean): Promise>; saveToJsonAsync(): Promise; compressToFileAsync(): Promise; computePartDefinitions(parts: string[]): pxt.Map; } function inflateJRes(js: Map, allres?: Map): Map; function allPkgFiles(cfg: PackageConfig): string[]; function isPkgBeta(cfg: { description?: string; }): boolean; } declare namespace pxt.packetio { interface TalkArgs { cmd: number; data?: Uint8Array; } interface PacketIOWrapper { readonly io: PacketIO; icon: string; familyID: number; onSerial: (buf: Uint8Array, isStderr: boolean) => void; reconnectAsync(): Promise; disconnectAsync(): Promise; isConnected(): boolean; isConnecting(): boolean; reflashAsync(resp: pxtc.CompileResult, progressCallback?: (percentageComplete: number) => void): Promise; onCustomEvent: (type: string, payload: Uint8Array) => void; sendCustomEventAsync(type: string, payload: Uint8Array): Promise; unsupportedParts?(): string[]; devVariant?: string; } interface PacketIO { sendPacketAsync(pkt: Uint8Array): Promise; recvPacketAsync?: (timeout?: number) => Promise; onDeviceConnectionChanged: (connect: boolean) => void; onConnectionChanged: () => void; onData: (v: Uint8Array) => void; onError: (e: Error) => void; onEvent: (v: Uint8Array) => void; error(msg: string): any; reconnectAsync(): Promise; disconnectAsync(): Promise; isConnecting(): boolean; isConnected(): boolean; isSwitchingToBootloader?: () => void; disposeAsync(): Promise; talksAsync?(cmds: TalkArgs[]): Promise; sendSerialAsync?(buf: Uint8Array, useStdErr: boolean): Promise; onSerial?: (v: Uint8Array, isErr: boolean) => void; } let mkPacketIOAsync: () => Promise; let mkPacketIOWrapper: (io: PacketIO) => PacketIOWrapper; /** * A DAP wrapper is active */ function isActive(): boolean; /** * The DAP wrapper is active and the device is connected */ function isConnected(): boolean; function isConnecting(): boolean; function icon(): string; function unsupportedParts(): string[]; function deviceVariant(): string; function disconnectAsync(): Promise; function configureEvents(onConnectionChanged: () => void, onSerial: (buf: Uint8Array, isStderr: boolean) => void, onCustomEvent: (type: string, buf: Uint8Array) => void): void; function sendCustomEventAsync(type: string, payload: Uint8Array): Promise; function initAsync(force?: boolean): Promise; } declare namespace pxt.patching { function computePatches(version: string, kind?: string): ts.pxtc.UpgradePolicy[]; function computePyPatches(version: string, kind?: string): ts.pxtc.UpgradePolicy[]; function upgradePackageReference(pkgTargetVersion: string, pkg: string, val: string): string; function patchJavaScript(pkgTargetVersion: string, fileContents: string): string; function patchPython(pkgTargetVersion: string, fileContents: string): string; } declare namespace pxt.react { interface FieldEditorView { show(): void; hide(): void; getResult(): U; onHide(cb: () => void): void; getPersistentData(): any; restorePersistentData(value: any): void; } let isFieldEditorViewVisible: () => boolean; let getFieldEditorView: (fieldEditorId: string, value: U, options: any, container?: HTMLDivElement, keyboardTriggered?: boolean) => FieldEditorView; let getTilemapProject: () => TilemapProject; } declare namespace pxt.semver { interface Version { major: number; minor: number; patch: number; pre: string[]; build: string[]; } function cmp(a: Version, b: Version): number; function parse(v: string, defaultVersion?: string): Version; function tryParse(v: string): Version; function normalize(v: string): string; function stringify(v: Version): string; function majorCmp(a: string, b: string): number; /** * Compares two semver version strings and returns -1 if a < b, 1 if a > b and 0 * if versions are equivalent. If a and b are invalid versions, classic strcmp is called. * If a (or b) is an invalid version, it is considered greater than any version (strmp(undefined, "0.0.0") = 1) */ function strcmp(a: string, b: string): number; function inRange(rng: string, v: Version): boolean; /** * Filters and sort tags from latest to oldest (semver wize) * @param tags */ function sortLatestTags(tags: string[]): string[]; function bump(v: Version, bumpType: "patch" | "minor" | "major" | string): Version; function test(): void; } declare namespace ts.pxtc { const assert: typeof U.assert; const oops: typeof U.oops; export import U = pxtc.Util; const ON_START_TYPE = "pxt-on-start"; const ON_START_COMMENT = "on start"; const HANDLER_COMMENT = "code goes here"; const TS_STATEMENT_TYPE = "typescript_statement"; const TS_DEBUGGER_TYPE = "debugger_keyword"; const TS_BREAK_TYPE = "break_keyword"; const TS_CONTINUE_TYPE = "continue_keyword"; const TS_OUTPUT_TYPE = "typescript_expression"; const TS_RETURN_STATEMENT_TYPE = "function_return"; const PAUSE_UNTIL_TYPE = "pxt_pause_until"; const COLLAPSED_BLOCK = "pxt_collapsed_block"; const FUNCTION_DEFINITION_TYPE = "function_definition"; const BINARY_JS = "binary.js"; const BINARY_ASM = "binary.asm"; const BINARY_HEX = "binary.hex"; const BINARY_UF2 = "binary.uf2"; const BINARY_ELF = "binary.elf"; const BINARY_PXT64 = "binary.pxt64"; const BINARY_ESP = "binary.bin"; const BINARY_SRCMAP = "binary.srcmap"; const NATIVE_TYPE_THUMB = "thumb"; const NATIVE_TYPE_VM = "vm"; const BLOCK_TRANSLATION_CACHE_KEY = "_blocks"; interface BlocksInfo { apis: ApisInfo; blocks: SymbolInfo[]; blocksById: pxt.Map; enumsByName: pxt.Map; kindsByName: pxt.Map; } interface EnumInfo { name: string; memberName: string; blockId: string; isBitMask: boolean; isHash: boolean; firstValue?: number; initialMembers: string[]; promptHint: string; } interface KindInfo { name: string; memberName: string; createFunctionName: string; blockId: string; promptHint: string; initialMembers: string[]; } interface CompletionEntry { name: string; kind: string; qualifiedName: string; } interface CompletionInfo { entries: SymbolInfo[]; isMemberCompletion: boolean; isNewIdentifierLocation: boolean; isTypeLocation: boolean; namespace: string[]; } interface LocationInfo { fileName: string; start: number; length: number; line?: number; column?: number; endLine?: number; endColumn?: number; } interface FunctionLocationInfo extends LocationInfo { functionName: string; argumentNames?: string[]; } interface KsDiagnostic extends LocationInfo { code: number; category: DiagnosticCategory; messageText: string | DiagnosticMessageChain; } interface ConfigEntry { name: string; key: number; value: number; } type CodeLang = "py" | "blocks" | "ts"; type PosSpan = { startPos: number; endPos: number; }; interface SourceInterval { ts: PosSpan; py: PosSpan; } type LineColToPos = (line: number, col: number) => number; type PosToLineCol = (pos: number) => [number, number]; interface SourceMapHelpers { ts: { posToLineCol: PosToLineCol; lineColToPos: LineColToPos; allOverlaps: (i: PosSpan) => SourceInterval[]; smallestOverlap: (i: PosSpan) => SourceInterval | undefined; locToLoc: (thisLoc: pxtc.LocationInfo) => pxtc.LocationInfo; getText: (i: PosSpan) => string; }; py: { posToLineCol: PosToLineCol; lineColToPos: LineColToPos; allOverlaps: (i: PosSpan) => SourceInterval[]; smallestOverlap: (i: PosSpan) => SourceInterval | undefined; locToLoc: (thisLoc: pxtc.LocationInfo) => pxtc.LocationInfo; getText: (i: PosSpan) => string; }; } function BuildSourceMapHelpers(sourceMap: SourceInterval[], tsFile: string, pyFile: string): SourceMapHelpers; interface CompileResult { outfiles: pxt.Map; diagnostics: KsDiagnostic[]; success: boolean; times: pxt.Map; breakpoints?: Breakpoint[]; procCallLocations?: pxtc.LocationInfo[]; procDebugInfo?: ProcDebugInfo[]; blocksInfo?: BlocksInfo; blockSourceMap?: pxt.blocks.BlockSourceInterval[]; usedSymbols?: pxt.Map; usedArguments?: pxt.Map; usedParts?: string[]; needsFullRecompile?: boolean; saveOnly?: boolean; userContextWindow?: Window; downloadFileBaseName?: string; headerId?: string; confirmAsync?: (confirmOptions: {}) => Promise; configData?: ConfigEntry[]; sourceMap?: SourceInterval[]; globalNames?: pxt.Map; builtVariants?: string[]; fileSystem?: pxt.Map; } interface Breakpoint extends LocationInfo { id: number; isDebuggerStmt: boolean; binAddr?: number; } interface CellInfo { name: string; type: string; index: number; } interface ProcCallInfo { procIndex: number; callLabel: string; addr: number; stack: number; } interface ProcDebugInfo { name: string; idx: number; bkptLoc: number; codeStartLoc: number; codeEndLoc: number; locals: CellInfo[]; args: CellInfo[]; localsMark: number; calls: ProcCallInfo[]; size: number; } const enum BitSize { None = 0, Int8 = 1, UInt8 = 2, Int16 = 3, UInt16 = 4, Int32 = 5, UInt32 = 6 } function computeUsedParts(resp: CompileResult, filter?: "onlybuiltin" | "ignorebuiltin", force?: boolean): string[]; function buildSimJsInfo(compileResult: pxtc.CompileResult): pxtc.BuiltSimJsInfo; /** * Unlocalized category name for a symbol */ function blocksCategory(si: SymbolInfo): string; function getBlocksInfo(info: ApisInfo, categoryFilters?: string[]): BlocksInfo; function tsSnippetToPySnippet(param: string, symbol?: SymbolInfo): string; let apiLocalizationStrings: pxt.Map; function localizeApisAsync(apis: pxtc.ApisInfo, mainPkg: pxt.MainPackage): Promise; function getBlockTranslationsCacheKey(key: string): string | undefined; function emptyExtInfo(): ExtensionInfo; function parseCommentString(cmt: string): CommentAttrs; function parameterTypeIsArrowFunction(pr: pxtc.ParameterDesc): boolean; function updateBlockDef(attrs: CommentAttrs): void; function parseBlockDefinition(def: string): ParsedBlockDef; interface ChecksumBlock { magic: number; endMarkerPos: number; endMarker: number; regions: { start: number; length: number; checksum: number; }[]; } function parseChecksumBlock(buf: ArrayLike, pos?: number): ChecksumBlock; namespace UF2 { const UF2_MAGIC_START0 = 171066965; const UF2_MAGIC_START1 = 2656915799; const UF2_MAGIC_END = 179400496; const UF2_FLAG_NONE = 0; const UF2_FLAG_NOFLASH = 1; const UF2_FLAG_FILE = 4096; const UF2_FLAG_FAMILY_ID_PRESENT = 8192; interface Block { flags: number; targetAddr: number; payloadSize: number; blockNo: number; numBlocks: number; fileSize: number; familyId: number; filename?: string; data: Uint8Array; } function parseBlock(block: Uint8Array): Block; function parseFile(blocks: Uint8Array): Block[]; interface ShiftedBuffer { start: number; buf: Uint8Array; } function toBin(blocks: Uint8Array, endAddr?: number): ShiftedBuffer; function readBytes(blocks: Block[], addr: number, length: number): Uint8Array; interface BlockFile { currBlock: Uint8Array; currPtr: number; blocks: Uint8Array[]; ptrs: number[]; filename?: string; filesize: number; familyId: number; } function newBlockFile(familyId?: string | number): BlockFile; function finalizeFile(f: BlockFile): void; function concatFiles(fs: BlockFile[]): BlockFile; function serializeFile(f: BlockFile): string; function readBytesFromFile(f: BlockFile, addr: number, length: number): Uint8Array; function writeBytes(f: BlockFile, addr: number, bytes: ArrayLike, flags?: number): void; function writeHex(f: BlockFile, hex: string[]): void; } } declare namespace ts.pxtc.service { interface OpArg { fileName?: string; fileContent?: string; infoType?: InfoType; position?: number; wordStartPos?: number; wordEndPos?: number; options?: CompileOptions; search?: SearchOptions; format?: FormatOptions; blocks?: BlocksOptions; extensions?: ExtensionsOptions; projectSearch?: ProjectSearchOptions; snippet?: SnippetOptions; runtime?: pxt.RuntimeOptions; light?: boolean; } interface SnippetOptions { qName: string; python?: boolean; } interface SearchOptions { subset?: pxt.Map; term: string; localizedApis?: ApisInfo; localizedStrings?: pxt.Map; } interface FormatOptions { input: string; pos: number; } enum ExtensionType { Bundled = 1, Github = 2, ShareScript = 3 } interface ExtensionMeta { name: string; displayName?: string; fullRepo?: string; description?: string; imageUrl?: string; type?: ExtensionType; learnMoreUrl?: string; pkgConfig?: pxt.PackageConfig; repo?: pxt.github.GitRepo; scriptInfo?: pxt.Cloud.JsonScript; } interface SearchInfo { id: string; name: string; qName?: string; block?: string; namespace?: string; jsdoc?: string; field?: [string, string]; localizedCategory?: string; builtinBlock?: boolean; params?: string; dropdownOptions?: string; } interface ProjectSearchOptions { term: string; headers: ProjectSearchInfo[]; } interface ProjectSearchInfo { name: string; id?: string; } interface BlocksOptions { bannedCategories?: string[]; } interface ExtensionsOptions { srcs: ExtensionMeta[]; } } declare namespace pxt.shell { enum EditorLayoutType { IDE = 0, Sandbox = 1, Widget = 2, Controller = 3 } enum ControllerMode { None = 0, Basic = 1, App = 2 } function layoutTypeClass(): string; function isSandboxMode(): boolean; function isTimeMachineEmbed(): boolean; function isReadOnly(): boolean; function isNoProject(): boolean; function isControllerMode(): boolean; function getControllerMode(): ControllerMode; function isPyLangPref(): boolean; function getEditorLanguagePref(): string; function setEditorLanguagePref(lang: string): void; function getToolboxAnimation(): string; function setToolboxAnimation(): void; function hasHomeScreen(): boolean; } declare namespace pxt.skillmap { type ScriptText = pxt.Map; interface Project { header?: pxt.workspace.Header; text?: ScriptText; deleted?: boolean; } interface WorkspaceProvider { initAsync(): Promise; getProjectAsync(headerId: string): Promise; saveProjectAsync(project: Project): Promise; getUserStateAsync(): Promise; saveUserStateAsync(user: U): Promise; } const USER_VERSION = "0.0.1"; class IndexedDBWorkspace implements WorkspaceProvider { static version: number; static databaseName: string; static projectTable: string; static projectKey: string; static userTable: string; static userKey: string; db: BrowserUtils.IDBWrapper; constructor(); initAsync(): Promise; getAllProjectsAsync(): Promise; deleteProjectAsync(headerId: string): Promise; getProjectAsync(headerId: string): Promise; saveProjectAsync(project: Project): Promise; getUserStateAsync(): Promise; saveUserStateAsync(user: U): Promise; } } declare namespace pxt.assets { type SoundWaveForm = "square" | "sine" | "triangle" | "noise" | "sawtooth"; type SoundInterpolation = "linear" | "curve" | "logarithmic"; type SoundEffect = "vibrato" | "tremolo" | "warble" | "none"; interface Sound { wave: SoundWaveForm; interpolation: SoundInterpolation; effect: SoundEffect; startFrequency: number; endFrequency: number; startVolume: number; endVolume: number; duration: number; } const MAX_FREQUENCY = 5000; const MAX_VOLUME = 255; function renderSoundPath(sound: pxt.assets.Sound, width: number, height: number): string; function renderWaveSnapshot(frequency: number, volume: number, wave: SoundWaveForm, width: number, height: number, timeBase: number): string; function soundToInstructionBuffer(sound: Sound, fxSteps: number, fxRange: number): Uint8Array; } declare namespace pxt.streams { interface JsonStreamField { name: string; sum: number; min: number; max: number; count: number; } interface JsonStreamMeta { fields: JsonStreamField[]; size: number; rows: number; batches: number; } interface JsonStream { kind: string; id: string; time: number; name?: string; meta: JsonStreamMeta; privatekey?: string; } interface JsonStreamPayload { fields: string[]; values: number[][]; } interface JsonStreamPayloadResponse { meta: JsonStreamMeta; quotaUsedHere: number; quotaLeft: number; } interface JsonStreamData { fields: JsonStreamField[]; values: number[][]; continuation?: string; continuationUrl?: string; } function createStreamAsync(target: string, name?: string): Promise; function postPayloadAsync(stream: JsonStream, data: JsonStreamPayload): Promise; } declare namespace pxt.svgUtil { type Map = { [index: string]: T; }; type PointerHandler = () => void; enum PatternUnits { userSpaceOnUse = 0, objectBoundingBox = 1 } enum LengthUnit { em = 0, ex = 1, px = 2, in = 3, cm = 4, mm = 5, pt = 6, pc = 7, percent = 8 } class BaseElement { el: T; protected titleElement: SVGTitleElement; constructor(type: string); attr(attributes: Map): this; setAttribute(name: string, value: string | number | boolean): this; setAttributeNS(ns: string, name: string, value: string | number | boolean): this; id(id: string): this; setClass(...classes: string[]): this; appendClass(className: string): this; removeClass(className: string): void; title(text: string): void; setVisible(visible: boolean): this; } class DrawContext extends BaseElement { draw(type: "text"): Text; draw(type: "circle"): Circle; draw(type: "rect"): Rect; draw(type: "line"): Line; draw(type: "polygon"): Polygon; draw(type: "polyline"): Polyline; draw(type: "path"): Path; element(type: "text", cb: (newElement: Text) => void): this; element(type: "circle", cb: (newElement: Circle) => void): this; element(type: "rect", cb: (newElement: Rect) => void): this; element(type: "line", cb: (newElement: Line) => void): this; element(type: "polygon", cb: (newElement: Polygon) => void): this; element(type: "polyline", cb: (newElement: Polyline) => void): this; element(type: "path", cb: (newElement: Path) => void): this; group(): Group; appendChild(child: BaseElement): void; onDown(handler: PointerHandler): this; onUp(handler: PointerHandler): this; onMove(handler: PointerHandler): this; onEnter(handler: (isDown: boolean) => void): this; onLeave(handler: PointerHandler): this; onClick(handler: PointerHandler): this; } class SVG extends DrawContext { defs: DefsElement; constructor(parent?: Element); define(cb: (defs: DefsElement) => void): this; } class Group extends DrawContext { top: number; left: number; scaleFactor: number; constructor(parent?: SVGElement); translate(x: number, y: number): this; scale(factor: number): this; def(): DefsElement; style(): StyleElement; private updateTransform; } class Pattern extends DrawContext { constructor(); units(kind: PatternUnits): this; contentUnits(kind: PatternUnits): this; size(width: number, height: number): this; } class DefsElement extends BaseElement { constructor(parent: SVGElement); create(type: "path", id: string): Path; create(type: "pattern", id: string): Pattern; create(type: "radialGradient", id: string): RadialGradient; create(type: "linearGradient", id: string): LinearGradient; create(type: "clipPath", id: string): ClipPath; } class StyleElement extends BaseElement { constructor(parent: SVGElement); content(css: string): void; } class Drawable extends DrawContext { at(x: number, y: number): this; moveTo(x: number, y: number): this; fill(color: string, opacity?: number): this; opacity(opacity: number): this; stroke(color: string, width?: number): this; strokeWidth(width: number): this; strokeOpacity(opacity: number): this; clipPath(url: string): this; } class Text extends Drawable { constructor(text?: string); text(text: string): this; fontFamily(family: string): this; fontSize(size: number, units: LengthUnit): this; offset(dx: number, dy: number, units: LengthUnit): this; anchor(type: "start" | "middle" | "end" | "inherit"): this; } class Rect extends Drawable { constructor(); width(width: number, unit?: LengthUnit): this; height(height: number, unit?: LengthUnit): this; corner(radius: number): this; corners(rx: number, ry: number): this; size(width: number, height: number, unit?: LengthUnit): this; } class Circle extends Drawable { constructor(); at(cx: number, cy: number): this; radius(r: number): this; } class Line extends Drawable { constructor(); at(x1: number, y1: number, x2?: number, y2?: number): this; from(x1: number, y1: number): this; to(x2: number, y2: number): this; } class PolyElement extends Drawable { points(points: string): this; with(points: { x: number; y: number; }[]): this; } class Polyline extends PolyElement { constructor(); } class Polygon extends PolyElement { constructor(); } class Path extends Drawable { d: PathContext; constructor(); update(): this; path(cb: (d: PathContext) => void): this; setD(d: string): this; } class Image extends Drawable { constructor(); src(url: string): this; width(width: number, unit?: LengthUnit): this; height(height: number, unit?: LengthUnit): this; size(width: number, height: number, unit?: LengthUnit): this; } class Gradient extends BaseElement { units(kind: PatternUnits): this; stop(offset: number, color?: string, opacity?: string): this; } class LinearGradient extends Gradient { constructor(); start(x1: number, y1: number): this; end(x2: number, y2: number): this; } class RadialGradient extends Gradient { constructor(); center(cx: number, cy: number): this; focus(fx: number, fy: number, fr: number): this; radius(r: number): this; } class ClipPath extends DrawContext { constructor(); clipPathUnits(objectBoundingBox: boolean): this; } type OperatorSymbol = "m" | "M" | "l" | "L" | "c" | "C" | "q" | "Q" | "T" | "t" | "S" | "s" | "z" | "Z" | "A" | "a"; interface PathOp { op: OperatorSymbol; args: number[]; } class PathContext { private ops; clear(): void; moveTo(x: number, y: number): this; moveBy(dx: number, dy: number): this; lineTo(x: number, y: number): this; lineBy(dx: number, dy: number): this; cCurveTo(c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): this; cCurveBy(dc1x: number, dc1y: number, dc2x: number, dc2y: number, dx: number, dy: number): this; qCurveTo(cx: number, cy: number, x: number, y: number): this; qCurveBy(dcx: number, dcy: number, dx: number, dy: number): this; sCurveTo(cx: number, cy: number, x: number, y: number): this; sCurveBy(dcx: number, dcy: number, dx: number, dy: number): this; tCurveTo(x: number, y: number): this; tCurveBy(dx: number, dy: number): this; arcTo(rx: number, ry: number, xRotate: number, large: boolean, sweepClockwise: boolean, x: number, y: number): this; arcBy(rx: number, ry: number, xRotate: number, large: boolean, sweepClockwise: boolean, x: number, y: number): this; close(): this; toAttribute(): string; private op; } } declare namespace pxt.svgUtil.events { function isTouchEnabled(): boolean; function hasPointerEvents(): boolean; function down(el: SVGElement, handler: () => void): void; function up(el: SVGElement, handler: () => void): void; function enter(el: SVGElement, handler: (isDown: boolean) => void): void; function leave(el: SVGElement, handler: () => void): void; function move(el: SVGElement, handler: () => void): void; function click(el: SVGElement, handler: () => void): void; } declare namespace pxt.svgUtil.helpers { class CenteredText extends Text { protected cx: number; protected cy: number; protected fontSizePixels: number; at(cx: number, cy: number): this; text(text: string, fontSizePixels?: number): this; protected rePosition(): void; } } declare namespace pxt.editor { let initExtensionsAsync: (opts: pxt.editor.ExtensionOptions) => Promise; let initFieldExtensionsAsync: (opts: pxt.editor.FieldExtensionOptions) => Promise; interface ExtensionOptions { } interface FieldExtensionResult { } interface ExtensionResult { } interface FieldExtensionOptions { } } declare namespace pxt { export const IMAGE_MIME_TYPE = "image/x-mkcd-f4"; export const TILEMAP_MIME_TYPE = "application/mkcd-tilemap"; export const ANIMATION_MIME_TYPE = "application/mkcd-animation"; export const SONG_MIME_TYPE = "application/mkcd-song"; export const JSON_MIME_TYPE = "application/json"; export const enum AssetType { Image = "image", Tile = "tile", Tilemap = "tilemap", Animation = "animation", Song = "song", Json = "json" } export interface AssetMetadata { displayName?: string; tags?: string[]; blockIDs?: string[]; temporaryInfo?: TemporaryAssetInfo; package?: string; } export interface TemporaryAssetInfo { blockId: string; fieldName: string; } export type Asset = ProjectImage | Tile | Animation | ProjectTilemap | Song | JsonAsset; export interface BaseAsset { internalID: number; id: string; meta: AssetMetadata; previewURI?: string; } export interface ProjectImage extends BaseAsset { type: AssetType.Image; jresData: string; bitmap: pxt.sprite.BitmapData; } export interface Tile extends BaseAsset { type: AssetType.Tile; jresData: string; bitmap: pxt.sprite.BitmapData; isProjectTile?: boolean; } export interface Animation extends BaseAsset { type: AssetType.Animation; frames: pxt.sprite.BitmapData[]; flippedHorizontal?: boolean; frameIds?: string[]; framePreviewURIs?: string[]; interval: number; } export interface TileSet { tileWidth: number; tiles: Tile[]; } export interface TileSetCollection { extensionID: string; tileSets: TileSet[]; } export interface ProjectTilemap extends BaseAsset { type: AssetType.Tilemap; data: pxt.sprite.TilemapData; } export interface Song extends BaseAsset { type: AssetType.Song; song: assets.music.Song; } export interface JsonAsset extends BaseAsset { type: AssetType.Json; data: any; fileName?: string; } export interface TilemapSnapshot { revision: number; projectTilemaps?: ProjectTilemap[]; projectTileSet?: TileSetCollection; takenNames?: pxt.Map; projectImages?: ProjectImage[]; } interface AssetSnapshot { revision: number; assets: pxt.Map>; } interface AssetSnapshotDiff { beforeRevision: number; afterRevision: number; assetDiffs: pxt.Map>; } interface AssetUpdateListener { internalID: number; callback: () => void; } interface AssetCollectionDiff { before: U[]; after: U[]; } class AssetCollection { readonly type: string; protected assets: U[]; protected takenNames: pxt.Map; protected listeners: AssetUpdateListener[]; constructor(type: string); add(asset: U): U; getSnapshot(filter?: (asset: U) => boolean): U[]; update(id: string, newValue: U): U; removeByID(id: string): void; getByID(id: string): U; getByDisplayName(name: string): U; getByValue(toFind: U): U; isIDTaken(id: string): boolean; clone(): AssetCollection; serializeToJRes(allJRes?: pxt.Map, filter?: (asset: U) => boolean): pxt.Map; addListener(internalID: number, listener: () => void): void; removeListener(listener: () => void): void; diff(past: AssetCollection): AssetCollectionDiff; applyDiff(diff: AssetCollectionDiff, backwards?: boolean): void; protected lookupByID(id: string): U; protected lookupByInternalID(id: number): U; protected removeByInternalID(id: number): void; protected notifyListener(internalID: number): void; protected generateNewDisplayName(prefix: string): string; } export class TilemapProject { needsRebuild: boolean; protected static nextRevision: number; protected extensionTileSets: TileSetCollection[]; protected state: AssetSnapshot; protected committedState: AssetSnapshot; protected gallery: AssetSnapshot; protected undoStack: AssetSnapshotDiff[]; protected redoStack: AssetSnapshotDiff[]; protected nextID: number; protected nextInternalID: number; constructor(); getNewInternalId(): number; createNewImage(width?: number, height?: number): ProjectImage; createNewAnimation(width?: number, height?: number): Animation; createNewAnimationFromData(frames: pxt.sprite.BitmapData[], interval?: number, displayName?: string): Animation; getGalleryTiles(tileWidth: number): TileSet[] | null; getProjectImages(): ProjectImage[]; getProjectTiles(tileWidth: number, createIfMissing: boolean): TileSet | null; createNewTile(data: pxt.sprite.BitmapData, id?: string, displayName?: string): Tile; createNewProjectImage(data: pxt.sprite.BitmapData, displayName?: string): ProjectImage; createNewSong(data: pxt.assets.music.Song, displayName?: string): Song; createNewJsonAsset(data: any, fileName?: string, displayName?: string): JsonAsset; updateTile(tile: pxt.Tile): Tile; deleteTile(id: string): void; getProjectTilesetJRes(projectFiles?: pxt.Map<{ content: string; }>): Map; getProjectAssetsJRes(): Map; getTilemap(id: string): ProjectTilemap; updateTilemap(id: string, data: pxt.sprite.TilemapData): ProjectTilemap; createNewTilemap(name: string, tileWidth: number, width?: number, height?: number): [string, pxt.sprite.TilemapData]; blankTilemap(tileWidth: number, width?: number, height?: number): sprite.TilemapData; resolveTile(id: string): Tile; resolveProjectTileByInternalID(id: number): Tile; resolveTileByBitmap(data: pxt.sprite.BitmapData): Tile; getTransparency(tileWidth: number): Tile; createNewTilemapFromData(data: pxt.sprite.TilemapData, name?: string): [string, pxt.sprite.TilemapData]; protected cloneState(): AssetSnapshot; undo(): void; redo(): void; pushUndo(): void; revision(): number; encodeTilemap(tilemap: sprite.TilemapData, id: string): JRes; forceUpdate(): void; isNameTaken(assetType: AssetType, name: string): boolean; /** * Checks if the asset is referenced anywhere in the user's code. * If an asset is referenced in any block we return true, as well * as if a tile is used in any tilemap. * * Ways to reference an asset in TS/Python: * * TILES: * myTiles.shortId * assets.tile`shortId` * assets.tile`displayName` * * IMAGES: * assets.image`shortId` * assets.image`displayName` * * ANIMATIONS: * assets.animation`shortId` * assets.animation`displayName` * * SONGS: * assets.song`shortId` * assets.song`displayName` * * TILEMAPS: * tilemap`shortId` * * @param skipIDs string[] a list of string ids (block id, asset id, or file name) to ignore **/ isAssetUsed(asset: Asset, files?: pxt.Map<{ content: string; }>, skipIDs?: string[]): boolean; lookupAsset(assetType: AssetType.Image, name: string): ProjectImage; lookupAsset(assetType: AssetType.Tile, name: string): Tile; lookupAsset(assetType: AssetType.Tilemap, name: string): ProjectTilemap; lookupAsset(assetType: AssetType.Animation, name: string): Animation; lookupAsset(assetType: AssetType.Song, name: string): Song; lookupAsset(assetType: AssetType.Json, name: string): JsonAsset; lookupAsset(assetType: AssetType, name: string): Asset; lookupAssetByName(assetType: AssetType.Image, name: string): ProjectImage; lookupAssetByName(assetType: AssetType.Tile, name: string): Tile; lookupAssetByName(assetType: AssetType.Tilemap, name: string): ProjectTilemap; lookupAssetByName(assetType: AssetType.Animation, name: string): Animation; lookupAssetByName(assetType: AssetType.Song, name: string): Song; lookupAssetByName(assetType: AssetType.Json, name: string): JsonAsset; lookupAssetByName(assetType: AssetType, name: string): Asset; lookupAssetByValue(assetType: AssetType.Image, toFind: ProjectImage): ProjectImage; lookupAssetByValue(assetType: AssetType.Tile, toFind: Tile): Tile; lookupAssetByValue(assetType: AssetType.Tilemap, toFind: ProjectTilemap): ProjectTilemap; lookupAssetByValue(assetType: AssetType.Animation, toFind: Animation): Animation; lookupAssetByValue(assetType: AssetType.Song, toFind: Song): Song; lookupAssetByValue(assetType: AssetType.Json, toFind: Song): JsonAsset; lookupAssetByValue(assetType: AssetType, toFind: Asset): Asset; getAssets(type: AssetType.Image): ProjectImage[]; getAssets(type: AssetType.Tile): Tile[]; getAssets(type: AssetType.Tilemap): ProjectTilemap[]; getAssets(type: AssetType.Animation): Animation[]; getAssets(type: AssetType.Song): Song[]; getAssets(type: AssetType.Json): JsonAsset[]; getAssets(type: AssetType): Asset[]; getGalleryAssets(type: AssetType.Image): ProjectImage[]; getGalleryAssets(type: AssetType.Tile): Tile[]; getGalleryAssets(type: AssetType.Tilemap): ProjectTilemap[]; getGalleryAssets(type: AssetType.Animation): Animation[]; getGalleryAssets(type: AssetType.Song): Song[]; getGalleryAssets(type: AssetType.Json): JsonAsset[]; getGalleryAssets(type: AssetType): Asset[]; lookupBlockAsset(assetType: AssetType.Image, blockID: string): ProjectImage; lookupBlockAsset(assetType: AssetType.Tile, blockID: string): Tile; lookupBlockAsset(assetType: AssetType.Tilemap, blockID: string): ProjectTilemap; lookupBlockAsset(assetType: AssetType.Animation, blockID: string): Animation; lookupBlockAsset(assetType: AssetType.Song, blockID: string): Song; lookupBlockAsset(assetType: AssetType.Json, blockID: string): JsonAsset; lookupBlockAsset(assetType: AssetType, blockID: string): Asset; updateAsset(asset: ProjectImage): ProjectImage; updateAsset(asset: Tile): Tile; updateAsset(asset: ProjectTilemap): ProjectTilemap; updateAsset(asset: Animation): Animation; updateAsset(asset: Song): Song; updateAsset(asset: JsonAsset): JsonAsset; updateAsset(asset: Asset): Asset; duplicateAsset(asset: ProjectImage, displayName?: string): ProjectImage; duplicateAsset(asset: Tile, displayName?: string): Tile; duplicateAsset(asset: ProjectTilemap, displayName?: string): ProjectTilemap; duplicateAsset(asset: Animation, displayName?: string): Animation; duplicateAsset(asset: Song, displayName?: string): Song; duplicateAsset(asset: JsonAsset, displayName?: string): JsonAsset; duplicateAsset(asset: Asset, displayName?: string): Asset; removeAsset(asset: Asset): void; addChangeListener(asset: Asset, listener: () => void): void; removeChangeListener(type: AssetType, listener: () => void): void; loadPackage(pack: MainPackage): void; loadTilemapJRes(jres: Map, skipDuplicates?: boolean, gallery?: boolean): void; loadAssetsJRes(jres: Map, gallery?: boolean): void; removeInactiveBlockAssets(activeBlockIDs: string[]): void; clone(): TilemapProject; saveGallerySnapshot(): AssetSnapshot; loadGallerySnapshot(snapshot: AssetSnapshot): void; protected generateImage(entry: JRes, type: AssetType.Image): ProjectImage; protected generateImage(entry: JRes, type: AssetType.Tile): Tile; protected generateSong(entry: JRes): Song; protected generateJsonAsset(entry: JRes): JsonAsset; protected generateAnimation(entry: JRes): [Animation, boolean]; protected inflateAnimation(animation: Animation, assets: (Tile | ProjectImage | Animation | Song | JsonAsset)[]): Animation; generateNewID(type: AssetType): string; generateNewName(type: AssetType, name?: string): string; protected generateNewIDInternal(type: AssetType, varPrefix: string, namespaceString?: string): string; protected onChange(): void; protected readImages(allJRes: Map, isProjectFile?: boolean): (Tile | ProjectImage | Animation | Song | JsonAsset)[]; protected cleanupTemporaryAssets(): void; protected getAssetCollection(type: AssetType.Animation, gallery?: boolean): AssetCollection; protected getAssetCollection(type: AssetType.Image, gallery?: boolean): AssetCollection; protected getAssetCollection(type: AssetType.Song, gallery?: boolean): AssetCollection; protected getAssetCollection(type: AssetType.Tile, gallery?: boolean): AssetCollection; protected getAssetCollection(type: AssetType.Tilemap, gallery?: boolean): AssetCollection; protected getAssetCollection(type: AssetType.Json, gallery?: boolean): AssetCollection; protected getAssetCollection(type: AssetType, gallery?: boolean): AssetCollection; } export function emitGalleryDeclarations(jres: pxt.Map, namespaceName: string): [pxt.Map, string]; export function emitTilemapsFromJRes(jres: pxt.Map): string; export function emitProjectImages(jres: pxt.Map): string; export function cloneAsset(asset: U, includeEditorData?: boolean): U; export function assetEquals(a: Asset, b: Asset, valueOnly?: boolean): boolean; export function validateAssetName(name: string): boolean; export function getTSReferenceForAsset(asset: pxt.Asset, isPython?: boolean): string; export function parseAssetTSReference(ts: string): { type: string; name: string; }; export function lookupProjectAssetByTSReference(ts: string, project: TilemapProject): Tile | ProjectImage | Animation | ProjectTilemap | Song | JsonAsset; export function getDefaultAssetDisplayName(type: pxt.AssetType): string; export function getShortIDForAsset(asset: pxt.Asset): string; export function validateAsset(asset: pxt.Asset): boolean; export function patchTemporaryAsset(oldValue: pxt.Asset, newValue: pxt.Asset, project: TilemapProject): Asset; export {}; } declare namespace pxt.toolbox { const blockColors: Map; const blockIcons: Map; function appendToolboxIconCss(className: string, i: string): void; function getNamespaceColor(ns: string): string; function getNamespaceIcon(ns: string): string; function advancedTitle(): string; function addPackageTitle(): string; function recipesTitle(): string; /** * Convert blockly hue to rgb */ function convertColor(colour: string): string; function hueToRgb(hue: number): string; function fadeColor(hex: string, luminosity: number, lighten: boolean): string; /** * Calculates an accessible background color assuming a foreground color of white and * caches the result. Does not clear the cache, but this shouldn't be much of a memory * concern since we only cache colors that are used in the toolbox. */ function getAccessibleBackground(color: string): string; } declare namespace pxt.tutorial { function parseTutorial(tutorialmd: string): TutorialInfo; function getMetadataRegex(): RegExp; function highlight(pre: HTMLElement): void; function getTutorialOptions(md: string, tutorialId: string, filename: string, reportId: string, recipe: boolean): { options: pxt.tutorial.TutorialOptions; editor: string; }; function parseCachedTutorialInfo(json: string, id?: string): Promise; function resolveLocalizedMarkdown(ghid: pxt.github.ParsedRepo, files: pxt.Map, fileName?: string): string; function parseAssetJson(json: string): pxt.Map; function parseSimThemeJson(json: string): Partial; function getTutorialHighlightedBlocks(tutorial: TutorialOptions): Promise> | undefined>; function getTutorialValidateBlocks(tutorial: TutorialOptions): Promise> | undefined>; function getRequiredBlockCounts(stepBlocks: pxt.Map): pxt.Map; function getTutorialStepHash(tutorial: TutorialOptions): string; function shouldFilterProject(metadata: pxt.tutorial.TutorialMetadata): boolean; } declare namespace ts.pxtc { function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; enum ScriptTarget { ES3 = 0, ES5 = 1, ES6 = 2, ES2015 = 2, Latest = 2 } const enum CharacterCodes { nullCharacter = 0, maxAsciiCharacter = 127, lineFeed = 10, carriageReturn = 13, lineSeparator = 8232, paragraphSeparator = 8233, nextLine = 133, space = 32, nonBreakingSpace = 160, enQuad = 8192, emQuad = 8193, enSpace = 8194, emSpace = 8195, threePerEmSpace = 8196, fourPerEmSpace = 8197, sixPerEmSpace = 8198, figureSpace = 8199, punctuationSpace = 8200, thinSpace = 8201, hairSpace = 8202, zeroWidthSpace = 8203, narrowNoBreakSpace = 8239, ideographicSpace = 12288, mathematicalSpace = 8287, ogham = 5760, _ = 95, $ = 36, _0 = 48, _1 = 49, _2 = 50, _3 = 51, _4 = 52, _5 = 53, _6 = 54, _7 = 55, _8 = 56, _9 = 57, a = 97, b = 98, c = 99, d = 100, e = 101, f = 102, g = 103, h = 104, i = 105, j = 106, k = 107, l = 108, m = 109, n = 110, o = 111, p = 112, q = 113, r = 114, s = 115, t = 116, u = 117, v = 118, w = 119, x = 120, y = 121, z = 122, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, ampersand = 38, asterisk = 42, at = 64, backslash = 92, backtick = 96, bar = 124, caret = 94, closeBrace = 125, closeBracket = 93, closeParen = 41, colon = 58, comma = 44, dot = 46, doubleQuote = 34, equals = 61, exclamation = 33, greaterThan = 62, hash = 35, lessThan = 60, minus = 45, openBrace = 123, openBracket = 91, openParen = 40, percent = 37, plus = 43, question = 63, semicolon = 59, singleQuote = 39, slash = 47, tilde = 126, backspace = 8, formFeed = 12, byteOrderMark = 65279, tab = 9, verticalTab = 11 } function isIdentifierStart(ch: number, languageVersion: ts.pxtc.ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ts.pxtc.ScriptTarget): boolean; const reservedWords: string[]; const keywordTypes: string[]; function escapeIdentifier(name: string): string; function isUnicodeIdentifierStart(code: number, languageVersion: ts.pxtc.ScriptTarget): boolean; enum DiagnosticCategory { Warning = 0, Error = 1, Message = 2 } } declare namespace pxt.webBluetooth { function isAvailable(): boolean; function hasConsole(): boolean; function hasPartialFlash(): boolean; function isValidUUID(id: string): boolean; class BLERemote { id: string; aliveToken: pxt.Util.CancellationToken; connectionTimeout: number; private connectPromise; constructor(id: string, aliveToken: pxt.Util.CancellationToken); protected debug(msg: string): void; protected alivePromise(p: Promise): Promise; protected cancelConnect(): void; protected createConnectPromise(): Promise; connectAsync(): Promise; disconnect(): void; kill(): void; } class BLEService extends BLERemote { protected device: BLEDevice; autoReconnect: boolean; autoReconnectDelay: number; disconnectOnAutoReconnect: boolean; private reconnectPromise; private failedConnectionServicesVersion; constructor(id: string, device: BLEDevice, autoReconnect: boolean); handleDisconnected(event: Event): void; private exponentialBackoffConnectAsync; } class BLETXService extends BLEService { protected device: BLEDevice; private serviceUUID; private txCharacteristicUUID; service: BluetoothRemoteGATTService; txCharacteristic: BluetoothRemoteGATTCharacteristic; constructor(id: string, device: BLEDevice, serviceUUID: BluetoothServiceUUID, txCharacteristicUUID: BluetoothServiceUUID); protected createConnectPromise(): Promise; handlePacket(data: DataView): void; private handleValueChanged; disconnect(): void; } class HF2Service extends BLETXService { protected device: BLEDevice; static SERVICE_UUID: BluetoothServiceUUID; static CHARACTERISTIC_TX_UUID: BluetoothCharacteristicUUID; static BLEHF2_FLAG_SERIAL_OUT: number; static BLEHF2_FLAG_SERIAL_ERR: number; constructor(device: BLEDevice); handlePacket(data: DataView): void; } class UARTService extends BLETXService { protected device: BLEDevice; static SERVICE_UUID: BluetoothServiceUUID; static CHARACTERISTIC_TX_UUID: BluetoothCharacteristicUUID; constructor(device: BLEDevice); handlePacket(data: DataView): void; } class PartialFlashingService extends BLEService { protected device: BLEDevice; static SERVICE_UUID: string; static CHARACTERISTIC_UUID: string; static REGION_INFO: number; static FLASH_DATA: number; static PACKET_OUT_OF_ORDER: number; static PACKET_WRITTEN: number; static END_OF_TRANSMISSION: number; static STATUS: number; static RESET: number; static MODE_PAIRING: number; static MODE_APPLICATION: number; static REGION_SOFTDEVICE: number; static REGION_DAL: number; static REGION_MAKECODE: number; static MAGIC_MARKER: Uint8Array; static CHUNK_MIN_DELAY: number; static CHUNK_MAX_DELAY: number; private pfCharacteristic; private state; private chunkDelay; private version; private mode; private regions; private hex; private bin; private magicOffset; private dalHash; private makeCodeHash; private flashOffset; private flashPacketNumber; private flashPacketToken; private flashResolve; private flashReject; constructor(device: BLEDevice); private clearFlashData; protected createConnectPromise(): Promise; disconnect(): void; private findMarker; flashAsync(hex: string): Promise; private createFlashPromise; private checkStateTransition; private handleCharacteristic; private flashNextPacket; } class BLEDevice extends BLERemote { device: BluetoothDevice; uartService: UARTService; hf2Service: HF2Service; partialFlashingService: PartialFlashingService; private services; private pendingResumeLogOnDisconnection; servicesVersion: number; constructor(device: BluetoothDevice); startServices(): void; pauseLog(): void; resumeLogOnDisconnection(): void; private resumeLog; get isPaired(): boolean; get name(): string; get connected(): boolean; get gatt(): BluetoothRemoteGATTServer; protected createConnectPromise(): Promise; handleServiceAdded(event: Event): void; handleServiceRemoved(event: Event): void; handleServiceChanged(event: Event): void; handleDisconnected(event: Event): void; disconnect(): void; } let bleDevice: BLEDevice; function isPaired(): boolean; function pairAsync(): Promise; function flashAsync(resp: pxtc.CompileResult, d?: pxt.commands.DeployOptions): Promise; } interface Navigator { readonly usb?: { getDevices(): Promise; requestDevice(options?: pxt.usb.USBDeviceRequestOptions): Promise; addEventListener(type: "connect" | "disconnect", listener: (ev: pxt.usb.USBConnectionEvent) => any, useCapture?: boolean): void; removeEventListener(type: "connect" | "disconnect", callback: (ev: pxt.usb.USBConnectionEvent) => any, useCapture?: boolean): void; }; } declare namespace pxt.usb { /** * For local testing of WebUSB, be sure to (temporarily) * enable the browser command line flag `--disable-webusb-security` * to allow localhost (non-https) access to the APIs. * If possible it might be easiest to download a separate canary build * for chrome / edge to run. * https://chromium.googlesource.com/playground/chromium-org-site/+/refs/heads/main/for-testers/command-line-flags.md */ class USBError extends Error { constructor(msg: string); } const enum VID { ATMEL = 1003, ARDUINO = 9025, ADAFRUIT = 9114, NXP = 3368 } interface USBDeviceFilter { vendorId?: number; productId?: number; classCode?: number; subclassCode?: number; protocolCode?: number; serialNumber?: string; } interface USBDeviceRequestOptions { filters: USBDeviceFilter[]; exclusionFilters?: USBDeviceFilter[] | undefined; } interface USBConnectionEvent extends Event { device: USBDevice; } let filters: USBDeviceFilter[]; function setFilters(f: USBDeviceFilter[]): void; type USBEndpointType = "bulk" | "interrupt" | "isochronous"; type USBRequestType = "standard" | "class" | "vendor"; type USBRecipient = "device" | "interface" | "endpoint" | "other"; type USBTransferStatus = "ok" | "stall" | "babble"; type USBDirection = "in" | "out"; type BufferSource = Uint8Array; interface USBConfiguration { configurationValue: number; configurationName: string; interfaces: USBInterface[]; } interface USBInterface { interfaceNumber: number; alternate: USBAlternateInterface; alternates: USBAlternateInterface[]; claimed: boolean; } interface USBAlternateInterface { alternateSetting: number; interfaceClass: number; interfaceSubclass: number; interfaceProtocol: number; interfaceName: string; endpoints: USBEndpoint[]; } interface USBEndpoint { endpointNumber: number; direction: USBDirection; type: USBEndpointType; packetSize: number; } interface USBControlTransferParameters { requestType: USBRequestType; recipient: USBRecipient; request: number; value: number; index: number; } interface USBInTransferResult { data: { buffer: ArrayBuffer; }; status: USBTransferStatus; } interface USBOutTransferResult { bytesWritten: number; status: USBTransferStatus; } interface USBIsochronousInTransferPacket { data: DataView; status: USBTransferStatus; } interface USBIsochronousInTransferResult { data: DataView; packets: USBIsochronousInTransferPacket[]; } interface USBIsochronousOutTransferPacket { bytesWritten: number; status: USBTransferStatus; } interface USBIsochronousOutTransferResult { packets: USBIsochronousOutTransferPacket[]; } interface USBDevice { vendorId: number; productId: number; manufacturerName: string; productName: string; serialNumber: string; deviceClass: number; deviceSubclass: number; deviceProtocol: number; deviceVersionMajor: number; deviceVersionMinor: number; deviceVersionSubminor: number; usbVersionMajor: number; usbVersionMinor: number; usbVersionSubminor: number; configurations: USBConfiguration[]; opened: boolean; open(): Promise; close(): Promise; selectConfiguration(configurationValue: number): Promise; claimInterface(interfaceNumber: number): Promise; releaseInterface(interfaceNumber: number): Promise; selectAlternateInterface(interfaceNumber: number, alternateSetting: number): Promise; controlTransferIn(setup: USBControlTransferParameters, length: number): Promise; controlTransferOut(setup: USBControlTransferParameters, data?: BufferSource): Promise; clearHalt(direction: USBDirection, endpointNumber: number): Promise; transferIn(endpointNumber: number, length: number): Promise; transferOut(endpointNumber: number, data: BufferSource): Promise; isochronousTransferIn(endpointNumber: number, packetLengths: number[]): Promise; isochronousTransferOut(endpointNumber: number, data: BufferSource, packetLengths: number[]): Promise; reset(): Promise; forget?(): Promise; } function pairAsync(): Promise; function tryGetDevicesAsync(): Promise; function mkWebUSBHIDPacketIOAsync(): Promise; function forgetDeviceAsync(): Promise; let isEnabled: boolean; function setEnabled(v: boolean): void; function checkAvailableAsync(): Promise; function getReasonUnavailable(): Promise<"electron" | "notimpl" | "oldwindows" | "security" | undefined>; function isAvailable(): boolean; } declare namespace pxt.worker { function getWorker(workerFile: string): Iface; interface Iface { opAsync: (op: string, arg: any) => Promise; recvHandler: (v: any) => void; } function wrap(send: (v: any) => void): Iface; function makeWebWorker(workerFile: string): Iface; function makeWebSocket(url: string, onOOB?: (v: any) => void): Iface; } declare namespace pxt.youtube { let apiKey: string; interface PlaylistResource { items: Playlist[]; } interface Playlist { id: string; snippet: { publishedAt: string; channelId: string; title: string; description: string; thumbnails?: Thumbnails; }; } interface Thumbnail { url: string; width: number; height: number; } interface Thumbnails { default?: Thumbnail; medium?: Thumbnail; high?: Thumbnail; standard?: Thumbnail; maxres?: Thumbnail; } function playlistItemToCodeCard(video: PlaylistItem): pxt.CodeCard; function playlistInfoAsync(playlistId: string): Promise; interface PlaylistItem { snippet: { playlistId: string; title: string; description: string; publishedAt: string; thumbnails: Thumbnails; position: number; resourceId: { videoId: string; }; }; } interface PlaylistVideos { nextPageToken: string; prevPageToken: string; items: PlaylistItem[]; } function listPlaylistVideosAsync(playlistId: string): Promise; function watchUrl(videoId?: string, playlistId?: string): string; } declare namespace ts.pxtc.assembler { let debug: boolean; interface InlineError { scope: string; message: string; line: string; lineNo: number; coremsg: string; hints: string; } interface EmitResult { stack: number; opcode: number; opcode2?: number; opcode3?: number; numArgs?: number[]; error?: string; errorAt?: string; labelName?: string; } function lf(fmt: string, ...args: any[]): string; class Instruction { opcode: number; mask: number; is32bit: boolean; name: string; args: string[]; friendlyFmt: string; code: string; protected ei: AbstractProcessor; canBeShared: boolean; constructor(ei: AbstractProcessor, format: string, opcode: number, mask: number, is32bit: boolean); emit(ln: Line): EmitResult; toString(): string; } class Line { bin: File; text: string; type: string; lineNo: number; words: string[]; scope: string; location: number; instruction: Instruction; numArgs: number[]; opcode: number; stack: number; isLong: boolean; ldlitLabel: string; constructor(bin: File, text: string); getOpExt(): string; getOp(): string; update(s: string): void; } class File { constructor(ei: AbstractProcessor); baseOffset: number; finalEmit: boolean; reallyFinalEmit: boolean; checkStack: boolean; inlineMode: boolean; lookupExternalLabel: (name: string) => number; normalizeExternalLabel: (n: string) => string; ei: AbstractProcessor; lines: Line[]; private currLineNo; private realCurrLineNo; private currLine; private scope; private scopeId; errors: InlineError[]; buf: number[]; private labels; private equs; private userLabelsCache; private stackpointers; private stack; commPtr: number; peepOps: number; peepDel: number; peepCounts: pxt.Map; private stats; throwOnError: boolean; disablePeepHole: boolean; stackAtLabel: pxt.Map; private prevLabel; codeSizeStats: boolean; private labelToObject; private idToObject; private objSuspendStart; private currObject; private labelsToObjectDone; protected emitShort(op: number): void; protected emitOpCode(op: number): void; location(): number; pc(): number; useLabel(name: string): void; parseOneInt(s: string): number; private looksLikeLabel; private scopedName; lookupLabel(name: string, direct?: boolean): number; private align; pushError(msg: string, hints?: string): void; private directiveError; private emitString; private parseNumber; private parseNumbers; private emitSpace; private emitBytes; private emitHex; private handleDirective; private handleOneInstruction; private handleInstruction; buildLine(tx: string, lst: Line[]): void; private prepLines; private iterLines; getSourceMap(): pxt.Map; getCodeSizeStats(): string; getSource(clean: boolean, numStmts?: number, usableEnd?: number): string; private peepHole; private clearLabels; private peepPass; getLabels(): pxt.Map; emit(text: string): void; } class VMFile extends File { constructor(ei: AbstractProcessor); } interface Encoder { name: string; pretty: string; encode: (v: number) => number; isRegister: boolean; isImmediate: boolean; isRegList: boolean; isLabel: boolean; isWordAligned?: boolean; } abstract class AbstractProcessor { encoders: pxt.Map; instructions: pxt.Map; file: File; constructor(); toFnPtr(v: number, baseOff: number, lbl: string): number; wordSize(): number; computeStackOffset(kind: string, offset: number): number; is32bit(i: Instruction): boolean; emit32(v1: number, v2: number, actual: string): EmitResult; postProcessRelAddress(f: File, v: number): number; postProcessAbsAddress(f: File, v: number): number; peephole(ln: Line, lnNext: Line, lnNext2: Line): void; registerNo(actual: string): number; getAddressFromLabel(f: File, i: Instruction, s: string, wordAligned?: boolean): number; isPop(opcode: number): boolean; isPush(opcode: number): boolean; isAddSP(opcode: number): boolean; isSubSP(opcode: number): boolean; testAssembler(): void; expandLdlit(f: File): void; protected addEnc: (n: string, p: string, e: (v: number) => number) => Encoder; protected inrange: (max: number, v: number, e: number) => number; protected inminmax: (min: number, max: number, v: number, e: number) => number; protected inseq: (seq: number[], v: number) => number; protected inrangeSigned: (max: number, v: number, e: number) => number; protected addInst: (name: string, code: number, mask: number, is32Bit?: boolean) => Instruction; } function emitErr(msg: string, tok: string): { stack: number; opcode: number; error: string; errorAt: string; }; function expectError(ei: AbstractProcessor, asm: string): void; function tohex(n: number): string; function expect(ei: AbstractProcessor, disasm: string): void; } declare namespace pxt.Cloud { import Util = pxtc.Util; let apiRoot: string; let accessToken: string; let localToken: string; let onOffline: () => void; function hasAccessToken(): boolean; function localRequestAsync(path: string, data?: any): Promise; function useCdnApi(): boolean; function cdnApiUrl(url: string): string; function apiRequestWithCdnAsync(options: Util.HttpRequestOptions): Promise; function privateRequestAsync(options: Util.HttpRequestOptions): Promise; function privateGetTextAsync(path: string, headers?: pxt.Map): Promise; function privateGetAsync(path: string, forceLiveEndpoint?: boolean): Promise; function downloadTargetConfigAsync(): Promise; function downloadScriptFilesAsync(id: string): Promise>; function downloadScriptMetaAsync(id: string): Promise; function downloadBuiltSimJsInfoAsync(id: string): Promise; function markdownAsync(docid: string, locale?: string, propagateExceptions?: boolean, downloadTutorialBundle?: boolean): Promise; function privateDeleteAsync(path: string): Promise; function privatePostAsync(path: string, data: any, forceLiveEndpoint?: boolean): Promise; function isLoggedIn(): boolean; function isNavigatorOnline(): boolean; function isOnline(): boolean; function getServiceUrl(): string; function getUserId(): string; function parseScriptId(uri: string): string; function initRegionAsync(): Promise; function getRegion(): string; interface JsonIdObject { kind: string; id: string; } interface JsonPublication extends JsonIdObject { time: number; } interface JsonScript extends JsonPublication { shortid?: string; name: string; description: string; editor?: string; target?: string; targetVersion?: string; meta?: JsonScriptMeta; thumb?: boolean; persistId?: string; } interface JsonText { "Readme.md"?: string; "assets.json"?: string; "images.g.jres"?: string; "images.g.ts"?: string; "main.blocks"?: string; "main.ts"?: string; "pxt.json"?: string; "tilemap.g.jres"?: string; "tilemap.g.ts"?: string; } } declare namespace ts.pxtc { function f4EncodeImg(w: number, h: number, bpp: number, getPix: (x: number, y: number) => number): string; } declare namespace pxtmelody { class MelodyArray { private tempo; private numCols; private numRows; private melody; private polyphonic; constructor(tempo?: number); setTempo(tempo: number): void; getArray(): boolean[][]; setArray(array: boolean[][]): void; getColor(row: number): number; getValue(row: number, col: number): boolean; getWidth(): number; getHeight(): number; updateMelody(row: number, col: number): void; getStringRepresentation(): string; parseNotes(stringNotes: string): void; setPolyphonic(isPolyphonic: boolean): void; isPolyphonic(): boolean; resetMelody(): void; } function rowToNote(rowNum: number): string; function noteToRow(note: string): number; function getColorClass(row: number): string; } declare namespace pxtmelody { class MelodyGallery { protected contentDiv: HTMLDivElement; protected containerDiv: HTMLDivElement; protected itemBorderColor: string; protected itemBackgroundColor: string; protected value: string; protected visible: boolean; protected pending: (res: string) => void; protected playIcons: HTMLElement[]; protected selectionButtons: HTMLElement[]; protected previewButtons: HTMLElement[]; private timeouts; private numSamples; private selectedElement; private selectedColRow; private keyDownHandler; private focusHandler; private blurHandler; constructor(); keyDownListener(e: KeyboardEvent): void; focusListener(_e: FocusEvent): void; blurListener(_e: FocusEvent): void; getElement(): HTMLDivElement; getValue(): string; show(notes: (res: string) => void): void; hide(): void; clearDomReferences(): void; layout(left: number, top: number, height: number): void; getLastFocusableElement(): HTMLDivElement; protected buildDom(): void; protected initStyles(): void; protected mkButton(sample: pxtmelody.MelodyInfo, i: number, width: string, height: string): void; protected handleSelection(sample: pxtmelody.MelodyInfo): void; private playNote; private getDuration; private previewMelody; private togglePlay; stopMelody(): void; private resetPlayIcons; private createColorBlock; } } declare const getCellId: (x: number, y: number) => string; declare namespace pxtmelody { class MelodyInfo { name: string; notes: string; tempo: number; constructor(name: string, notes: string, tempo: number); } const SampleMelodies: MelodyInfo[]; }