repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
obsidian-multi-properties | github_2023 | technohiker | typescript | MultiPropPlugin.addPropsCallback | addPropsCallback(props: any) {
return (file: TFile) => {
addProperties(this.app, file, props, this.settings.overwrite);
};
} | /** Callback function to run addProperties inside iterative functions.*/ | https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L289-L293 | c7c41a571d7e85946694a97e45ba8c8b977c1413 |
obsidian-multi-properties | github_2023 | technohiker | typescript | MultiPropPlugin.removePropsCallback | removePropsCallback(props: any) {
return (file: TFile) => {
removeProperties(this.app, file, props);
};
} | /** Callback function to run removeProperties inside iterative functions. */ | https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L296-L300 | c7c41a571d7e85946694a97e45ba8c8b977c1413 |
portfolio_site | github_2023 | AlpayC | typescript | Imprint | const Imprint = () => {
const { language } = useLanguage();
return (
<React.Fragment>
{language === "DE" ? (
<article className="flex flex-col gap-6 max-w-[70vw]">
<h1>Impressum</h1>
</article>
) : (
<article className="flex flex-col gap-6 max-w-[70vw]">
<h1>Site Notice</h1>
</article>
)}
</React.Fragment>
);
}; | // import { Link } from "react-router-dom"; | https://github.com/AlpayC/portfolio_site/blob/2677889a6f23fb2be16f18a1327124600c9ab550/src/components/Imprint.tsx#L5-L21 | 2677889a6f23fb2be16f18a1327124600c9ab550 |
portfolio_site | github_2023 | AlpayC | typescript | Privacy | const Privacy = () => {
const { language } = useLanguage();
return (
<React.Fragment>
{language === "DE" ? (
<article className="flex flex-col gap-6 max-w-[70vw] break-words">
<h1>Datenschutz­erklärung</h1>
</article>
) : (
<article className="flex flex-col gap-6 max-w-[70vw] break-words">
<h1>Privacy Policy</h1>
</article>
)}
</React.Fragment>
);
}; | // import { Link } from "react-router-dom"; | https://github.com/AlpayC/portfolio_site/blob/2677889a6f23fb2be16f18a1327124600c9ab550/src/components/Privacy.tsx#L5-L21 | 2677889a6f23fb2be16f18a1327124600c9ab550 |
memo-card | github_2023 | kubk | typescript | copyToClipboardOld | function copyToClipboardOld(textToCopy: string) {
const textarea = document.createElement("textarea");
textarea.value = textToCopy;
// Move the textarea outside the viewport to make it invisible
textarea.style.position = "absolute";
textarea.style.left = "-99999999px";
// @ts-ignore
document.body.prepend(textarea);
// highlight the content of the textarea element
textarea.select();
try {
document.execCommand("copy");
} catch (err) {
console.log(err);
} finally {
textarea.remove();
}
} | // A hack for old android to get clipboard copy feature ready | https://github.com/kubk/memo-card/blob/27196793e05a4b68b2783a81352e8eba82f55a3a/src/lib/copy-to-clipboard/copy-to-clipboard.ts#L10-L31 | 27196793e05a4b68b2783a81352e8eba82f55a3a |
memo-card | github_2023 | kubk | typescript | RequestStore.isLoading | get isLoading() {
return this.result.status === "loading";
} | // Non type-safe shorthand | https://github.com/kubk/memo-card/blob/27196793e05a4b68b2783a81352e8eba82f55a3a/src/lib/mobx-request/request-store.ts#L66-L68 | 27196793e05a4b68b2783a81352e8eba82f55a3a |
memo-card | github_2023 | kubk | typescript | RequestStore.isSuccess | get isSuccess() {
return this.result.status === "success";
} | // Non type-safe shorthand | https://github.com/kubk/memo-card/blob/27196793e05a4b68b2783a81352e8eba82f55a3a/src/lib/mobx-request/request-store.ts#L71-L73 | 27196793e05a4b68b2783a81352e8eba82f55a3a |
memo-card | github_2023 | kubk | typescript | BrowserPlatform.handleTelegramWidgetLogin | handleTelegramWidgetLogin(data: Record<any, any>) {
localStorage.setItem(
browserTokenKey,
`${UserSource.Telegram} ${JSON.stringify(data)}`,
);
window.location.reload();
} | // Telegram auth outside Telegram mini app | https://github.com/kubk/memo-card/blob/27196793e05a4b68b2783a81352e8eba82f55a3a/src/lib/platform/browser/browser-platform.ts#L120-L126 | 27196793e05a4b68b2783a81352e8eba82f55a3a |
memo-card | github_2023 | kubk | typescript | BrowserPlatform.handleGoogleAuth | handleGoogleAuth(credential: string) {
googleSignInRequest({ token: credential })
.then((response) => {
localStorage.setItem(
browserTokenKey,
`${UserSource.Google} ${response.browserToken}`,
);
window.location.reload();
})
.catch(console.error);
} | // Google auth outside Telegram mini app | https://github.com/kubk/memo-card/blob/27196793e05a4b68b2783a81352e8eba82f55a3a/src/lib/platform/browser/browser-platform.ts#L129-L139 | 27196793e05a4b68b2783a81352e8eba82f55a3a |
memo-card | github_2023 | kubk | typescript | ScreenStore.restoreHistory | restoreHistory() {
this.history = [{ type: "main" }];
} | // TODO: Remove this when we have a proper navigation | https://github.com/kubk/memo-card/blob/27196793e05a4b68b2783a81352e8eba82f55a3a/src/store/screen-store.ts#L59-L61 | 27196793e05a4b68b2783a81352e8eba82f55a3a |
pergel | github_2023 | oku-ui | typescript | sleep | function sleep(time: number) {
return new Promise((resolve) => {
console.warn('Process started')
setTimeout(() => {
resolve('Process finished')
}, time)
})
} | // Sleep | https://github.com/oku-ui/pergel/blob/2b7f24dd8459e6c423c47ac972ca9eb150632505/examples/p-bullmq/server/plugins/bullmq.ts#L27-L34 | 2b7f24dd8459e6c423c47ac972ca9eb150632505 |
pergel | github_2023 | oku-ui | typescript | determineEnvPrefix | function determineEnvPrefix(customPrefix?: string) {
const defaultPrefix = 'NUXT_'
const alternativePrefixVariable = 'NITRO_ENV_PREFIX'
return customPrefix ?? process.env[alternativePrefixVariable] ?? defaultPrefix
} | /**
* Determines the environment variable prefix based on defined environment variables.
*/ | https://github.com/oku-ui/pergel/blob/2b7f24dd8459e6c423c47ac972ca9eb150632505/packages/nuxt/src/runtime/core/utils/runtimeConfigToEnv.ts#L7-L12 | 2b7f24dd8459e6c423c47ac972ca9eb150632505 |
pergel | github_2023 | oku-ui | typescript | schedule | async function schedule(...data: Parameters<Queue<any, any, string>['add']>) {
const name = data[0]
const myQueue = _myQueue.get(_pergel.projectName)
if (!myQueue)
throw new Error('Queue not initialized')
// Add: name, data, opts
consola.info('Adding job to queue %s', name)
return myQueue.add(...data)
} | // TODO: fix type | https://github.com/oku-ui/pergel/blob/2b7f24dd8459e6c423c47ac972ca9eb150632505/packages/nuxt/src/runtime/modules/bullmq/composables/nitro/useScheduler.ts#L223-L232 | 2b7f24dd8459e6c423c47ac972ca9eb150632505 |
pergel | github_2023 | oku-ui | typescript | download | function download(data: any, filename: string) {
const defaultMimeType = 'application/octet-stream'
const blob = new Blob([data], { type: defaultMimeType })
const blobURL = window.URL.createObjectURL(blob)
const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', filename)
if (typeof tempLink.download === 'undefined')
tempLink.setAttribute('target', '_blank')
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(blobURL)
} | /**
* @example
* ```ts
* await useFetch('/api/csvDownload', {
method: 'get',
onResponse({ response }) {
download(response._data, 'form.csv')
},
})
* ```
* @param data
* @param filename
*/ | https://github.com/oku-ui/pergel/blob/2b7f24dd8459e6c423c47ac972ca9eb150632505/packages/nuxt/src/runtime/modules/json2csv/composables/vue/download.ts#L14-L31 | 2b7f24dd8459e6c423c47ac972ca9eb150632505 |
pergel | github_2023 | oku-ui | typescript | everySeconds | function everySeconds(seconds: number = 1, handleDate: (result: string) => void) {
cron.schedule(`*/${seconds} * * * * *`, () => handleDate(new Date().toISOString()))
} | // # ┌────────────── second (optional) | https://github.com/oku-ui/pergel/blob/2b7f24dd8459e6c423c47ac972ca9eb150632505/packages/nuxt/src/runtime/modules/nodeCron/composables/nitroPlugin.ts#L79-L81 | 2b7f24dd8459e6c423c47ac972ca9eb150632505 |
kaguya-app | github_2023 | hoangvu12 | typescript | AnilistProvider.handleCode | async handleCode(url: string): Promise<Token> {
const params = paramsToObject(url.split('#')[1]);
const accessToken = params?.access_token as string;
if (!accessToken) throw new Error('No access token found');
return {
accessToken,
};
} | // kaguya://settings?provider=anilist#access_token=....&token_type=Bearer&expires_in=... | https://github.com/hoangvu12/kaguya-app/blob/5f78e6c9828b98ca3f19309119ceb3ce7cbe6541/src/providers/anilist.tsx#L96-L106 | 5f78e6c9828b98ca3f19309119ceb3ce7cbe6541 |
open-webui | github_2023 | open-webui | typescript | getCredentials | async function getCredentials() {
const response = await fetch('/api/config');
if (!response.ok) {
throw new Error('Failed to fetch Google Drive credentials');
}
const config = await response.json();
API_KEY = config.google_drive?.api_key;
CLIENT_ID = config.google_drive?.client_id;
if (!API_KEY || !CLIENT_ID) {
throw new Error('Google Drive API credentials not configured');
}
} | // Function to fetch credentials from backend config | https://github.com/open-webui/open-webui/blob/2017856791b666fac5f1c2f80a3bc7916439438b/src/lib/utils/google-drive-picker.ts#L6-L18 | 2017856791b666fac5f1c2f80a3bc7916439438b |
open-webui | github_2023 | open-webui | typescript | validateCredentials | const validateCredentials = () => {
if (!API_KEY || !CLIENT_ID) {
throw new Error('Google Drive API credentials not configured');
}
if (API_KEY === '' || CLIENT_ID === '') {
throw new Error('Please configure valid Google Drive API credentials');
}
}; | // Validate required credentials | https://github.com/open-webui/open-webui/blob/2017856791b666fac5f1c2f80a3bc7916439438b/src/lib/utils/google-drive-picker.ts#L25-L32 | 2017856791b666fac5f1c2f80a3bc7916439438b |
open-webui | github_2023 | open-webui | typescript | findMatchingClosingTag | function findMatchingClosingTag(src: string, openTag: string, closeTag: string): number {
let depth = 1;
let index = openTag.length;
while (depth > 0 && index < src.length) {
if (src.startsWith(openTag, index)) {
depth++;
} else if (src.startsWith(closeTag, index)) {
depth--;
}
if (depth > 0) {
index++;
}
}
return depth === 0 ? index + closeTag.length : -1;
} | // Helper function to find matching closing tag | https://github.com/open-webui/open-webui/blob/2017856791b666fac5f1c2f80a3bc7916439438b/src/lib/utils/marked/extension.ts#L2-L16 | 2017856791b666fac5f1c2f80a3bc7916439438b |
open-webui | github_2023 | open-webui | typescript | parseAttributes | function parseAttributes(tag: string): { [key: string]: string } {
const attributes: { [key: string]: string } = {};
const attrRegex = /(\w+)="(.*?)"/g;
let match;
while ((match = attrRegex.exec(tag)) !== null) {
attributes[match[1]] = match[2];
}
return attributes;
} | // Function to parse attributes from tag | https://github.com/open-webui/open-webui/blob/2017856791b666fac5f1c2f80a3bc7916439438b/src/lib/utils/marked/extension.ts#L19-L27 | 2017856791b666fac5f1c2f80a3bc7916439438b |
open-webui | github_2023 | open-webui | typescript | detailsExtension | function detailsExtension() {
return {
name: 'details',
level: 'block',
start: detailsStart,
tokenizer: detailsTokenizer,
renderer: detailsRenderer
};
} | // Extension wrapper function | https://github.com/open-webui/open-webui/blob/2017856791b666fac5f1c2f80a3bc7916439438b/src/lib/utils/marked/extension.ts#L80-L88 | 2017856791b666fac5f1c2f80a3bc7916439438b |
open-webui | github_2023 | open-webui | typescript | KokoroWorker.constructor | constructor(dtype: string = 'fp32') {
this.dtype = dtype;
} | // To track if a request is being processed | https://github.com/open-webui/open-webui/blob/2017856791b666fac5f1c2f80a3bc7916439438b/src/lib/workers/KokoroWorker.ts#L15-L17 | 2017856791b666fac5f1c2f80a3bc7916439438b |
baml | github_2023 | BoundaryML | typescript | createBamlErrorUnsafe | function createBamlErrorUnsafe(error: unknown): BamlErrors | Error {
if (!isError(error)) {
return new Error(String(error))
}
const bamlClientHttpError = BamlClientHttpError.from(error)
if (bamlClientHttpError) {
return bamlClientHttpError
}
const bamlValidationError = BamlValidationError.from(error)
if (bamlValidationError) {
return bamlValidationError
}
const bamlClientFinishReasonError = BamlClientFinishReasonError.from(error)
if (bamlClientFinishReasonError) {
return bamlClientFinishReasonError
}
// otherwise return the original error
return error
} | // Helper function to safely create a BamlValidationError | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/engine/language_client_typescript/typescript_src/errors.ts#L157-L179 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | BamlStream.toStreamable | toStreamable(): ReadableStream<Uint8Array> {
const stream = this
const encoder = new TextEncoder()
return new ReadableStream({
async start(controller) {
try {
// Stream partials
for await (const partial of stream) {
controller.enqueue(encoder.encode(JSON.stringify({ partial })))
}
try {
const final = await stream.getFinalResponse()
controller.enqueue(encoder.encode(JSON.stringify({ final })))
controller.close()
return
} catch (err: unknown) {
const bamlError = toBamlError(err instanceof Error ? err : new Error(String(err)))
controller.enqueue(encoder.encode(JSON.stringify({ error: bamlError })))
controller.close()
return
}
} catch (streamErr: unknown) {
const errorPayload = {
type: 'StreamError',
message: streamErr instanceof Error ? streamErr.message : 'Error in stream processing',
prompt: '',
raw_output: '',
}
controller.enqueue(encoder.encode(JSON.stringify({ error: errorPayload })))
controller.close()
}
},
})
} | /**
* Converts the BAML stream to a Next.js compatible stream.
* This is used for server-side streaming in Next.js API routes and Server Actions.
* The stream emits JSON-encoded messages containing either:
* - Partial results of type PartialOutputType
* - Final result of type FinalOutputType
* - Error information
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/engine/language_client_typescript/typescript_src/stream.ts#L76-L112 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | BamlSyncClient.stream | get stream() {
throw new Error("stream is not available in BamlSyncClient. Use `import { b } from 'baml_client/async_client")
} | /*
* @deprecated NOT IMPLEMENTED as streaming must by async. We
* are not providing an async version as we want to reserve the
* right to provide a sync version in the future.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/integ-tests/react/baml_client/sync_client.ts#L43-L45 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | isStreamingProps | function isStreamingProps<FunctionName extends FunctionNames>(
props: HookInput<FunctionName, { stream?: boolean }>,
): props is HookInput<FunctionName, { stream?: true }> {
return props.stream !== false
} | /**
* Type guard to check if the hook props are configured for streaming mode.
*
* @template FunctionName - The name of the BAML function.
* @param props - The hook props.
* @returns {boolean} True if the props indicate streaming mode.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/integ-tests/react/baml_client/react/hooks.tsx#L107-L111 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | isNotStreamingProps | function isNotStreamingProps<FunctionName extends FunctionNames>(
props: HookInput<FunctionName, { stream?: boolean }>,
): props is HookInput<FunctionName, { stream: false }> {
return props.stream === false
} | /**
* Type guard to check if the hook props are configured for non‑streaming mode.
*
* @template FunctionName - The name of the BAML function.
* @param props - The hook props.
* @returns {boolean} True if the props indicate non‑streaming mode.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/integ-tests/react/baml_client/react/hooks.tsx#L120-L124 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | hookReducer | function hookReducer<TPartial, TFinal>(
state: HookState<TPartial, TFinal>,
action: HookStateAction<TPartial, TFinal>,
): HookState<TPartial, TFinal> {
switch (action.type) {
case 'START_REQUEST':
return {
...state,
isSuccess: false,
error: undefined,
isStreaming: false,
finalData: undefined,
streamData: undefined,
}
case 'SET_ERROR':
return {
...state,
isSuccess: false,
isStreaming: false,
error: action.payload,
}
case 'SET_PARTIAL':
return {
...state,
isStreaming: true,
streamData: action.payload,
}
case 'SET_FINAL':
return {
...state,
isSuccess: true,
isStreaming: false,
finalData: action.payload,
}
case 'RESET':
return {
isSuccess: false,
isStreaming: false,
error: undefined,
finalData: undefined,
streamData: undefined,
}
default:
return state
}
} | /**
* Reducer function to manage the hook state transitions.
*
* @template TPartial - The type of the partial (streaming) data.
* @template TFinal - The type of the final (non‑streaming) data.
* @param state - The current hook state.
* @param action - The action to apply.
* @returns The updated state.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/integ-tests/react/baml_client/react/hooks.tsx#L150-L195 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | BamlSyncClient.stream | get stream() {
throw new Error("stream is not available in BamlSyncClient. Use `import { b } from 'baml_client/async_client")
} | /*
* @deprecated NOT IMPLEMENTED as streaming must by async. We
* are not providing an async version as we want to reserve the
* right to provide a sync version in the future.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/integ-tests/typescript/baml_client/sync_client.ts#L43-L45 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | foo | function foo() {
// @ts-ignore
var reb2b = (window.reb2b = window.reb2b || [])
if (reb2b.invoked) return
reb2b.invoked = true
reb2b.methods = ['identify', 'collect']
reb2b.factory = function (method: string) {
return function () {
var args = Array.prototype.slice.call(arguments)
args.unshift(method)
reb2b.push(args)
return reb2b
}
}
for (var i = 0; i < reb2b.methods.length; i++) {
var key = reb2b.methods[i]
reb2b[key] = reb2b.factory(key)
}
reb2b.load = function (key: string) {
var script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = 'https://s3-us-west-2.amazonaws.com/b2bjsstore/b/' + key + '/reb2b.js.gz'
var first = document.getElementsByTagName('script')[0]
first.parentNode!.insertBefore(script, first)
}
reb2b.SNIPPET_VERSION = '1.0.1'
reb2b.load('1VN080H5R86J')
} | // Directly adding your script content here | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/fiddle-frontend/app/_components/PosthogProvider.tsx#L21-L49 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | loadChatwoot | const loadChatwoot = () => {
;(function (d, t) {
var BASE_URL = 'https://app.chatwoot.com'
var g = d.createElement(t) as any,
s = d.getElementsByTagName(t)[0] as any
g.src = BASE_URL + '/packs/js/sdk.js'
g.defer = true
g.async = true
s.parentNode.insertBefore(g, s)
g.onload = function () {
;(window as any).chatwootSDK.run({
websiteToken: 'M4EXKvdb9NGgxqZzkTZfeFV7',
baseUrl: BASE_URL,
position: 'left',
})
}
})(document, 'script')
} | // const loadDoorbell = () => { | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/lib/feedback_widget.ts#L64-L81 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | serializeBinaryData | function serializeBinaryData(uint8Array: Uint8Array): string {
return uint8Array.reduce((data, byte) => data + String.fromCharCode(byte), '')
} | // Serialization for binary data (like images) | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/shared/baml-project-panel/vscode-rpc.ts#L132-L134 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | deserializeBinaryData | function deserializeBinaryData(serialized: string): Uint8Array {
return new Uint8Array(serialized.split('').map((char) => char.charCodeAt(0)))
} | // Deserialization for binary data | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/shared/baml-project-panel/vscode-rpc.ts#L137-L139 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | base64Encode | function base64Encode(str: string): string {
const base64chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
let result: string = ''
let i: number
for (i = 0; i < str.length; i += 3) {
const chunk: number = (str.charCodeAt(i) << 16) | (str.charCodeAt(i + 1) << 8) | str.charCodeAt(i + 2)
result +=
base64chars.charAt((chunk & 16515072) >> 18) +
base64chars.charAt((chunk & 258048) >> 12) +
base64chars.charAt((chunk & 4032) >> 6) +
base64chars.charAt(chunk & 63)
}
if (str.length % 3 === 1) result = result.slice(0, -2) + '=='
if (str.length % 3 === 2) result = result.slice(0, -1) + '='
return result
} | // Base64 encoding | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/shared/baml-project-panel/vscode-rpc.ts#L142-L157 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | base64Decode | function base64Decode(str: string): string {
const base64chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
while (str[str.length - 1] === '=') {
str = str.slice(0, -1)
}
let result: string = ''
for (let i = 0; i < str.length; i += 4) {
const chunk: number =
(base64chars.indexOf(str[i]) << 18) |
(base64chars.indexOf(str[i + 1]) << 12) |
(base64chars.indexOf(str[i + 2]) << 6) |
base64chars.indexOf(str[i + 3])
result += String.fromCharCode((chunk & 16711680) >> 16, (chunk & 65280) >> 8, chunk & 255)
}
return result.slice(0, result.length - (str.length % 4 ? 4 - (str.length % 4) : 0))
} | // Base64 decoding | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/shared/baml-project-panel/vscode-rpc.ts#L160-L175 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | VSCodeAPIWrapper.postMessage | public postMessage(message: unknown) {
if (this.vsCodeApi) {
this.vsCodeApi.postMessage(message)
} else {
console.log('posting message' + JSON.stringify(message))
window.postMessage(message)
}
} | /**
* Post a message (i.e. send arbitrary data) to the owner of the webview.
*
* @remarks When running webview code inside a web browser, postMessage will instead
* log the given message to the console.
*
* @param message Abitrary data (must be JSON serializable) to send to the extension context.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/shared/baml-project-panel/vscode.ts#L167-L174 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | VSCodeAPIWrapper.getState | public getState(): unknown | undefined {
if (this.vsCodeApi) {
return this.vsCodeApi.getState()
} else {
const state = localStorage.getItem('vscodeState')
return state ? JSON.parse(state) : undefined
}
} | /**
* Get the persistent state stored for this webview.
*
* @remarks When running webview source code inside a web browser, getState will retrieve state
* from local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
*
* @return The current state or `undefined` if no state has been set.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/shared/baml-project-panel/vscode.ts#L184-L191 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | VSCodeAPIWrapper.setState | public setState<T extends unknown | undefined>(newState: T): T {
if (this.vsCodeApi) {
return this.vsCodeApi.setState(newState)
} else {
localStorage.setItem('vscodeState', JSON.stringify(newState))
return newState
}
} | /**
* Set the persistent state stored for this webview.
*
* @remarks When running webview source code inside a web browser, setState will set the given
* state using local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
*
* @param newState New persisted state. This must be a JSON serializable object. Can be retrieved
* using {@link getState}.
*
* @return The new state.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/shared/baml-project-panel/vscode.ts#L204-L211 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WasmPanicRegistry.set_message | private set_message(value: string) {
this.message = `RuntimeError: ${value}`
} | // Don't use this method directly, it's only used by the Wasm panic hook in @prisma/prisma-schema-wasm. | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/playground-common/src/wasm/error/WasmPanicRegistry.ts#L9-L11 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | showErrorToast | function showErrorToast(errorMessage: string): void {
connection.window
.showErrorMessage(errorMessage, {
title: 'Show Details',
})
.then((item) => {
if (item?.title === 'Show Details') {
// connection.sendNotification('baml/showLanguageServerOutput')
}
})
} | // Note: VS Code strips newline characters from the message | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/language-server/src/server.ts#L337-L347 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | Project.runGeneratorsWithoutDebounce | runGeneratorsWithoutDebounce = async ({
onSuccess,
onError,
}: { onSuccess: (message: string) => void; onError: (message: string) => void }) => {
const startMillis = performance.now()
try {
const generated = await Promise.all(
this.wasmProject.run_generators().map(async (g) => {
// Creating the tmpdir next to the output dir can cause some weird issues with vscode, if we recover
// from an error and delete the tmpdir - vscode's explorer UI will still show baml_client.tmp even
// though it doesn't exist anymore, and vscode has no good way of letting the user purge it from the UI
console.log(`outputdir ${g.output_dir}`)
console.log(`relative output dir ${g.output_dir_relative_to_baml_src}`)
const out_dir = path.join(this.rootPath(), g.output_dir_relative_to_baml_src)
const tmpDir = path.join(out_dir + '.tmp')
const backupDir = path.join(out_dir + '.bak')
await mkdir(tmpDir, { recursive: true })
console.log(`tmpdir ${tmpDir}`)
await Promise.all(
g.files.map(async (f) => {
const fpath = path.join(tmpDir, f.path_in_output_dir)
await mkdir(path.dirname(fpath), { recursive: true })
await writeFile(fpath, f.contents)
}),
)
if (existsSync(backupDir)) {
await rm(backupDir, { recursive: true, force: true })
}
if (existsSync(out_dir)) {
console.log('out dir exists')
const contents = await readdir(out_dir, { withFileTypes: true })
const contentsWithSafeToRemove = await Promise.all(
contents.map(async (c) => {
if (c.isDirectory()) {
if (['__pycache__'].includes(c.name)) {
return { path: c.name, safeToRemove: true }
}
return { path: c.name, safeToRemove: false }
}
const handle = await open(path.join(out_dir, c.name))
try {
const { bytesRead, buffer } = await handle.read(Buffer.alloc(1024), 0, 1024, 0)
const firstNBytes = buffer.subarray(0, bytesRead).toString('utf8')
return { path: c.name, safeToRemove: firstNBytes.includes('generated by BAML') }
} finally {
await handle.close()
}
}),
)
const notSafeToRemove = contentsWithSafeToRemove.filter((c) => !c.safeToRemove).map((c) => c.path)
if (notSafeToRemove.length !== 0) {
throw new Error(
`Output dir ${g.output_dir} contains this file(s) not generated by BAML: ${notSafeToRemove.join(', ')}`,
)
}
try {
await rename(out_dir, backupDir)
} catch (e) {
console.error(`Something happened backing up baml_client to the .bak directory. ${e}`)
}
}
await rename(tmpDir, out_dir)
try {
// some filewatchers don't trigger unless the file is touched. Creating the new dir alone doesn't work.
// if we remove this, TS will still have the old types, and nextjs will not hot-reload.
g.files.map((f) => {
const fpath = path.join(out_dir, f.path_in_output_dir)
const currentTime = new Date()
const newTime = new Date(currentTime.getTime() + 100)
utimes(fpath, newTime, newTime, (err) => {
if (err) {
console.log(`Error setting file times: ${err.message}`)
}
})
})
} catch (e) {
if (e instanceof Error) {
console.error(`Error setting file times: ${e.message}`)
} else {
console.error(`Error setting file times:`)
}
}
await rm(backupDir, { recursive: true, force: true })
return g
}),
)
const endMillis = performance.now()
const generatedFileCount = generated.reduce((acc, g) => acc + g.files.length, 0)
if (generatedFileCount > 0) {
onSuccess(`BAML client generated! (took ${Math.round(endMillis - startMillis)}ms)`)
}
} catch (e) {
console.error(`Failed to generate BAML client: ${e}`)
onError(`Failed to generate BAML client: ${e}`)
}
} | // Not currently debounced - lodash debounce doesn't work for this, p-debounce doesn't support trailing edge | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/language-server/src/lib/baml_project_manager.ts#L364-L468 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | BamlProjectManager.requestDiagnostics | async requestDiagnostics(documentUri: URI) {
await this.wrapAsync(async () => {
const project = this.getProjectById(documentUri)
if (project) {
project.requestDiagnostics()
if (project.runtime()) {
this.notifier({ type: 'runtime_updated', root_path: project.rootPath(), files: project.files() })
} else {
console.log('undefined runtime')
}
} else {
console.error('project not found', documentUri)
}
})
} | // the web panel filters them out and just sends the diagnostics for the current project that's opened in view. | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/language-server/src/lib/baml_project_manager.ts#L656-L670 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | BamlProjectManager.reload_project_files | async reload_project_files(path: URI) {
// console.debug(`Reloading project files: ${path}`)
await this.wrapAsync(async () => {
const rootPath = uriToRootPath(path)
const files = await Promise.all(
gatherFiles(rootPath).map(async (uri): Promise<[string, string]> => {
const path = uri.fsPath
const content = await readFile(path, 'utf8')
return [path, content]
}),
)
if (files.length === 0) {
this.notifier({
type: 'warn',
message: `Empty baml_src directory found: ${rootPath}. See Output panel -> BAML Language Server for more details.`,
})
}
console.debug(`projects ${this.projects.size}: ${JSON.stringify(this.projects, null, 2)},`)
if (!this.projects.has(rootPath)) {
const project = this.add_project(rootPath, Object.fromEntries(files))
project.update_runtime()
} else {
const project = this.get_project(rootPath)
project.replace_all_files(BamlWasm.WasmProject.new(rootPath, Object.fromEntries(files)))
project.update_runtime()
}
})
} | // Takes in a URI to any file in the project | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/language-server/src/lib/baml_project_manager.ts#L674-L705 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WasmPanicRegistry.set_message | private set_message(value: string) {
this.message = `RuntimeError: ${value}`
} | // Don't use this method directly, it's only used by the Wasm panic hook in @prisma/prisma-schema-wasm. | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/language-server/src/lib/wasm/error/WasmPanicRegistry.ts#L9-L11 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | createBamlPatterns | function createBamlPatterns() {
return [
// React hooks pattern - matches both direct and namespace imports with parameters
new RegExp('(?:[a-zA-Z0-9_]+\\.)?use([A-Z][a-zA-Z0-9_]*)\\s*\\([^)]*\\)', 'g'),
// Direct BAML client pattern - matches capitalized function names only
new RegExp('(?:^|\\s)(?:baml|b)\\.([A-Z][a-zA-Z0-9_]*)(?:\\s|\\(|$)', 'g'),
]
} | // Helper function to create regex patterns for matching BAML function calls | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/LanguageToBamlCodeLensProvider.ts#L5-L12 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WebPanelView.dispose | public dispose() {
while (this._disposables.length) {
const disposable = this._disposables.pop()
if (disposable) {
disposable.dispose()
}
}
} | /**
* Cleans up and disposes of webview resources when the webview panel is closed.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/WebPanelView.ts#L47-L54 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WebPanelView._setWebviewMessageListener | private _setWebviewMessageListener(webview: Webview) {
webview.onDidReceiveMessage(
(message: any) => {
const command = message.command
const text = message.text
switch (command) {
case 'hello':
// Code that should run in response to the hello message command
window.showInformationMessage(text)
return
// Add more switch case statements here as more webview message commands
// are created within the webview context (i.e. inside media/main.js)
}
},
undefined,
this._disposables,
)
} | /**
* Sets up an event listener to listen for messages passed from the webview context and
* executes code based on the message that is recieved.
*
* @param webview A reference to the extension webview
* @param context A reference to the extension context
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/WebPanelView.ts#L123-L141 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | serializeBinaryData | function serializeBinaryData(uint8Array: Uint8Array): string {
return uint8Array.reduce((data, byte) => data + String.fromCharCode(byte), '')
} | // Serialization for binary data (like images) | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/vscode-rpc.ts#L132-L134 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | deserializeBinaryData | function deserializeBinaryData(serialized: string): Uint8Array {
return new Uint8Array(serialized.split('').map((char) => char.charCodeAt(0)))
} | // Deserialization for binary data | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/vscode-rpc.ts#L137-L139 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | base64Encode | function base64Encode(str: string): string {
const base64chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
let result: string = ''
let i: number
for (i = 0; i < str.length; i += 3) {
const chunk: number = (str.charCodeAt(i) << 16) | (str.charCodeAt(i + 1) << 8) | str.charCodeAt(i + 2)
result +=
base64chars.charAt((chunk & 16515072) >> 18) +
base64chars.charAt((chunk & 258048) >> 12) +
base64chars.charAt((chunk & 4032) >> 6) +
base64chars.charAt(chunk & 63)
}
if (str.length % 3 === 1) result = result.slice(0, -2) + '=='
if (str.length % 3 === 2) result = result.slice(0, -1) + '='
return result
} | // Base64 encoding | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/vscode-rpc.ts#L142-L157 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | base64Decode | function base64Decode(str: string): string {
const base64chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
while (str[str.length - 1] === '=') {
str = str.slice(0, -1)
}
let result: string = ''
for (let i = 0; i < str.length; i += 4) {
const chunk: number =
(base64chars.indexOf(str[i]) << 18) |
(base64chars.indexOf(str[i + 1]) << 12) |
(base64chars.indexOf(str[i + 2]) << 6) |
base64chars.indexOf(str[i + 3])
result += String.fromCharCode((chunk & 16711680) >> 16, (chunk & 65280) >> 8, chunk & 255)
}
return result.slice(0, result.length - (str.length % 4 ? 4 - (str.length % 4) : 0))
} | // Base64 decoding | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/vscode-rpc.ts#L160-L175 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | Extension.isProductionMode | public get isProductionMode(): boolean {
return this.ctx.extensionMode === ExtensionMode.Production
} | /**
* Check if the extension is in production/development mode
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/helpers/extension.ts#L19-L21 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WebPanelView.constructor | private constructor(
panel: WebviewPanel,
extensionUri: Uri,
portLoader: () => number,
private reporter?: TelemetryReporter,
) {
this._panel = panel
this._port = portLoader
// Set an event listener to listen for when the panel is disposed (i.e. when the user closes
// the panel or when the panel is closed programmatically)
this._panel.onDidDispose(() => this.dispose(), null, this._disposables)
// Set the HTML content for the webview panel
this._panel.webview.html = this._getWebviewContent(this._panel.webview, extensionUri)
// Set an event listener to listen for messages passed from the webview context
this._setWebviewMessageListener(this._panel.webview)
} | /**
* The WebPanelView class private constructor (called only from the render method).
*
* @param panel A reference to the webview panel
* @param extensionUri The URI of the directory containing the extension
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/panels/WebPanelView.ts#L54-L72 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WebPanelView.render | public static render(extensionUri: Uri, portLoader: () => number, reporter: TelemetryReporter) {
if (WebPanelView.currentPanel) {
// If the webview panel already exists reveal it
WebPanelView.currentPanel._panel.reveal(ViewColumn.Beside)
} else {
// If a webview panel does not already exist create and show a new one
const panel = window.createWebviewPanel(
// Panel view type
'showHelloWorld',
// Panel title
'BAML Playground',
// The editor column the panel should be displayed in
// process.env.VSCODE_DEBUG_MODE === 'true' ? ViewColumn.Two : ViewColumn.Beside,
{ viewColumn: ViewColumn.Beside, preserveFocus: true },
// Extra panel configurations
{
// Enable JavaScript in the webview
enableScripts: true,
// Restrict the webview to only load resources from the `out` and `web-panel/dist` directories
localResourceRoots: [
...(vscode.workspace.workspaceFolders ?? []).map((f) => f.uri),
Uri.joinPath(extensionUri, 'out'),
Uri.joinPath(extensionUri, 'web-panel/dist'),
],
retainContextWhenHidden: true,
enableCommandUris: true,
},
)
WebPanelView.currentPanel = new WebPanelView(panel, extensionUri, portLoader, reporter)
}
} | /**
* Renders the current webview panel if it exists otherwise a new webview panel
* will be created and displayed.
*
* @param extensionUri The URI of the directory containing the extension.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/panels/WebPanelView.ts#L80-L113 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WebPanelView.dispose | public dispose() {
WebPanelView.currentPanel = undefined
// Dispose of the current webview panel
this._panel.dispose()
const config = workspace.getConfiguration()
config.update('baml.bamlPanelOpen', false, true)
// Dispose of all disposables (i.e. commands) for the current webview panel
while (this._disposables.length) {
const disposable = this._disposables.pop()
if (disposable) {
disposable.dispose()
}
}
} | /**
* Cleans up and disposes of webview resources when the webview panel is closed.
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/panels/WebPanelView.ts#L126-L142 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WebPanelView._getWebviewContent | private _getWebviewContent(webview: Webview, extensionUri: Uri) {
// The CSS file from the React dist output
const stylesUri = getUri(webview, extensionUri, ['web-panel', 'dist', 'assets', 'index.css'])
// The JS file from the React dist output
const scriptUri = getUri(webview, extensionUri, ['web-panel', 'dist', 'assets', 'index.js'])
const nonce = getNonce()
// Tip: Install the es6-string-html VS Code extension to enable code highlighting below
return /*html*/ `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="${stylesUri}">
<title>Hello World</title>
</head>
<body>
<div id="root">Waiting for react: ${scriptUri}</div>
<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>
`
} | /**
* Defines and returns the HTML that should be rendered within the webview panel.
*
* @remarks This is also the place where references to the React webview dist files
* are created and inserted into the webview HTML.
*
* @param webview A reference to the extension webview
* @param extensionUri The URI of the directory containing the extension
* @returns A template string literal containing the HTML that should be
* rendered within the webview panel
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/panels/WebPanelView.ts#L155-L179 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
baml | github_2023 | BoundaryML | typescript | WebPanelView._setWebviewMessageListener | private _setWebviewMessageListener(webview: Webview) {
const addProject = async () => {
await requestDiagnostics()
console.log('last opened func', openPlaygroundConfig.lastOpenedFunction)
this.postMessage('select_function', {
root_path: 'default',
function_name: openPlaygroundConfig.lastOpenedFunction,
})
this.postMessage('baml_cli_version', bamlConfig.cliVersion)
}
webview.onDidReceiveMessage(
async (
message:
| {
command: 'get_port' | 'add_project' | 'cancelTestRun' | 'removeTest'
}
| {
command: 'jumpToFile'
span: StringSpan
}
| {
command: 'telemetry'
meta: {
action: string
data: Record<string, unknown>
}
}
| {
rpcId: number
data: WebviewToVscodeRpc
},
) => {
if ('command' in message) {
switch (message.command) {
case 'add_project':
console.log('webview add_project')
addProject()
return
case 'jumpToFile': {
try {
console.log('jumpToFile', message.span)
const span = message.span
// span.source_file is a file:/// URI
const uri = vscode.Uri.parse(span.source_file)
await vscode.workspace.openTextDocument(uri).then((doc) => {
const range = new vscode.Range(doc.positionAt(span.start), doc.positionAt(span.end))
vscode.window.showTextDocument(doc, { selection: range, viewColumn: ViewColumn.One })
})
} catch (e: any) {
console.log(e)
}
return
}
case 'telemetry': {
const { action, data } = message.meta
this.reporter?.sendTelemetryEvent({
event: `baml.webview.${action}`,
properties: data,
})
return
}
}
}
if (!('rpcId' in message)) {
return
}
// console.log('message from webview, after above handlers:', message)
const vscodeMessage = message.data
const vscodeCommand = vscodeMessage.vscodeCommand
// TODO: implement error handling in our RPC framework
switch (vscodeCommand) {
case 'ECHO':
const echoresp: EchoResponse = { message: vscodeMessage.message }
// also respond with rpc id
this._panel.webview.postMessage({ rpcId: message.rpcId, rpcMethod: vscodeCommand, data: echoresp })
return
case 'GET_WEBVIEW_URI':
// This is 1:1 with the contents of `image.file` in a test file, e.g. given `image { file baml_src://path/to-image.png }`,
// relpath will be 'baml_src://path/to-image.png'
const relpath = vscodeMessage.path
// NB(san): this is a violation of the "never URI.parse rule"
// (see https://www.notion.so/gloochat/windows-uri-treatment-fe87b22abebb4089945eb8cd1ad050ef)
// but this relpath is already a file URI, it seems...
const uriPath = Uri.parse(relpath)
const uri = this._panel.webview.asWebviewUri(uriPath).toString()
console.log('GET_WEBVIEW_URI', { vscodeMessage, uri, parsed: uriPath })
let webviewUriResp: GetWebviewUriResponse = {
uri,
}
if (vscodeMessage.contents) {
try {
const contents = await workspace.fs.readFile(uriPath)
webviewUriResp = {
...webviewUriResp,
contents: encodeBuffer(contents),
}
} catch (e) {
webviewUriResp = {
...webviewUriResp,
readError: `${e}`,
}
}
}
this._panel.webview.postMessage({ rpcId: message.rpcId, rpcMethod: vscodeCommand, data: webviewUriResp })
return
case 'GET_VSCODE_SETTINGS':
const responseData: GetVSCodeSettingsResponse = {
enablePlaygroundProxy: bamlConfig.config?.enablePlaygroundProxy ?? true,
}
this._panel.webview.postMessage({ rpcId: message.rpcId, rpcMethod: vscodeCommand, data: responseData })
return
case 'GET_PLAYGROUND_PORT':
const response: GetPlaygroundPortResponse = {
port: this._port(),
}
this._panel.webview.postMessage({ rpcId: message.rpcId, rpcMethod: vscodeCommand, data: response })
return
case 'INITIALIZED': // when the playground is initialized and listening for file changes, we should resend all project files.
// request diagnostics, which updates the runtime and triggers a new project files update.
addProject()
console.log('initialized webview')
this._panel.webview.postMessage({ rpcId: message.rpcId, rpcMethod: vscodeCommand, data: { ack: true } })
return
}
},
undefined,
this._disposables,
)
} | /**
* Sets up an event listener to listen for messages passed from the webview context and
* executes code based on the message that is recieved.
*
* @param webview A reference to the extension webview
* @param context A reference to the extension context
*/ | https://github.com/BoundaryML/baml/blob/0b792decf96ebd2c84e6b9388b996612910e52f8/typescript/vscode-ext/packages/vscode/src/panels/WebPanelView.ts#L188-L324 | 0b792decf96ebd2c84e6b9388b996612910e52f8 |
rsbuild | github_2023 | web-infra-dev | typescript | convertPath | const convertPath = (path: string) => {
if (platform() === 'win32') {
return convertPathToPattern(path);
}
return path;
}; | // fast-glob only accepts posix path | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/e2e/scripts/helper.ts#L45-L50 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | minifyWithTimeout | function minifyWithTimeout(
filename: string,
minify: () => Promise<Output>,
): Promise<Output> {
const timer = setTimeout(() => {
logger.warn(
`SWC minimize has running for over 180 seconds for a single file: ${filename}\n
It is likely that you've encountered a ${color.red(
'SWC internal bug',
)}, please contact us at https://github.com/web-infra-dev/modern.js/issues`,
);
}, 180_000);
const outputPromise = minify();
outputPromise.finally(() => {
clearTimeout(timer);
});
return outputPromise;
} | /**
* Currently SWC minify is not stable as we expected, there is a
* change that it can never ends, so add a warning if it hangs too long.
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/compat/plugin-webpack-swc/src/minimizer.ts#L261-L281 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | isOverridePath | const isOverridePath = (key: string) => {
// ignore environments name prefix, such as `environments.web`
if (key.startsWith('environments.')) {
const realKey = key.split('.').slice(2).join('.');
return OVERRIDE_PATHS.includes(realKey);
}
return OVERRIDE_PATHS.includes(key);
}; | /**
* When merging configs, some properties prefer `override` over `merge to array`
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/mergeConfig.ts#L19-L26 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | handleSuccess | function handleSuccess() {
clearOutdatedErrors();
const isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates();
}
} | // Successful compilation. | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/client/hmr.ts#L54-L65 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | handleWarnings | function handleWarnings({ text }: { text: string[] }) {
clearOutdatedErrors();
const isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
for (let i = 0; i < text.length; i++) {
if (i === 5) {
console.warn(
'There were more warnings in other files, you can find a complete log in the terminal.',
);
break;
}
console.warn(text[i]);
}
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates();
}
} | // Compilation with warnings (e.g. ESLint). | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/client/hmr.ts#L68-L89 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | handleErrors | function handleErrors({ text, html }: { text: string[]; html: string }) {
clearOutdatedErrors();
isFirstCompilation = false;
hasCompileErrors = true;
// Also log them to the console.
for (const error of text) {
console.error(error);
}
if (createOverlay) {
createOverlay(html);
}
} | // Compilation with errors (e.g. syntax error or missing modules). | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/client/hmr.ts#L92-L106 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | isUpdateAvailable | const isUpdateAvailable = () => lastCompilationHash !== WEBPACK_HASH; | // __webpack_hash__ is the hash of the current compilation. | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/client/hmr.ts#L110-L110 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | tryApplyUpdates | function tryApplyUpdates() {
// detect is there a newer version of this code available
if (!isUpdateAvailable()) {
return;
}
if (!import.meta.webpackHot) {
// HotModuleReplacementPlugin is not in Rspack configuration.
reloadPage();
return;
}
// Rspack disallows updates in other states.
if (import.meta.webpackHot.status() !== 'idle') {
return;
}
const handleApplyUpdates = (
err: unknown,
updatedModules: (string | number)[] | null,
) => {
const forcedReload = err || !updatedModules;
if (forcedReload) {
if (err) {
console.error('[HMR] Forced reload caused by: ', err);
}
reloadPage();
return;
}
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdates();
}
};
// https://rspack.dev/api/runtime-api/module-variables#importmetawebpackhot
import.meta.webpackHot.check(true).then(
(updatedModules) => handleApplyUpdates(null, updatedModules),
(err) => handleApplyUpdates(err, null),
);
} | // Attempt to update code on the fly, fall back to a hard reload. | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/client/hmr.ts#L113-L154 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | connect | function connect(fallback = false) {
const socketUrl = formatURL(fallback ? resolvedConfig : config);
connection = new WebSocket(socketUrl);
connection.addEventListener('open', onOpen);
// Attempt to reconnect after disconnection
connection.addEventListener('close', onClose);
// Handle messages from the server.
connection.addEventListener('message', onMessage);
// Handle errors
if (!fallback) {
connection.addEventListener('error', onError);
}
} | // Establishing a WebSocket connection with the server. | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/client/hmr.ts#L227-L239 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | hintNodePolyfill | const hintNodePolyfill = (message: string): string => {
const getTips = (moduleName: string) => {
const tips = [
`Tip: "${moduleName}" is a built-in Node.js module. It cannot be imported in client-side code.`,
`Check if you need to import Node.js module. If needed, you can use "${color.cyan('@rsbuild/plugin-node-polyfill')}" to polyfill it.`,
];
return `${message}\n\n${color.yellow(tips.join('\n'))}`;
};
const isNodeProtocolError = message.includes(
'need an additional plugin to handle "node:" URIs',
);
if (isNodeProtocolError) {
return getTips('node:*');
}
if (!message.includes(`Can't resolve`)) {
return message;
}
const matchArray = message.match(/Can't resolve '(\w+)'/);
if (!matchArray) {
return message;
}
const moduleName = matchArray[1];
const nodeModules = [
'assert',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'domain',
'events',
'fs',
'http',
'https',
'module',
'net',
'os',
'path',
'punycode',
'process',
'querystring',
'readline',
'repl',
'stream',
'_stream_duplex',
'_stream_passthrough',
'_stream_readable',
'_stream_transform',
'_stream_writable',
'string_decoder',
'sys',
'timers',
'tls',
'tty',
'url',
'util',
'vm',
'zlib',
];
if (moduleName && nodeModules.includes(moduleName)) {
return getTips(moduleName);
}
return message;
}; | /**
* Add node polyfill tip when failed to resolve node built-in modules.
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/helpers/format.ts#L92-L165 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | formatMessage | function formatMessage(stats: StatsError | string, verbose?: boolean) {
let lines: string[] = [];
let message: string;
// Stats error object
if (typeof stats === 'object') {
const fileName = resolveFileName(stats);
const mainMessage = stats.message;
const details =
verbose && stats.details ? `\nDetails: ${stats.details}\n` : '';
const stack = verbose && stats.stack ? `\n${stats.stack}` : '';
const moduleTrace = resolveModuleTrace(stats);
message = `${fileName}${mainMessage}${details}${stack}${moduleTrace}`;
} else {
message = stats;
}
// Remove inner error message
const innerError = '-- inner error --';
if (!verbose && message.includes(innerError)) {
message = message.split(innerError)[0];
}
message = hintUnknownFiles(message);
message = hintNodePolyfill(message);
lines = message.split('\n');
// Remove duplicated newlines
lines = lines.filter(
(line, index, arr) =>
index === 0 ||
line.trim() !== '' ||
line.trim() !== arr[index - 1].trim(),
);
// Reassemble the message
message = lines.join('\n');
return message.trim();
} | // Cleans up Rspack error messages. | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/helpers/format.ts#L168-L209 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | isUseAnalyzer | const isUseAnalyzer = (config: RsbuildConfig | NormalizedEnvironmentConfig) =>
process.env.BUNDLE_ANALYZE || config.performance?.bundleAnalyze; | // There are two ways to enable the bundle analyzer: | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/bundleAnalyzer.ts#L10-L11 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | validateWebpackCache | async function validateWebpackCache(
cacheDirectory: string,
buildDependencies: Record<string, string[]>,
) {
const configFile = join(cacheDirectory, 'buildDependencies.json');
if (await isFileExists(configFile)) {
const rawConfigFile = await fs.promises.readFile(configFile, 'utf-8');
let prevBuildDependencies: Record<string, string[]> | null = null;
try {
prevBuildDependencies = JSON.parse(rawConfigFile);
} catch (e) {
logger.debug('Failed to parse the previous buildDependencies.json', e);
}
if (
JSON.stringify(prevBuildDependencies) ===
JSON.stringify(buildDependencies)
) {
return;
}
await fs.promises.rm(cacheDirectory, { force: true, recursive: true });
}
await fs.promises.mkdir(cacheDirectory, { recursive: true });
await fs.promises.writeFile(configFile, JSON.stringify(buildDependencies));
} | /**
* If the filenames in the buildDependencies are changed, webpack will not invalidate the previous cache.
* So we need to remove the cache directory to make sure the cache is invalidated.
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/cache.ts#L18-L46 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | getBuildDependencies | async function getBuildDependencies(
context: Readonly<RsbuildContext>,
config: NormalizedEnvironmentConfig,
environmentContext: EnvironmentContext,
userBuildDependencies: Record<string, string[]>,
) {
const rootPackageJson = join(context.rootPath, 'package.json');
const browserslistConfig = join(context.rootPath, '.browserslistrc');
const buildDependencies: Record<string, string[]> = {};
if (await isFileExists(rootPackageJson)) {
buildDependencies.packageJson = [rootPackageJson];
}
const { tsconfigPath } = environmentContext;
if (tsconfigPath) {
buildDependencies.tsconfig = [tsconfigPath];
}
if (config._privateMeta?.configFilePath) {
buildDependencies.rsbuildConfig = [config._privateMeta.configFilePath];
}
if (await isFileExists(browserslistConfig)) {
buildDependencies.browserslistrc = [browserslistConfig];
}
const tailwindExts = ['ts', 'js', 'cjs', 'mjs'];
const configs = tailwindExts.map((ext) =>
join(context.rootPath, `tailwind.config.${ext}`),
);
const tailwindConfig = findExists(configs);
if (tailwindConfig) {
buildDependencies.tailwindcss = [tailwindConfig];
}
return {
...buildDependencies,
...userBuildDependencies,
};
} | /**
* Rspack can't detect the changes of framework config, tsconfig, tailwind config and browserslist config.
* but they will affect the compilation result, so they need to be added to buildDependencies.
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/cache.ts#L70-L112 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | getRsbuildOutputPath | const getRsbuildOutputPath = (): PathInfo | undefined => {
const { rootPath, distPath } = api.context;
const config = api.getNormalizedConfig();
const targetPath = join(distPath, RSBUILD_OUTPUTS_PATH);
const { enable } = normalizeCleanDistPath(config.output.cleanDistPath);
if (
enable === true ||
(enable === 'auto' && isStrictSubdir(rootPath, targetPath))
) {
return {
path: targetPath,
};
}
return undefined;
}; | // clean Rsbuild outputs files, such as the inspected config files | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/cleanOutput.ts#L50-L65 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | clonePostCSSConfig | const clonePostCSSConfig = (config: PostCSSOptions) => ({
...config,
plugins: config.plugins ? [...config.plugins] : undefined,
}); | // Create a new config object, | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/css.ts#L93-L96 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | updateSourceMappingURL | function updateSourceMappingURL({
source,
compilation,
publicPath,
type,
config,
}: {
source: string;
compilation: Rspack.Compilation;
publicPath: string;
type: 'js' | 'css';
config: NormalizedEnvironmentConfig;
}) {
const { devtool } = compilation.options;
if (
devtool &&
// If the source map is inlined, we do not need to update the sourceMappingURL
!devtool.includes('inline') &&
source.includes('# sourceMappingURL')
) {
const prefix = addTrailingSlash(
path.join(publicPath, config.output.distPath[type] || ''),
);
return source.replace(
/# sourceMappingURL=/,
`# sourceMappingURL=${prefix}`,
);
}
return source;
} | /**
* If we inlined the chunk to HTML,we should update the value of sourceMappingURL,
* because the relative path of source code has been changed.
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/inlineChunk.ts#L21-L53 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | applyBundleAnalyzeConfig | const applyBundleAnalyzeConfig = (
config: RsbuildConfig | EnvironmentConfig,
) => {
if (!config.performance?.bundleAnalyze) {
config.performance ??= {};
config.performance.bundleAnalyze = {
analyzerMode: 'disabled',
generateStatsFile: true,
};
} else {
config.performance.bundleAnalyze = {
generateStatsFile: true,
...(config.performance.bundleAnalyze || {}),
};
}
}; | // profile needs to be output to stats.json | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/performance.ts#L14-L29 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | singleVendor | function singleVendor(ctx: SplitChunksContext): SplitChunks {
const { override, defaultConfig, forceSplittingGroups } = ctx;
const singleVendorCacheGroup: CacheGroups = {
singleVendor: {
test: NODE_MODULES_REGEX,
priority: 0,
chunks: 'all',
name: 'vendor',
enforce: true,
},
};
return {
...defaultConfig,
...override,
cacheGroups: {
...defaultConfig.cacheGroups,
...singleVendorCacheGroup,
...forceSplittingGroups,
...override.cacheGroups,
},
};
} | // Ignore user defined cache group to get single vendor chunk. | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/plugins/splitChunks.ts#L184-L207 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | formatBasicTag | const formatBasicTag = (tag: HtmlTagObject): HtmlBasicTag => ({
tag: tag.tagName,
attrs: tag.attributes,
children: tag.innerHTML,
}); | /**
* `HtmlTagObject` -> `HtmlBasicTag`
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/rspack/RsbuildHtmlPlugin.ts#L95-L99 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | fromBasicTag | const fromBasicTag = (tag: HtmlBasicTag): HtmlTagObject => ({
meta: {},
tagName: tag.tag,
attributes: tag.attrs ?? {},
voidTag: VOID_TAGS.includes(tag.tag),
innerHTML: tag.children,
}); | /**
* `HtmlBasicTag` -> `HtmlTagObject`
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/rspack/RsbuildHtmlPlugin.ts#L104-L110 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | formatTags | const formatTags = (
tags: HtmlTagObject[],
override?: Partial<HtmlTag>,
): HtmlTag[] =>
tags.map((tag) => ({
...formatBasicTag(tag),
publicPath: false,
...override,
})); | /**
* `HtmlTagObject[]` -> `HtmlTag[]`
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/rspack/RsbuildHtmlPlugin.ts#L115-L123 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | isChunksFiltered | function isChunksFiltered(
chunkName: string,
includeChunks?: string[] | 'all',
excludeChunks?: string[],
): boolean {
// Skip if the chunks should be filtered and the given chunk was not added explicity
if (Array.isArray(includeChunks) && includeChunks.indexOf(chunkName) === -1) {
return false;
}
// Skip if the chunks should be filtered and the given chunk was excluded explicity
if (Array.isArray(excludeChunks) && excludeChunks.indexOf(chunkName) !== -1) {
return false;
}
// Add otherwise
return true;
} | // modify from html-rspack-plugin/index.js `filterChunks` | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/rspack/preload/helpers/doesChunkBelongToHtml.ts#L54-L69 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | formatDevConfig | const formatDevConfig = (
config: OriginDevConfig,
environments: Record<string, EnvironmentContext>,
): DevConfig => {
const writeToDiskValues = Object.values(environments).map(
(env) => env.config.dev.writeToDisk,
);
if (new Set(writeToDiskValues).size === 1) {
return {
...config,
writeToDisk: writeToDiskValues[0],
};
}
return {
...config,
writeToDisk(filePath: string, compilationName?: string) {
let { writeToDisk } = config;
if (compilationName && environments[compilationName]) {
writeToDisk =
environments[compilationName].config.dev.writeToDisk ?? writeToDisk;
}
return typeof writeToDisk === 'function'
? writeToDisk(filePath)
: writeToDisk!;
},
};
}; | // allow to configure dev.writeToDisk in environments | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/compilerDevMiddleware.ts#L38-L65 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | formatPrefix | const formatPrefix = (input: string | undefined) => {
let prefix = input;
if (prefix?.startsWith('./')) {
prefix = prefix.replace('./', '');
}
if (!prefix) {
return '/';
}
const hasLeadingSlash = prefix.startsWith('/');
const hasTailSlash = prefix.endsWith('/');
return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
}; | /**
* Make sure there is slash before and after prefix
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/helper.ts#L49-L63 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | openBrowser | async function openBrowser(url: string): Promise<boolean> {
// If we're on OS X, the user hasn't specifically
// requested a different browser, we can try opening
// a Chromium browser with AppleScript. This lets us reuse an
// existing tab when possible instead of creating a new one.
const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin';
if (shouldTryOpenChromeWithAppleScript) {
try {
const targetBrowser = await getTargetBrowser();
if (targetBrowser) {
// Try to reuse existing tab with AppleScript
await execAsync(
`osascript openChrome.applescript "${encodeURI(
url,
)}" "${targetBrowser}"`,
{
cwd: STATIC_PATH,
},
);
return true;
}
logger.debug('Failed to find the target browser.');
} catch (err) {
logger.debug('Failed to open start URL with apple script.');
logger.debug(err);
}
}
// Fallback to open
// (It will always open new tab)
try {
const { default: open } = await import('../../compiled/open/index.js');
await open(url);
return true;
} catch (err) {
logger.error('Failed to open start URL.');
logger.error(err);
return false;
}
} | /**
* This method is modified based on source found in
* https://github.com/facebook/create-react-app
*
* MIT Licensed
* Copyright (c) 2015-present, Facebook, Inc.
* https://github.com/facebook/create-react-app/blob/master/LICENSE
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/open.ts#L41-L82 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | RsbuildProdServer.onInit | public async onInit(app: Server | Http2SecureServer): Promise<void> {
this.app = app;
await this.applyDefaultMiddlewares();
} | // Complete the preparation of services | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/prodServer.ts#L52-L56 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | SocketServer.prepare | public async prepare(): Promise<void> {
const { default: ws } = await import('../../compiled/ws/index.js');
this.wsServer = new ws.Server({
noServer: true,
path: this.options.client?.path,
});
this.wsServer.on('error', (err: Error) => {
// only dev server, use default logger
logger.error(err);
});
this.timer = setInterval(() => {
for (const socket of this.wsServer.clients) {
const extWs = socket as ExtWebSocket;
if (!extWs.isAlive) {
extWs.terminate();
} else {
extWs.isAlive = false;
extWs.ping(() => {
// empty
});
}
}
}, 30000);
this.wsServer.on('connection', (socket, req) => {
// /rsbuild-hmr?compilationId=web
const queryStr = req.url ? req.url.split('?')[1] : '';
this.onConnect(
socket,
queryStr ? (parse(queryStr) as Record<string, string>) : {},
);
});
} | // create socket, install socket handler, bind socket event | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/socketServer.ts#L61-L96 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | SocketServer.sockWrite | public sockWrite({ type, compilationId, data }: SocketMessage): void {
for (const socket of this.sockets) {
this.send(socket, JSON.stringify({ type, data, compilationId }));
}
} | // write message to each socket | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/socketServer.ts#L109-L113 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | SocketServer.getStats | private getStats(name: string) {
const curStats = this.stats[name];
if (!curStats) {
return null;
}
const defaultStats: Record<string, boolean> = {
all: false,
hash: true,
assets: true,
warnings: true,
warningsCount: true,
errors: true,
errorsCount: true,
errorDetails: false,
entrypoints: true,
children: true,
moduleTrace: true,
};
const statsOptions = getStatsOptions(curStats.compilation.compiler);
return curStats.toJson({ ...defaultStats, ...statsOptions });
} | // get standard stats | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/socketServer.ts#L172-L195 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | SocketServer.sendStats | private sendStats({
force = false,
compilationId,
}: {
compilationId: string;
force?: boolean;
}) {
const stats = this.getStats(compilationId);
// this should never happened
if (!stats) {
return null;
}
// web-infra-dev/rspack#6633
// when initial-chunks change, reload the page
// e.g: ['index.js'] -> ['index.js', 'lib-polyfill.js']
const newInitialChunks: Set<string> = new Set();
if (stats.entrypoints) {
for (const entrypoint of Object.values(stats.entrypoints)) {
const chunks = entrypoint.chunks;
if (!Array.isArray(chunks)) {
continue;
}
for (const chunkName of chunks) {
if (!chunkName) {
continue;
}
newInitialChunks.add(String(chunkName));
}
}
}
const initialChunks = this.initialChunks[compilationId];
const shouldReload =
Boolean(stats.entrypoints) &&
Boolean(initialChunks) &&
!isEqualSet(initialChunks, newInitialChunks);
this.initialChunks[compilationId] = newInitialChunks;
if (shouldReload) {
return this.sockWrite({
type: 'static-changed',
compilationId,
});
}
const shouldEmit =
!force &&
stats &&
!stats.errorsCount &&
stats.assets &&
stats.assets.every((asset: any) => !asset.emitted);
if (shouldEmit) {
return this.sockWrite({
type: 'still-ok',
compilationId,
});
}
this.sockWrite({
type: 'hash',
compilationId,
data: stats.hash,
});
if (stats.errorsCount) {
const errors = getAllStatsErrors(stats);
const { errors: formattedErrors } = formatStatsMessages({
errors,
warnings: [],
});
return this.sockWrite({
type: 'errors',
compilationId,
data: {
text: formattedErrors,
html: genOverlayHTML(formattedErrors),
},
});
}
if (stats.warningsCount) {
const warnings = getAllStatsWarnings(stats);
const { warnings: formattedWarnings } = formatStatsMessages({
warnings,
errors: [],
});
return this.sockWrite({
type: 'warnings',
compilationId,
data: {
text: formattedWarnings,
},
});
}
return this.sockWrite({
type: 'ok',
compilationId,
});
} | // determine what message should send by stats | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/socketServer.ts#L198-L304 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | SocketServer.send | private send(connection: Ws, message: string) {
if (connection.readyState !== 1) {
return;
}
connection.send(message);
} | // send message to connecting socket | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/socketServer.ts#L307-L313 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | isGlob | const isGlob = (str: string): boolean => GLOB_REGEX.test(str); | /**
* A simple glob pattern checker.
* This can help us to avoid unnecessary tinyglobby import and call.
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/core/src/server/watchFiles.ts#L124-L124 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | compileRuntimeFile | async function compileRuntimeFile(filename: string) {
const sourceFilePath = path.join(
api.context.rootPath,
`src/runtime/${filename}.ts`,
);
const runtimeCode = await readFile(sourceFilePath, 'utf8');
const distPath = path.join(
api.context.distPath,
'runtime',
`${filename}.js`,
);
const distMinPath = path.join(
api.context.distPath,
'runtime',
`${filename}.min.js`,
);
const { code } = await transform(runtimeCode, {
jsc: {
target: 'es5',
parser: {
syntax: 'typescript',
},
},
// Output script file to be used in `<script>` tag
isModule: false,
sourceFileName: sourceFilePath,
});
const { code: minifiedRuntimeCode } = await minify(code, {
ecma: 5,
// allows SWC to mangle function names
module: true,
});
await Promise.all([
writeFile(distPath, code),
writeFile(distMinPath, minifiedRuntimeCode),
]);
} | /**
* transform `src/runtime/${filename}.ts`
* to `dist/runtime/${filename}.js` and `dist/runtime/${filename}.min.js`
*/ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-assets-retry/rslib.config.ts#L21-L61 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | modifyRuntimeModule | function modifyRuntimeModule(
module: any,
modifier: (originSource: string) => string,
isRspack: boolean,
) {
if (isRspack) {
modifyRspackRuntimeModule(module, modifier);
} else {
modifyWebpackRuntimeModule(module, modifier);
}
} | // https://github.com/web-infra-dev/rspack/pull/5370 | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-assets-retry/src/AsyncChunkRetryPlugin.ts#L37-L47 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | ensureChunk | function ensureChunk(chunkId: string): Promise<unknown> {
// biome-ignore lint/style/noArguments: allowed
const args = Array.prototype.slice.call(arguments);
// Other webpack runtimes would add arguments for `__webpack_require__.e`,
// So we use `arguments[10]` to avoid conflicts with other runtimes
if (!args[10]) {
args[10] = { count: 0, cssFailedCount: 0 };
}
const callingCounter: { count: number; cssFailedCount: number } = args[10];
const result = originalEnsureChunk.apply(
null,
args as Parameters<EnsureChunk>,
);
try {
const originalScriptFilename = originalGetChunkScriptFilename(chunkId);
const originalCssFilename = originalGetCssFilename(chunkId);
// mark the async chunk name in the global variables and share it with initial chunk retry to avoid duplicate retrying
if (typeof window !== 'undefined') {
if (originalScriptFilename) {
window.__RB_ASYNC_CHUNKS__[originalScriptFilename] = true;
}
if (originalCssFilename) {
window.__RB_ASYNC_CHUNKS__[originalCssFilename] = true;
}
}
} catch (e) {
console.error(ERROR_PREFIX, 'get original script or CSS filename error', e);
}
// if __webpack_require__.e is polluted by other runtime codes, fallback to originalEnsureChunk
if (
!callingCounter ||
typeof callingCounter.count !== 'number' ||
typeof callingCounter.cssFailedCount !== 'number'
) {
return result;
}
callingCounter.count += 1;
return result.catch((error: Error) => {
// the first calling is not retry
// if the failed request is 4 in network panel, callingCounter.count === 4, the first one is the normal request, and existRetryTimes is 3, retried 3 times
const existRetryTimesAll = callingCounter.count - 1;
const cssExistRetryTimes = callingCounter.cssFailedCount;
const jsExistRetryTimes = existRetryTimesAll - cssExistRetryTimes;
let originalScriptFilename: string;
let nextRetryUrl: string;
let nextDomain: string;
const isCssAsyncChunkLoadFailed = Boolean(
error?.message?.includes('CSS chunk'),
);
if (isCssAsyncChunkLoadFailed) {
callingCounter.cssFailedCount += 1;
}
const existRetryTimes = isCssAsyncChunkLoadFailed
? cssExistRetryTimes
: jsExistRetryTimes;
try {
const retryResult = nextRetry(
chunkId,
existRetryTimes,
isCssAsyncChunkLoadFailed,
);
originalScriptFilename = retryResult.originalScriptFilename;
nextRetryUrl = retryResult.nextRetryUrl;
nextDomain = retryResult.nextDomain;
} catch (e) {
console.error(ERROR_PREFIX, 'failed to get nextRetryUrl', e);
throw error;
}
const createContext = (times: number): AssetsRetryHookContext => ({
times,
domain: nextDomain,
url: nextRetryUrl,
tagName: isCssAsyncChunkLoadFailed ? 'link' : 'script',
isAsyncChunk: true,
});
const context = createContext(existRetryTimes);
if (existRetryTimes >= maxRetries) {
error.message = error.message?.includes('retries:')
? error.message
: `Loading chunk ${chunkId} from "${originalScriptFilename}" failed after ${maxRetries} retries: "${error.message}"`;
if (typeof config.onFail === 'function') {
config.onFail(context);
}
throw error;
}
// Filter by config.test and config.domain
let tester = config.test;
if (tester) {
if (typeof tester === 'string') {
const regexp = new RegExp(tester);
tester = (str: string) => regexp.test(str);
}
if (typeof tester !== 'function' || !tester(nextRetryUrl)) {
throw error;
}
}
if (config.domain && config.domain.indexOf(nextDomain) === -1) {
throw error;
}
// Start retry
if (typeof config.onRetry === 'function') {
config.onRetry(context);
}
const nextPromise = ensureChunk.apply(ensureChunk, args as [string]);
return nextPromise.then((result) => {
// when after retrying the third time
// ensureChunk(chunkId, { count: 3 }), at that time, existRetryTimes === 2
// at the end, callingCounter.count is 4
const isLastSuccessRetry =
callingCounter?.count === existRetryTimesAll + 2;
if (typeof config.onSuccess === 'function' && isLastSuccessRetry) {
const context = createContext(existRetryTimes + 1);
config.onSuccess(context);
}
return result;
});
});
} | // if users want to support es5, add Promise polyfill first https://github.com/webpack/webpack/issues/12877 | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-assets-retry/src/runtime/asyncChunkRetry.ts#L226-L361 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | findCurrentDomain | function findCurrentDomain(url: string, domains: string[]) {
let domain = '';
for (let i = 0; i < domains.length; i++) {
if (url.indexOf(domains[i]) !== -1) {
domain = domains[i];
break;
}
}
return domain || window.origin;
} | // this function is the same as async chunk retry | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-assets-retry/src/runtime/initialChunkRetry.ts#L23-L32 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | findNextDomain | function findNextDomain(url: string, domains: string[]) {
const currentDomain = findCurrentDomain(url, domains);
const index = domains.indexOf(currentDomain);
return domains[(index + 1) % domains.length] || url;
} | // this function is the same as async chunk retry | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-assets-retry/src/runtime/initialChunkRetry.ts#L35-L39 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | getUrlRetryQuery | function getUrlRetryQuery(existRetryTimes: number): string {
if (config.addQuery === true) {
return originalQuery !== ''
? `${originalQuery}&retry=${existRetryTimes}`
: `?retry=${existRetryTimes}`;
}
if (typeof config.addQuery === 'function') {
return config.addQuery({ times: existRetryTimes, originalQuery });
}
return '';
} | // this function is the same as async chunk retry | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-assets-retry/src/runtime/initialChunkRetry.ts#L242-L252 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | getNextRetryUrl | function getNextRetryUrl(
currRetryUrl: string,
domain: string,
nextDomain: string,
existRetryTimes: number,
) {
return (
cleanUrl(currRetryUrl.replace(domain, nextDomain)) +
getUrlRetryQuery(existRetryTimes + 1)
);
} | // this function is the same as async chunk retry | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-assets-retry/src/runtime/initialChunkRetry.ts#L255-L265 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | formatPath | const formatPath = (originPath: string) => {
if (isAbsolute(originPath)) {
return originPath.split(sep).join('/');
}
return originPath;
}; | // compatible with Windows path | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-babel/src/helper.ts#L31-L36 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | findRuleId | const findRuleId = (chain: RspackChain, defaultId: string) => {
let id = defaultId;
let index = 0;
while (chain.module.rules.has(id)) {
id = `${defaultId}-${++index}`;
}
return id;
}; | // Find a unique rule id for the less rule, | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-less/src/index.ts#L123-L130 | eabd31dfe3b5d99dcaae40c825152468798f864f |
rsbuild | github_2023 | web-infra-dev | typescript | patchGlobalLocation | function patchGlobalLocation() {
if (!global.location) {
const href = pathToFileURL(process.cwd()).href + path.sep;
const location = Object.freeze({ [GLOBAL_PATCHED_SYMBOL]: true, href });
global.location = location as unknown as Location;
}
} | /** fix issue about dart2js: https://github.com/dart-lang/sdk/issues/27979 */ | https://github.com/web-infra-dev/rsbuild/blob/eabd31dfe3b5d99dcaae40c825152468798f864f/packages/plugin-sass/src/helpers.ts#L14-L20 | eabd31dfe3b5d99dcaae40c825152468798f864f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.