repo_name
string | dataset
string | owner
string | lang
string | func_name
string | code
string | docstring
string | url
string | sha
string |
|---|---|---|---|---|---|---|---|---|
atomicals-js
|
github_2023
|
danieleth2
|
typescript
|
AtomicalOperationBuilder.addCommitChangeOutputIfRequired
|
addCommitChangeOutputIfRequired(
extraInputValue: number,
fee: FeeCalculations,
pbst: any,
address: string
) {
const totalInputsValue = extraInputValue;
const totalOutputsValue = this.getOutputValueForCommit(fee);
const calculatedFee = totalInputsValue - totalOutputsValue;
// It will be invalid, but at least we know we don't need to add change
if (calculatedFee <= 0) {
return;
}
// In order to keep the fee-rate unchanged, we should add extra fee for the new added change output.
const expectedFee =
fee.commitFeeOnly +
(this.options.satsbyte as any) * OUTPUT_BYTES_BASE;
// console.log('expectedFee', expectedFee);
const differenceBetweenCalculatedAndExpected =
calculatedFee - expectedFee;
if (differenceBetweenCalculatedAndExpected <= 0) {
return;
}
// There were some excess satoshis, but let's verify that it meets the dust threshold to make change
if (differenceBetweenCalculatedAndExpected >= DUST_AMOUNT) {
pbst.addOutput({
address: address,
value: differenceBetweenCalculatedAndExpected,
});
}
}
|
/**
* Adds an extra output at the end if it was detected there would be excess satoshis for the reveal transaction
* @param fee Fee calculations
* @returns
*/
|
https://github.com/danieleth2/atomicals-js/blob/02e854cc71c0f6c6559ff35c2093dc8d526b5d72/lib/utils/atomical-operation-builder.ts#L1212-L1242
|
02e854cc71c0f6c6559ff35c2093dc8d526b5d72
|
atomicals-js
|
github_2023
|
danieleth2
|
typescript
|
AtomicalOperationBuilder.finalSafetyCheckForExcessiveFee
|
static finalSafetyCheckForExcessiveFee(psbt: any, tx) {
let sumInputs = 0;
psbt.data.inputs.map((inp) => {
sumInputs += inp.witnessUtxo.value;
});
let sumOutputs = 0;
tx.outs.map((out) => {
sumOutputs += out.value;
});
if (sumInputs - sumOutputs > EXCESSIVE_FEE_LIMIT) {
throw new Error(
`Excessive fee detected. Hardcoded to ${EXCESSIVE_FEE_LIMIT} satoshis. Aborting due to protect funds. Contact developer`
);
}
}
|
/**
* a final safety check to ensure we don't accidentally broadcast a tx with too high of a fe
* @param psbt Partially signed bitcoin tx coresponding to the tx to calculate the total inputs values provided
* @param tx The tx to broadcast, uses the outputs to calculate total outputs
*/
|
https://github.com/danieleth2/atomicals-js/blob/02e854cc71c0f6c6559ff35c2093dc8d526b5d72/lib/utils/atomical-operation-builder.ts#L1249-L1263
|
02e854cc71c0f6c6559ff35c2093dc8d526b5d72
|
atomicals-js
|
github_2023
|
danieleth2
|
typescript
|
AtomicalOperationBuilder.resolveInputParent
|
static async resolveInputParent(
electrumxApi: ElectrumApiInterface,
parentId,
parentOwner: IWalletRecord
): Promise<ParentInputAtomical> {
const { atomicalInfo, locationInfo, inputUtxoPartial } =
await getAndCheckAtomicalInfo(
electrumxApi,
parentId,
parentOwner.address as any
);
const parentKeypairInput = ECPair.fromWIF(parentOwner.WIF as any);
const parentKeypairInputInfo = getKeypairInfo(parentKeypairInput);
const inp: ParentInputAtomical = {
parentId,
parentUtxoPartial: inputUtxoPartial,
parentKeyInfo: parentKeypairInputInfo,
};
return inp;
}
|
/**
* Helper function to resolve a parent atomical id and the wallet record into a format that's easily processable by setInputParent
* @param electrumxApi
* @param parentId
* @param parentOwner
*/
|
https://github.com/danieleth2/atomicals-js/blob/02e854cc71c0f6c6559ff35c2093dc8d526b5d72/lib/utils/atomical-operation-builder.ts#L1271-L1290
|
02e854cc71c0f6c6559ff35c2093dc8d526b5d72
|
moondream
|
github_2023
|
vikhyat
|
typescript
|
createMockResponse
|
function createMockResponse(data: any, status = 200): MockResponse {
const response = new EventEmitter() as MockResponse;
response.statusCode = status;
process.nextTick(() => {
response.emit('data', Buffer.from(JSON.stringify(data)));
response.emit('end');
});
return response;
}
|
// Helper to create mock response
|
https://github.com/vikhyat/moondream/blob/f102859c0be76997bbd43e6010dcf8d5583f4b46/clients/node/src/__tests__/moondream.test.ts#L41-L51
|
f102859c0be76997bbd43e6010dcf8d5583f4b46
|
moondream
|
github_2023
|
vikhyat
|
typescript
|
createMockStreamingResponse
|
function createMockStreamingResponse(chunks: string[], status = 200): MockResponse {
const response = new EventEmitter() as MockResponse;
response.statusCode = status;
// Emit chunks immediately
for (const chunk of chunks) {
response.emit('data', Buffer.from(chunk));
}
response.emit('end');
return response;
}
|
// Helper to create mock streaming response
|
https://github.com/vikhyat/moondream/blob/f102859c0be76997bbd43e6010dcf8d5583f4b46/clients/node/src/__tests__/moondream.test.ts#L54-L65
|
f102859c0be76997bbd43e6010dcf8d5583f4b46
|
moondream
|
github_2023
|
vikhyat
|
typescript
|
createMockRequest
|
function createMockRequest(): MockRequest {
const request = new EventEmitter() as MockRequest;
request.write = jest.fn();
request.end = jest.fn();
return request;
}
|
// Helper to create mock request
|
https://github.com/vikhyat/moondream/blob/f102859c0be76997bbd43e6010dcf8d5583f4b46/clients/node/src/__tests__/moondream.test.ts#L68-L73
|
f102859c0be76997bbd43e6010dcf8d5583f4b46
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
uploadChunk
|
const uploadChunk = async (uploadUrl: string, startByte: number, endByte: number) => {
const chunk = file.slice(startByte, endByte + 1)
return await fetch(uploadUrl, {
method: 'PUT',
headers: {
'Content-Range': `bytes ${startByte}-${endByte}/${file.size}`,
},
body: chunk,
}).catch((err) => {
throw new Error(err)
})
}
|
// const checkUploadStatus = async (uploadUrl: string) => {
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/FileManager.ts#L62-L74
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
getVolumeFromFrequencyData
|
const getVolumeFromFrequencyData = (frequencyData: Uint8Array, bufferLength: number) => {
const sum = frequencyData.reduce((acc, value) => acc + value, 0)
const average = sum / bufferLength
return average
}
|
// 辅助函数:从频谱数据计算音量
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/Recorder.ts#L150-L154
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
processAudio
|
const processAudio = () => {
// 获取频谱数据
const bufferLength = analyser.frequencyBinCount
const frequencyData = new Uint8Array(bufferLength)
analyser.getByteFrequencyData(frequencyData)
// 计算音量
const volume = getVolumeFromFrequencyData(frequencyData, bufferLength)
if (volume > this.volumeThreshold) {
// 重置静音计时器
clearTimeout(silenceTimer)
silenceTimer = null
} else {
// 声音低于阈值,判断为发言结束
if (!silenceTimer) {
silenceTimer = setTimeout(() => {
if (mediaRecorder.state === 'recording') {
mediaRecorder.stop()
}
cancelAnimationFrame(rafID)
this.isRecording = false
this.stopTimer()
}, this.silenceThreshold)
}
}
// 循环处理音频流
rafID = requestAnimationFrame(() => {
processAudio()
})
}
|
// 开始实时分析音频流
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/Recorder.ts#L157-L188
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
isValidInlineStringCNode
|
function isValidInlineStringCNode(cNode: Element) {
// Initial check to see if the passed node is a cNode
if (cNode.tagName.toLowerCase() != 'c') return false
if (cNode.getAttribute('t') != 'inlineStr') return false
const childNodesNamedIs = cNode.getElementsByTagName('is')
if (childNodesNamedIs.length != 1) return false
const childNodesNamedT = childNodesNamedIs[0].getElementsByTagName('t')
if (childNodesNamedT.length != 1) return false
return childNodesNamedT[0].childNodes[0] && childNodesNamedT[0].childNodes[0].nodeValue != ''
}
|
/** Function to check if the given c node is a valid inline string node. */
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/officeParser.ts#L342-L351
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
hasValidVNodeInCNode
|
function hasValidVNodeInCNode(cNode: Element) {
return (
cNode.getElementsByTagName('v')[0] &&
cNode.getElementsByTagName('v')[0].childNodes[0] &&
cNode.getElementsByTagName('v')[0].childNodes[0].nodeValue != ''
)
}
|
/** Function to check if the given c node has a valid v node */
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/officeParser.ts#L354-L360
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
extractAllTextsFromNode
|
function extractAllTextsFromNode(root: Element) {
let xmlTextArray: string[] = []
for (let i = 0; i < root.childNodes.length; i++) traversal(root.childNodes[i], xmlTextArray, true)
return xmlTextArray.join('')
}
|
/** Main dfs traversal function that goes from one node to its children and returns the value out. */
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/officeParser.ts#L503-L507
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
traversal
|
function traversal(node: ChildNode, xmlTextArray: string[], isFirstRecursion: boolean) {
if (!node.childNodes || node.childNodes.length == 0) {
if (node.parentNode?.nodeName.indexOf('text') == 0 && node.nodeValue) {
if (isNotesNode(node.parentNode) && (config.putNotesAtLast || config.ignoreNotes)) {
notesText.push(node.nodeValue)
if (allowedTextTags.includes(node.parentNode.nodeName) && !isFirstRecursion)
notesText.push(config.newlineDelimiter ?? '\n')
} else {
xmlTextArray.push(node.nodeValue)
if (allowedTextTags.includes(node.parentNode.nodeName) && !isFirstRecursion)
xmlTextArray.push(config.newlineDelimiter ?? '\n')
}
}
return
}
for (let i = 0; i < node.childNodes.length; i++) traversal(node.childNodes[i], xmlTextArray, false)
}
|
/** Traversal function that gets recursive calling. */
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/officeParser.ts#L509-L526
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
isNotesNode
|
function isNotesNode(node: Node) {
if (node.nodeName == notesTag) return true
if (node.parentNode) return isNotesNode(node.parentNode)
return false
}
|
/** Checks if the given node has an ancestor which is a notes tag. We use this information to put the notes in the response text and its position. */
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/officeParser.ts#L529-L533
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
isInvalidTextNode
|
function isInvalidTextNode(node: Node) {
if (allowedTextTags.includes(node.nodeName)) return true
if (node.parentNode) return isInvalidTextNode(node.parentNode)
return false
}
|
/** Checks if the given node has an ancestor which is also an allowed text tag. In that case, we ignore the child text tag. */
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/officeParser.ts#L536-L540
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
gemini-next-chat
|
github_2023
|
u14app
|
typescript
|
animateResponseText
|
const animateResponseText = () => {
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 30))
const fetchText = remainText.slice(0, fetchCount)
remainText = remainText.slice(fetchCount)
onMessage(fetchText)
requestAnimationFrame(animateResponseText)
} else {
if (chunks.length > 0) handleRemainingText()
}
}
|
// animate response to make it looks smooth
|
https://github.com/u14app/gemini-next-chat/blob/03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a/utils/textStream.ts#L47-L57
|
03665a4e0cbe2fb665d3c2a41e6ffb043f3cc33a
|
nextjs-sessionauth-template
|
github_2023
|
saasykits
|
typescript
|
createContext
|
const createContext = async (req: NextRequest) => {
return createTRPCContext({ headers: req.headers });
};
|
/**
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
* handling a HTTP request (e.g. when you make requests from Client Components).
*/
|
https://github.com/saasykits/nextjs-sessionauth-template/blob/6d0a4b31f322d9bfe84faf74f1281f651a6ca4a1/src/app/api/trpc/[trpc]/route.ts#L12-L14
|
6d0a4b31f322d9bfe84faf74f1281f651a6ca4a1
|
vaul-svelte
|
github_2023
|
huntabyte
|
typescript
|
keydown
|
function keydown(event: KeyboardEvent | undefined) {
if (event && event.key === "Escape") {
set(event);
}
// New subscriptions will not trigger immediately
set(undefined);
}
|
/**
* Event handler for keydown events on the document.
* Updates the store's value with the latest Escape Keydown event and then resets it to undefined.
*/
|
https://github.com/huntabyte/vaul-svelte/blob/e86ea13ac77d37a494520bb86766ecfa223852db/src/lib/internal/escape-keydown.ts#L18-L25
|
e86ea13ac77d37a494520bb86766ecfa223852db
|
vaul-svelte
|
github_2023
|
huntabyte
|
typescript
|
preventScrollStandard
|
function preventScrollStandard() {
if (typeof document === "undefined") return () => {};
const win = document.defaultView ?? window;
const { documentElement, body } = document;
const scrollbarWidth = win.innerWidth - documentElement.clientWidth;
const setScrollbarWidthProperty = () =>
setCSSProperty(documentElement, "--scrollbar-width", `${scrollbarWidth}px`);
const paddingProperty = getPaddingProperty(documentElement);
const scrollbarSidePadding = win.getComputedStyle(body)[paddingProperty];
return chain(
setScrollbarWidthProperty(),
setStyle(body, paddingProperty, `calc(${scrollbarSidePadding} + ${scrollbarWidth}px)`),
setStyle(body, "overflow", "hidden")
);
}
|
// For most browsers, all we need to do is set `overflow: hidden` on the root element, and
|
https://github.com/huntabyte/vaul-svelte/blob/e86ea13ac77d37a494520bb86766ecfa223852db/src/lib/internal/prevent-scroll.ts#L105-L121
|
e86ea13ac77d37a494520bb86766ecfa223852db
|
vaul-svelte
|
github_2023
|
huntabyte
|
typescript
|
preventScrollMobileSafari
|
function preventScrollMobileSafari() {
let scrollable: Element;
let lastY = 0;
const { documentElement, body, activeElement } = document;
function onTouchStart(e: TouchEvent) {
// Store the nearest scrollable parent element from the element that the user touched.
scrollable = getScrollParent(e.target as Element);
if (scrollable === documentElement && scrollable === body) return;
lastY = e.changedTouches[0].pageY;
}
function onTouchMove(e: TouchEvent) {
// Prevent scrolling the window.
if (!scrollable || scrollable === documentElement || scrollable === body) {
e.preventDefault();
return;
}
// Prevent scrolling up when at the top and scrolling down when at the bottom
// of a nested scrollable area, otherwise mobile Safari will start scrolling
// the window instead. Unfortunately, this disables bounce scrolling when at
// the top but it's the best we can do.
const y = e.changedTouches[0].pageY;
const scrollTop = scrollable.scrollTop;
const bottom = scrollable.scrollHeight - scrollable.clientHeight;
if (bottom === 0) return;
if ((scrollTop <= 0 && y > lastY) || (scrollTop >= bottom && y < lastY)) {
e.preventDefault();
}
lastY = y;
}
function onTouchEnd(e: TouchEvent) {
const target = e.target as HTMLElement;
if (!(isInput(target) && target !== activeElement)) return;
// Apply this change if we're not already focused on the target element
e.preventDefault();
// Apply a transform to trick Safari into thinking the input is at the top of the page
// so it doesn't try to scroll it into view. When tapping on an input, this needs to
// be done before the "focus" event, so we have to focus the element ourselves.
target.style.transform = "translateY(-2000px)";
target.focus();
requestAnimationFrame(() => {
target.style.transform = "";
});
}
function onFocus(e: FocusEvent) {
const target = e.target as HTMLElement;
if (!isInput(target)) return;
// Transform also needs to be applied in the focus event in cases where focus moves
// other than tapping on an input directly, e.g. the next/previous buttons in the
// software keyboard. In these cases, it seems applying the transform in the focus event
// is good enough, whereas when tapping an input, it must be done before the focus event. 🤷♂️
target.style.transform = "translateY(-2000px)";
requestAnimationFrame(() => {
target.style.transform = "";
// This will have prevented the browser from scrolling the focused element into view,
// so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
if (visualViewport) {
if (visualViewport.height < window.innerHeight) {
// If the keyboard is already visible, do this after one additional frame
// to wait for the transform to be removed.
requestAnimationFrame(() => {
scrollIntoView(target);
});
} else {
// Otherwise, wait for the visual viewport to resize before scrolling so we can
// measure the correct position to scroll to.
visualViewport.addEventListener("resize", () => scrollIntoView(target), { once: true });
}
}
});
}
function onWindowScroll() {
// Last resort. If the window scrolled, scroll it back to the top.
// It should always be at the top because the body will have a negative margin (see below).
window.scrollTo(0, 0);
}
// Record the original scroll position so we can restore it.
// Then apply a negative margin to the body to offset it by the scroll position. This will
// enable us to scroll the window to the top, which is required for the rest of this to work.
const scrollX = window.pageXOffset;
const scrollY = window.pageYOffset;
const restoreStyles = chain(
setStyle(
documentElement,
"paddingRight",
`${window.innerWidth - documentElement.clientWidth}px`
),
setStyle(documentElement, "overflow", "hidden")
// setStyle(document.body, 'marginTop', `-${scrollY}px`),
);
// Scroll to the top. The negative margin on the body will make this appear the same.
window.scrollTo(0, 0);
const removeEvents = chain(
addEventListener(document, "touchstart", onTouchStart, { passive: false, capture: true }),
addEventListener(document, "touchmove", onTouchMove, { passive: false, capture: true }),
addEventListener(document, "touchend", onTouchEnd, { passive: false, capture: true }),
addEventListener(document, "focus", onFocus, true),
addEventListener(window, "scroll", onWindowScroll)
);
return () => {
// Restore styles and scroll the page back to where it was.
restoreStyles();
removeEvents();
window.scrollTo(scrollX, scrollY);
};
}
|
// Mobile Safari is a whole different beast. Even with overflow: hidden,
|
https://github.com/huntabyte/vaul-svelte/blob/e86ea13ac77d37a494520bb86766ecfa223852db/src/lib/internal/prevent-scroll.ts#L149-L271
|
e86ea13ac77d37a494520bb86766ecfa223852db
|
vaul-svelte
|
github_2023
|
huntabyte
|
typescript
|
setStyle
|
function setStyle(element: HTMLElement, style: any, value: string) {
const cur = element.style[style];
element.style[style] = value;
return () => {
element.style[style] = cur;
};
}
|
// Sets a CSS property on an element, and returns a function to revert it to the previous value.
|
https://github.com/huntabyte/vaul-svelte/blob/e86ea13ac77d37a494520bb86766ecfa223852db/src/lib/internal/prevent-scroll.ts#L275-L282
|
e86ea13ac77d37a494520bb86766ecfa223852db
|
thumbmarkjs
|
github_2023
|
thumbmarkjs
|
typescript
|
integrate
|
const integrate = (f: (x: number) => number, a: number, b: number, n: number): number => {
const h = (b - a) / n;
let sum = 0;
for (let i = 0; i < n; i++) {
const x = a + (i + 0.5) * h;
sum += f(x);
}
return sum * h;
};
|
/** This might be a little excessive, but I wasn't sure what number to pick for some of the
* trigonometric functions. Using an integral here, so a few numbers are calculated. However,
* I do this mainly for those integrals that sum up to a small value, otherwise there's no point.
*/
|
https://github.com/thumbmarkjs/thumbmarkjs/blob/0115a34ad8d18a032db8572182427497862bfc7b/src/components/math/math.ts#L29-L37
|
0115a34ad8d18a032db8572182427497862bfc7b
|
thumbmarkjs
|
github_2023
|
thumbmarkjs
|
typescript
|
getApplePayVersion
|
function getApplePayVersion(): number {
if (window.location.protocol === 'https:' && typeof (window as any).ApplePaySession === 'function') {
try {
const versionCheck = (window as any).ApplePaySession.supportsVersion;
for (let i = 15; i > 0; i--) {
if (versionCheck(i)) {
return i;
}
}
} catch (error) {
return 0
}
}
return 0
}
|
/**
* @returns applePayCanMakePayments: boolean, applePayMaxSupportedVersion: number
*/
|
https://github.com/thumbmarkjs/thumbmarkjs/blob/0115a34ad8d18a032db8572182427497862bfc7b/src/components/system/system.ts#L23-L37
|
0115a34ad8d18a032db8572182427497862bfc7b
|
thumbmarkjs
|
github_2023
|
thumbmarkjs
|
typescript
|
logFingerprintData
|
async function logFingerprintData(thisHash: string, fingerprintData: componentInterface) {
const url = 'https://logging.thumbmarkjs.com/v1/log'
const payload = {
thumbmark: thisHash,
components: fingerprintData,
version: getVersion()
};
if (!sessionStorage.getItem("_tmjs_l")) {
sessionStorage.setItem("_tmjs_l", "1")
try {
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
} catch { } // do nothing
}
}
|
// Function to log the fingerprint data
|
https://github.com/thumbmarkjs/thumbmarkjs/blob/0115a34ad8d18a032db8572182427497862bfc7b/src/fingerprint/functions.ts#L99-L118
|
0115a34ad8d18a032db8572182427497862bfc7b
|
thumbmarkjs
|
github_2023
|
thumbmarkjs
|
typescript
|
encodeUtf8
|
function encodeUtf8(text: string): ArrayBuffer {
const encoder = new TextEncoder();
return encoder.encode(text).buffer;
}
|
/**
* This code is taken from https://github.com/LinusU/murmur-128/blob/master/index.js
* But instead of dependencies to encode-utf8 and fmix, I've implemented them here.
*/
|
https://github.com/thumbmarkjs/thumbmarkjs/blob/0115a34ad8d18a032db8572182427497862bfc7b/src/utils/hash.ts#L6-L9
|
0115a34ad8d18a032db8572182427497862bfc7b
|
calendar-remark
|
github_2023
|
xyxc0673
|
typescript
|
base64ToBlob
|
function base64ToBlob(base64: string): Blob | null {
// 正则表达式分割数据类型和Base64数据
const parts = base64.match(/^data:(.+);base64,(.+)$/);
if (parts === null) {
return null;
}
const contentType = parts[1];
const raw = window.atob(parts[2]);
const rawLength = raw.length;
const array = new Uint8Array(rawLength);
// 将字符转换为字节
for (let i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return new Blob([array], { type: contentType });
}
|
// 辅助函数:将Base64字符串转换为Blob对象
|
https://github.com/xyxc0673/calendar-remark/blob/1d8698ce39337ed0ded6e6d245a793191b7baae7/src/libs/download.ts#L28-L46
|
1d8698ce39337ed0ded6e6d245a793191b7baae7
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
readRulesFromCommand
|
function readRulesFromCommand(): Rule[] {
// do not handle the exception
const oxlintOutput = execSync(`npx oxlint --rules --format=json`, {
encoding: 'utf8',
stdio: 'pipe',
});
// do not handle the exception
return JSON.parse(oxlintOutput);
}
|
/**
* Read the rules from oxlint command and returns an array of Rule-Objects
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/scripts/traverse-rules.ts#L20-L29
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
fixScopeOfRule
|
function fixScopeOfRule(rule: Rule): void {
if (
rule.scope === 'react' &&
reactHookRulesInsideReactScope.includes(rule.value)
) {
rule.scope = 'react_hooks';
}
}
|
/**
* Some rules are in a different scope then in eslint
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/scripts/traverse-rules.ts#L34-L41
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
fixValueOfRule
|
function fixValueOfRule(rule: Rule): void {
if (rule.scope === 'eslint') {
return;
}
const scope =
rule.scope in aliasPluginNames ? aliasPluginNames[rule.scope] : rule.scope;
rule.value = `${scope}/${rule.value}`;
}
|
/**
* oxlint returns the value without a scope name
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/scripts/traverse-rules.ts#L46-L55
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
getAliasRules
|
function getAliasRules(rule: Rule): Rule | undefined {
if (
rule.scope === 'eslint' &&
typescriptRulesExtendEslintRules.includes(rule.value)
) {
return {
value: `@typescript-eslint/${rule.value}`,
scope: 'typescript',
category: rule.category,
};
}
if (rule.scope === 'jest' && viteTestCompatibleRules.includes(rule.value)) {
return {
value: `vitest/${rule.value}`,
scope: 'vitest',
category: rule.category,
};
}
if (
rule.scope === 'eslint' &&
unicornRulesExtendEslintRules.includes(rule.value)
) {
return {
value: `unicorn/${rule.value}`,
scope: 'unicorn',
category: rule.category,
};
}
}
|
/**
* some rules are reimplemented in another scope
* remap them so we can disable all the reimplemented too
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/scripts/traverse-rules.ts#L61-L91
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
getConfigContent
|
const getConfigContent = (
oxlintConfigFile: string
): OxlintConfig | undefined => {
try {
const content = fs.readFileSync(oxlintConfigFile, 'utf8');
try {
const configContent = JSONCParser.parse(content);
if (!isObject(configContent)) {
throw new TypeError('not an valid config file');
}
return configContent;
} catch {
console.error(
`eslint-plugin-oxlint: could not parse oxlint config file: ${oxlintConfigFile}`
);
return undefined;
}
} catch {
console.error(
`eslint-plugin-oxlint: could not find oxlint config file: ${oxlintConfigFile}`
);
return undefined;
}
};
|
/**
* tries to read the oxlint config file and returning its JSON content.
* if the file is not found or could not be parsed, undefined is returned.
* And an error message will be emitted to `console.error`
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/src/build-from-oxlint-config/index.ts#L33-L59
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
isValueInSet
|
const isValueInSet = (value: unknown, validSet: unknown[]) =>
validSet.includes(value) ||
(Array.isArray(value) && validSet.includes(value[0]));
|
/**
* checks if value is validSet, or if validSet is an array, check if value is first value of it
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/src/build-from-oxlint-config/rules.ts#L60-L62
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
isDeactivateValue
|
const isDeactivateValue = (value: unknown) => isValueInSet(value, ['off', 0]);
|
/**
* check if the value is "off", 0, ["off", ...], or [0, ...]
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/src/build-from-oxlint-config/rules.ts#L67-L67
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
eslint-plugin-oxlint
|
github_2023
|
oxc-project
|
typescript
|
isActiveValue
|
const isActiveValue = (value: unknown) =>
isValueInSet(value, ['error', 'warn', 1, 2]);
|
/**
* check if the value is "error", "warn", 1, 2, ["error", ...], ["warn", ...], [1, ...], or [2, ...]
*/
|
https://github.com/oxc-project/eslint-plugin-oxlint/blob/13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297/src/build-from-oxlint-config/rules.ts#L72-L73
|
13b20c7e5bdfd3cd791bd8876c7ee7700cfd5297
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
IMPORTER
|
const IMPORTER = (filePath: string) => {
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href)
}
return import(filePath)
}
|
/**
* The importer is used to import files in context of the
* application.
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/docs/bin/build.ts#L27-L32
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
exportHTML
|
async function exportHTML() {
const { collections } = await import('#src/collections')
const { default: ace } = await import('@adonisjs/core/services/ace')
const { default: app } = await import('@adonisjs/core/services/app')
for (const collection of collections) {
for (const entry of collection.all()) {
try {
const output = await entry.writeToDisk(app.makePath('dist'), { collection, entry })
ace.ui.logger.action(`create ${output.filePath}`).succeeded()
} catch (error) {
ace.ui.logger.action(`create ${entry.permalink}`).failed(error)
}
}
}
}
|
/**
* Exports collection to HTML files
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/docs/bin/build.ts#L37-L52
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
IMPORTER
|
const IMPORTER = (filePath: string) => {
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href)
}
return import(filePath)
}
|
/**
* The importer is used to import files in context of the
* application.
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/docs/bin/serve.ts#L30-L35
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
defineRoutes
|
async function defineRoutes(app: ApplicationService) {
const { default: server } = await import('@adonisjs/core/services/server')
const { collections } = await import('#src/collections')
const { default: router } = await import('@adonisjs/core/services/router')
server.use([() => import('@adonisjs/static/static_middleware')])
const redirects = await readFile(app.publicPath('_redirects'), 'utf-8')
const redirectsCollection = redirects.split('\n').reduce(
(result, line) => {
const [from, to] = line.split(' ')
result[from] = to
return result
},
{} as Record<string, string>,
)
router.get('*', async ({ request, response }) => {
if (redirectsCollection[request.url()]) {
return response.redirect(redirectsCollection[request.url()])
}
for (const collection of collections) {
await collection.refresh()
const entry = collection.findByPermalink(request.url())
if (entry) {
return entry.render({ collection, entry })
}
}
return response.notFound('Page not found')
})
}
|
/**
* Defining routes for development server
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/docs/bin/serve.ts#L40-L72
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.getOwner
|
getOwner() {
return this.#owner
}
|
/**
* Returns the owner ID
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L47-L49
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.serialize
|
serialize(): SerializedLock {
return {
key: this.#key,
owner: this.#owner,
ttl: this.#ttl,
expirationTime: this.#expirationTime,
}
}
|
/**
* Serialize the lock
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L54-L61
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.acquire
|
async acquire(options: LockAcquireOptions = {}) {
this.#expirationTime = null
let attemptsDone = 0
const attemptsMax = options.retry?.attempts ?? this.#config.retry.attempts
const delay = resolveDuration(options.retry?.delay, this.#config.retry.delay)
const timeout = resolveDuration(options.retry?.timeout, this.#config.retry.timeout)
const start = Date.now()
while (attemptsDone++ < attemptsMax) {
const now = Date.now()
/**
* Try to acquire the lock
*/
const result = await this.#lockStore.save(this.#key, this.#owner, this.#ttl)
if (result) {
this.#expirationTime = this.#ttl ? now + this.#ttl : null
break
}
/**
* Check if we reached the maximum number of attempts
*/
if (attemptsDone === attemptsMax) return false
/**
* Or check if we reached the timeout
*/
const elapsed = Date.now() - start
if (timeout && elapsed > timeout) return false
/**
* Otherwise wait for the delay and try again
*/
await setTimeout(delay)
}
this.#config.logger.debug({ key: this.#key }, 'Lock acquired')
return true
}
|
/**
* Acquire the lock
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L66-L106
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.acquireImmediately
|
async acquireImmediately() {
const result = await this.#lockStore.save(this.#key, this.#owner, this.#ttl)
if (!result) return false
this.#expirationTime = this.#ttl ? Date.now() + this.#ttl : null
this.#config.logger.debug({ key: this.#key }, 'Lock acquired with acquireImmediately()')
return true
}
|
/**
* Try to acquire the lock immediately or throw an error
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L111-L118
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.run
|
async run<T>(callback: () => Promise<T>): Promise<[true, T] | [false, null]> {
const handle = await this.acquire()
if (!handle) return [false, null]
try {
const result = await callback()
return [true, result]
} finally {
await this.release()
}
}
|
/**
* Acquire the lock, run the callback and release the lock automatically
* after the callback is done.
* Also returns the callback return value
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L125-L135
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.runImmediately
|
async runImmediately<T>(callback: () => Promise<T>): Promise<[true, T] | [false, null]> {
const handle = await this.acquireImmediately()
if (!handle) return [false, null]
try {
const result = await callback()
return [true, result]
} finally {
if (handle) await this.release()
}
}
|
/**
* Same as `run` but try to acquire the lock immediately
* Or throw an error if the lock is already acquired
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L141-L151
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.forceRelease
|
async forceRelease() {
await this.#lockStore.forceDelete(this.#key)
}
|
/**
* Force release the lock
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L156-L158
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.release
|
async release() {
await this.#lockStore.delete(this.#key, this.#owner)
this.#config.logger.debug({ key: this.#key }, 'Lock released')
}
|
/**
* Release the lock
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L163-L166
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.isExpired
|
isExpired() {
if (this.#expirationTime === null) return false
return this.#expirationTime < Date.now()
}
|
/**
* Returns true if the lock is expired
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L171-L174
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.getRemainingTime
|
getRemainingTime() {
if (this.#expirationTime === null) return null
return this.#expirationTime - Date.now()
}
|
/**
* Get the remaining time before the lock expires
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L179-L182
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.extend
|
async extend(ttl?: Duration) {
const resolvedTtl = ttl ? resolveDuration(ttl) : this.#ttl
if (!resolvedTtl) throw new InvalidArgumentsException('Cannot extend a lock without TTL')
const now = Date.now()
await this.#lockStore.extend(this.#key, this.#owner, resolvedTtl)
this.#expirationTime = now + resolvedTtl
this.#config.logger.debug({ key: this.#key, newTtl: this.#expirationTime }, 'Lock extended')
}
|
/**
* Extends the lock TTL
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L187-L196
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Lock.isLocked
|
async isLocked() {
return await this.#lockStore.exists(this.#key)
}
|
/**
* Returns true if the lock is currently locked
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock.ts#L201-L203
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
LockFactory.createLock
|
createLock(name: string, ttl: Duration = LockFactory.#kDefaults.ttl) {
return new Lock(name, this.#store, this.#config, undefined, resolveDuration(ttl))
}
|
/**
* Create a new lock
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock_factory.ts#L51-L53
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
LockFactory.restoreLock
|
restoreLock(lock: SerializedLock) {
return new Lock(lock.key, this.#store, this.#config, lock.owner, lock.ttl, lock.expirationTime)
}
|
/**
* Restore a lock from a previous owner. This is particularly useful
* if you want to release a lock from a different process than the one
* that acquired it.
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/lock_factory.ts#L60-L62
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Verrou.use
|
use<T extends keyof KnownStores>(store: T) {
const storeToUse: keyof KnownStores | undefined = store ?? this.#defaultStoreName
if (!storeToUse) throw new Error('No store provided')
if (this.#storesCache.has(storeToUse)) {
return this.#storesCache.get(storeToUse)!
}
const factory = new LockFactory(this.#stores[storeToUse]!.driver.factory(), {
logger: this.#logger,
})
this.#storesCache.set(storeToUse, factory)
return factory
}
|
/**
* Access a store by its name
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/verrou.ts#L41-L56
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Verrou.createLock
|
createLock(name: string, ttl?: Duration) {
return this.use(this.#defaultStoreName).createLock(name, ttl)
}
|
/**
* Create a new lock using the default store
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/verrou.ts#L61-L63
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
Verrou.restoreLock
|
restoreLock(lock: SerializedLock) {
return this.use(this.#defaultStoreName).restoreLock(lock)
}
|
/**
* Restore a lock from a previous owner. This is particularly useful
* if you want to release a lock from a different process than the one
* that acquired it.
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/verrou.ts#L70-L72
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DatabaseStore.save
|
async save(key: string, owner: string, ttl: number | null) {
await this.#initialized
try {
await this.#adapter.insertLock({ key, owner, expiration: this.#computeExpiresAt(ttl) })
return true
} catch {
const updatedRows = await this.#adapter.acquireLock({
key,
owner,
expiration: this.#computeExpiresAt(ttl),
})
return updatedRows > 0
}
}
|
/**
* Save the lock in the store if not already locked by another owner
*
* We basically rely on primary key constraint to ensure the lock is
* unique.
*
* If the lock already exists, we check if it's expired. If it is, we
* update it with the new owner and expiration date.
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/database.ts#L51-L65
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DatabaseStore.delete
|
async delete(key: string, owner: string): Promise<void> {
const currentOwner = await this.#getCurrentOwner(key)
if (currentOwner !== owner) throw new E_LOCK_NOT_OWNED()
await this.#adapter.deleteLock(key, owner)
}
|
/**
* Delete the lock from the store if it is owned by the owner
* Otherwise throws a E_LOCK_NOT_OWNED error
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/database.ts#L71-L76
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DatabaseStore.forceDelete
|
async forceDelete(key: string) {
await this.#adapter.deleteLock(key)
}
|
/**
* Force delete the lock from the store. No check is made on the owner
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/database.ts#L81-L83
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DatabaseStore.extend
|
async extend(key: string, owner: string, duration: number) {
await this.#initialized
const updated = await this.#adapter.extendLock(key, owner, duration)
if (updated === 0) throw new E_LOCK_NOT_OWNED()
}
|
/**
* Extend the lock expiration. Throws an error if the lock is not owned by the owner
* Duration is in milliseconds
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/database.ts#L89-L94
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DatabaseStore.exists
|
async exists(key: string) {
await this.#initialized
const lock = await this.#adapter.getLock(key)
if (!lock) return false
if (lock.expiration === null) return true
return lock.expiration > Date.now()
}
|
/**
* Check if the lock exists
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/database.ts#L99-L107
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DynamoDBStore.save
|
async save(key: string, owner: string, ttl: number | null) {
await this.#initialized
try {
const command = new PutItemCommand({
TableName: this.#tableName,
Item: {
key: { S: key },
owner: { S: owner },
...(ttl ? { expires_at: { N: (Date.now() + ttl).toString() } } : {}),
},
ConditionExpression: 'attribute_not_exists(#key) OR #expires_at < :now',
ExpressionAttributeNames: {
'#key': 'key',
'#expires_at': 'expires_at',
},
ExpressionAttributeValues: { ':now': { N: Date.now().toString() } },
})
const result = await this.#connection.send(command)
return result.$metadata.httpStatusCode === 200
} catch (err) {
if (err instanceof ConditionalCheckFailedException) return false
throw err
}
}
|
/**
* Save the lock in the store if not already locked by another owner
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/dynamodb.ts#L66-L91
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DynamoDBStore.delete
|
async delete(key: string, owner: string) {
const command = new DeleteItemCommand({
TableName: this.#tableName,
Key: { key: { S: key } },
ConditionExpression: '#owner = :owner',
ExpressionAttributeNames: { '#owner': 'owner' },
ExpressionAttributeValues: { ':owner': { S: owner } },
})
try {
await this.#connection.send(command)
} catch {
throw new E_LOCK_NOT_OWNED()
}
}
|
/**
* Delete the lock from the store if it is owned by the owner
* Otherwise throws a E_LOCK_NOT_OWNED error
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/dynamodb.ts#L97-L111
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DynamoDBStore.forceDelete
|
async forceDelete(key: string) {
const command = new DeleteItemCommand({
TableName: this.#tableName,
Key: { key: { S: key } },
})
await this.#connection.send(command)
}
|
/**
* Force delete the lock from the store. No check is made on the owner
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/dynamodb.ts#L116-L123
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DynamoDBStore.exists
|
async exists(key: string) {
await this.#initialized
const command = new GetItemCommand({
TableName: this.#tableName,
Key: { key: { S: key } },
})
const result = await this.#connection.send(command)
const isExpired = result.Item?.expires_at?.N && result.Item.expires_at.N < Date.now().toString()
return result.Item !== undefined && !isExpired
}
|
/**
* Check if the lock exists
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/dynamodb.ts#L128-L139
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
DynamoDBStore.extend
|
async extend(key: string, owner: string, duration: number) {
const command = new PutItemCommand({
TableName: this.#tableName,
Item: {
key: { S: key },
owner: { S: owner },
expires_at: { N: (Date.now() + duration).toString() },
},
ConditionExpression: '#owner = :owner',
ExpressionAttributeNames: { '#owner': 'owner' },
ExpressionAttributeValues: { ':owner': { S: owner } },
})
try {
await this.#connection.send(command)
} catch {
throw new E_LOCK_NOT_OWNED()
}
}
|
/**
* Extend the lock expiration. Throws an error if the lock is not owned by the owner
* Duration is in milliseconds
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/dynamodb.ts#L145-L163
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
MemoryStore.getOrCreateForKey
|
getOrCreateForKey(key: string, owner: string) {
let lock = this.#locks.get(key)
if (!lock) {
lock = { mutex: new Mutex(), owner }
this.#locks.set(key, lock)
}
return lock
}
|
/**
* For a given key, get or create a new lock
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/memory.ts#L27-L35
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
MemoryStore.extend
|
async extend(key: string, owner: string, duration: number) {
const lock = this.#locks.get(key)
if (!lock || lock.owner !== owner) throw new E_LOCK_NOT_OWNED()
lock.expiresAt = this.#computeExpiresAt(duration)
}
|
/**
* Extend the lock expiration. Throws an error if the lock is not owned by the owner
* Duration is in milliseconds
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/memory.ts#L55-L60
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
MemoryStore.save
|
async save(key: string, owner: string, ttl: number | null) {
try {
const lock = this.getOrCreateForKey(key, owner)
if (this.#isLockEntryExpired(lock)) lock.releaser?.()
lock.releaser = await tryAcquire(lock.mutex).acquire()
lock.expiresAt = this.#computeExpiresAt(ttl)
return true
} catch {
return false
}
}
|
/**
* Save the lock in the store if not already locked by another owner
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/memory.ts#L65-L78
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
MemoryStore.delete
|
async delete(key: string, owner: string) {
const mutex = this.#locks.get(key)
if (!mutex || !mutex.releaser) return
if (mutex.owner !== owner) throw new E_LOCK_NOT_OWNED()
mutex.releaser()
this.#locks.delete(key)
}
|
/**
* Delete the lock from the store if it is owned by the owner
* Otherwise throws a E_LOCK_NOT_OWNED error
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/memory.ts#L84-L92
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
MemoryStore.forceDelete
|
async forceDelete(key: string) {
const lock = this.#locks.get(key)
if (!lock) return
lock.releaser?.()
}
|
/**
* Force delete the lock from the store. No check is made on the owner
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/memory.ts#L97-L102
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
MemoryStore.exists
|
async exists(key: string) {
const lock = this.#locks.get(key)
if (!lock || this.#isLockEntryExpired(lock)) return false
return lock.mutex.isLocked()
}
|
/**
* Check if the lock exists
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/memory.ts#L107-L112
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
RedisStore.save
|
async save(key: string, owner: string, ttl: number | null) {
if (ttl) {
const result = await this.#connection.set(key, owner, 'PX', ttl, 'NX')
return result === 'OK'
}
const result = await this.#connection.setnx(key, owner)
return result === 1
}
|
/**
* Save the lock in the store if not already locked by another owner
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/redis.ts#L26-L34
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
RedisStore.delete
|
async delete(key: string, owner: string) {
const lua = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
`
const result = await this.#connection.eval(lua, 1, key, owner)
if (result === 0) throw new E_LOCK_NOT_OWNED()
}
|
/**
* Delete the lock from the store if it is owned by the owner
* Otherwise throws a E_LOCK_NOT_OWNED error
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/redis.ts#L40-L51
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
RedisStore.forceDelete
|
async forceDelete(key: string) {
await this.#connection.del(key)
}
|
/**
* Force delete the lock from the store. No check is made on the owner
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/redis.ts#L56-L58
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
RedisStore.exists
|
async exists(key: string): Promise<boolean> {
const result = await this.#connection.get(key)
return !!result
}
|
/**
* Check if the lock exists
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/redis.ts#L63-L66
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
RedisStore.extend
|
async extend(key: string, owner: string, duration: number) {
const lua = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("pexpire", KEYS[1], ARGV[2])
else
return 0
end
`
const result = await this.#connection.eval(lua, 1, key, owner, duration)
if (result === 0) throw new E_LOCK_NOT_OWNED()
}
|
/**
* Extend the lock expiration. Throws an error if the lock is not owned by the owner
* Duration is in milliseconds
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/packages/verrou/src/drivers/redis.ts#L72-L83
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
getProduct
|
async function getProduct(productId: string) {
await setTimeout(200)
return products.find((product) => product.id === productId)!
}
|
/**
* Get a product by its ID.
* Simulate a database call by waiting 200ms
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/playground/src/index.ts#L31-L34
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
verrou
|
github_2023
|
Julien-R44
|
typescript
|
updateProductStock
|
async function updateProductStock(productId: string, stock: number) {
const product = await getProduct(productId)
product.stock = stock
}
|
/**
* Update the stock of a product
*/
|
https://github.com/Julien-R44/verrou/blob/25567583d07662e8f331dcfdb2e2cd8065713929/playground/src/index.ts#L39-L42
|
25567583d07662e8f331dcfdb2e2cd8065713929
|
unwasm
|
github_2023
|
unjs
|
typescript
|
getESMImportInstantiate
|
function getESMImportInstantiate(asset: WasmAsset, importsCode: string) {
return /* js */ `
${importsCode}
async function _instantiate(imports = _imports) {
const _mod = await import("${UNWASM_EXTERNAL_PREFIX}${asset.name}").then(r => r.default || r);
return WebAssembly.instantiate(_mod, imports)
}
`;
}
|
/** Get the code to instantiate module with direct import */
|
https://github.com/unjs/unwasm/blob/0262848009b3a6f3310dc6fa3212be476fbf420d/src/plugin/runtime/binding.ts#L44-L53
|
0262848009b3a6f3310dc6fa3212be476fbf420d
|
unwasm
|
github_2023
|
unjs
|
typescript
|
getBase64Instantiate
|
function getBase64Instantiate(asset: WasmAsset, importsCode: string) {
return /* js */ `
import { base64ToUint8Array } from "${UMWASM_HELPERS_ID}";
${importsCode}
function _instantiate(imports = _imports) {
const _data = base64ToUint8Array("${asset.source.toString("base64")}")
return WebAssembly.instantiate(_data, imports) }
`;
}
|
/** Get the code to instantiate module from inlined base64 data */
|
https://github.com/unjs/unwasm/blob/0262848009b3a6f3310dc6fa3212be476fbf420d/src/plugin/runtime/binding.ts#L56-L66
|
0262848009b3a6f3310dc6fa3212be476fbf420d
|
unwasm
|
github_2023
|
unjs
|
typescript
|
getExports
|
function getExports(asset: WasmAsset, instantiateCode: string) {
return /* js */ `
import { getExports } from "${UMWASM_HELPERS_ID}";
${instantiateCode}
const $exports = getExports(await _instantiate());
${asset.exports
.map((name) => `export const ${name} = $exports.${name};`)
.join("\n")}
const defaultExport = () => $exports;
${asset.exports.map((name) => `defaultExport["${name}"] = $exports.${name};`).join("\n")}
export default defaultExport;
`;
}
|
/** Get the exports code with top level await support */
|
https://github.com/unjs/unwasm/blob/0262848009b3a6f3310dc6fa3212be476fbf420d/src/plugin/runtime/binding.ts#L69-L85
|
0262848009b3a6f3310dc6fa3212be476fbf420d
|
unwasm
|
github_2023
|
unjs
|
typescript
|
getLazyExports
|
function getLazyExports(asset: WasmAsset, instantiateCode: string) {
return /* js */ `
import { createLazyWasmModule } from "${UMWASM_HELPERS_ID}";
${instantiateCode}
const _mod = createLazyWasmModule(_instantiate);
${asset.exports
.map((name) => `export const ${name} = _mod.${name};`)
.join("\n")}
export default _mod;
`;
}
|
/** Proxied exports when imports are needed or we can't have top-level await */
|
https://github.com/unjs/unwasm/blob/0262848009b3a6f3310dc6fa3212be476fbf420d/src/plugin/runtime/binding.ts#L88-L102
|
0262848009b3a6f3310dc6fa3212be476fbf420d
|
unwasm
|
github_2023
|
unjs
|
typescript
|
_rollupBuild
|
async function _rollupBuild(
entry: string,
name: string,
pluginOpts: UnwasmPluginOptions,
) {
const build = await rollup({
input: r(entry),
plugins: [rollupNodeResolve({}), unwasmRollup(pluginOpts)],
});
return await build.write({
format: "esm",
entryFileNames: "index.mjs",
chunkFileNames: "[name].mjs",
dir: r(`.tmp/${name}`),
});
}
|
// --- Utils ---
|
https://github.com/unjs/unwasm/blob/0262848009b3a6f3310dc6fa3212be476fbf420d/test/plugin.test.ts#L55-L70
|
0262848009b3a6f3310dc6fa3212be476fbf420d
|
y-durableobjects
|
github_2023
|
napolab
|
typescript
|
createYDocMessage
|
const createYDocMessage = (content: string = "Hello World!") => {
const doc = new Doc();
doc.getText("root").insert(0, content);
return encodeStateAsUpdate(doc);
};
|
// Helper to create updates based on document type
|
https://github.com/napolab/y-durableobjects/blob/91cdbc266721feb66d004917392cdcd2769e4eea/src/yjs/remote/ws-shared-doc.test.ts#L14-L19
|
91cdbc266721feb66d004917392cdcd2769e4eea
|
y-durableobjects
|
github_2023
|
napolab
|
typescript
|
createSyncMessage
|
const createSyncMessage = (update: Uint8Array) => {
const encoder = createEncoder();
writeVarUint(encoder, messageType.sync);
writeUpdate(encoder, update);
return toUint8Array(encoder);
};
|
// Helper to create an encoded message from an update
|
https://github.com/napolab/y-durableobjects/blob/91cdbc266721feb66d004917392cdcd2769e4eea/src/yjs/remote/ws-shared-doc.test.ts#L22-L28
|
91cdbc266721feb66d004917392cdcd2769e4eea
|
y-durableobjects
|
github_2023
|
napolab
|
typescript
|
applyMessage
|
const applyMessage = (message: Uint8Array) => {
const receivedDoc = new Doc();
const decoder = createDecoder(message);
readVarUint(decoder);
readSyncMessage(decoder, createEncoder(), receivedDoc, null);
return receivedDoc;
};
|
// Helper to apply a received message to a new document
|
https://github.com/napolab/y-durableobjects/blob/91cdbc266721feb66d004917392cdcd2769e4eea/src/yjs/remote/ws-shared-doc.test.ts#L31-L38
|
91cdbc266721feb66d004917392cdcd2769e4eea
|
y-durableobjects
|
github_2023
|
napolab
|
typescript
|
YTransactionStorageImpl.constructor
|
constructor(
private readonly storage: TransactionStorage,
options?: Options,
) {
this.MAX_BYTES = options?.maxBytes ?? 10 * 1024;
if (this.MAX_BYTES > 128 * 1024) {
// https://developers.cloudflare.com/durable-objects/platform/limits/
throw new Error("maxBytes must be less than 128KB");
}
this.MAX_UPDATES = options?.maxUpdates ?? 500;
}
|
// eslint-disable-next-line no-useless-constructor
|
https://github.com/napolab/y-durableobjects/blob/91cdbc266721feb66d004917392cdcd2769e4eea/src/yjs/storage/index.ts#L31-L42
|
91cdbc266721feb66d004917392cdcd2769e4eea
|
comfyui-on-eks
|
github_2023
|
aws-samples
|
typescript
|
addLightWeightNodeGroup
|
function addLightWeightNodeGroup(): blueprints.ManagedNodeGroup {
return {
id: `AL2-MNG-LW-${PROJECT_NAME}`.replace(/-$/,''),
amiType: NodegroupAmiType.AL2_X86_64,
instanceTypes: [new ec2.InstanceType('t3a.xlarge')],
nodeRole: blueprints.getNamedResource("node-role") as iam.Role,
minSize: 1,
desiredSize: 2,
maxSize: 5,
nodeGroupSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
launchTemplate: {
tags: {
"Name": `Comfyui-EKS-LW-Node-${PROJECT_NAME}`.replace(/-$/,'')
}
}
};
}
|
// Node Group for lightweight workloads
|
https://github.com/aws-samples/comfyui-on-eks/blob/babf2c034bab7c6e481b98c111a083bc1183d75d/lib/comfyui-on-eks-stack.ts#L94-L110
|
babf2c034bab7c6e481b98c111a083bc1183d75d
|
fabric
|
github_2023
|
danielmiessler
|
typescript
|
handleError
|
function handleError(error: Error | string) {
const errorMessage = error instanceof ChatError
? `${error.code}: ${error.message}`
: error instanceof Error
? error.message
: error;
errorStore.set(errorMessage);
streamingStore.set(false);
return errorMessage;
}
|
// Error handling utility
|
https://github.com/danielmiessler/fabric/blob/2331d011c1a164845b263017cfbe46cd77c2305d/web/src/lib/store/chat-store.ts#L39-L49
|
2331d011c1a164845b263017cfbe46cd77c2305d
|
ui
|
github_2023
|
shadcn-ui
|
typescript
|
getTasks
|
async function getTasks() {
const data = await fs.readFile(
path.join(process.cwd(), "app/(app)/examples/tasks/data/tasks.json")
)
const tasks = JSON.parse(data.toString())
return z.array(taskSchema).parse(tasks)
}
|
// Simulate a database read for tasks.
|
https://github.com/shadcn-ui/ui/blob/4810f744e3b5ec23e7fcac14b8377448055e9560/apps/www/app/(app)/examples/tasks/page.tsx#L18-L26
|
4810f744e3b5ec23e7fcac14b8377448055e9560
|
ui
|
github_2023
|
shadcn-ui
|
typescript
|
fetchProjects
|
async function fetchProjects() {
await new Promise((resolve) => setTimeout(resolve, 3000))
return projects
}
|
// Dummy fetch function
|
https://github.com/shadcn-ui/ui/blob/4810f744e3b5ec23e7fcac14b8377448055e9560/apps/www/registry/default/internal/sidebar-rsc.tsx#L51-L54
|
4810f744e3b5ec23e7fcac14b8377448055e9560
|
ui
|
github_2023
|
shadcn-ui
|
typescript
|
fetchProjects
|
async function fetchProjects() {
await new Promise((resolve) => setTimeout(resolve, 3000))
return projects
}
|
// Dummy fetch function
|
https://github.com/shadcn-ui/ui/blob/4810f744e3b5ec23e7fcac14b8377448055e9560/apps/www/registry/new-york/internal/sidebar-rsc.tsx#L51-L54
|
4810f744e3b5ec23e7fcac14b8377448055e9560
|
ui
|
github_2023
|
shadcn-ui
|
typescript
|
visitAndCheck
|
function visitAndCheck(url: string, waitTime = 1000) {
cy.visit(url);
cy.location("pathname").should("contain", url).wait(waitTime);
}
|
// We're waiting a second because of this issue happen randomly
// https://github.com/cypress-io/cypress/issues/7306
// Also added custom types to avoid getting detached
// https://github.com/cypress-io/cypress/issues/7306#issuecomment-1152752612
// ===========================================================
|
https://github.com/shadcn-ui/ui/blob/4810f744e3b5ec23e7fcac14b8377448055e9560/packages/shadcn/test/fixtures/frameworks/remix-indie-stack/cypress/support/commands.ts#L89-L92
|
4810f744e3b5ec23e7fcac14b8377448055e9560
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.