Skip to content

Instantly share code, notes, and snippets.

@igrek8
igrek8 / pack.ts
Created June 29, 2023 10:13
Pack and unpack JSON value
export function packJSON(object: unknown) {
const fragments: object[] = [];
const indices = new Map<string, number>();
function next(node: unknown): unknown {
if (node && typeof node === "object") {
let fragment: object;
if (Array.isArray(node)) {
fragment = node.map((el) => next(el));
} else {
fragment = Object.entries(node).reduce<Record<string, unknown>>((obj, [key, value]) => {
@igrek8
igrek8 / create-type-node-from-string.ts
Created June 26, 2023 07:21
TypeScript Compiler API: create a type node from a string
import assert from "assert";
import ts, { isTypeAliasDeclaration } from "typescript";
function createTypeNodeFromString(type: string): ts.TypeNode {
const sourceFile = ts.createSourceFile("source.ts", `type A = ${type};`, ts.ScriptTarget.Latest);
const statement = sourceFile.statements[0];
assert(isTypeAliasDeclaration(statement));
return statement.type;
}
@igrek8
igrek8 / check-syntax.ts
Created June 26, 2023 07:19
TypeScript Compiler API: Check language syntax using string content
import ts from "typescript";
const code = `type A = string;`;
const sourceFile = ts.createSourceFile("source.ts", code, ts.ScriptTarget.Latest);
const host = ts.createCompilerHost({});
const getSourceFile = host.getSourceFile;
host.getSourceFile = function (name, languageVersion) {
return name === sourceFile.fileName ? sourceFile : getSourceFile.call(host, name, languageVersion);
};
const program = ts.createProgram([sourceFile.fileName], { noEmit: true }, host);
@igrek8
igrek8 / flatten.js
Last active November 11, 2022 11:45
flatten / unflatten structures
var flatten;(()=>{var r={666:r=>{function e(r,t,n){return Array.isArray(t)?t.reduce(((t,o,c)=>({...t,...e(r?`${r}[${c}]`:`[${c}]`,o,n)})),{}):t&&"object"==typeof t?Object.entries(t).reduce(((t,[o,c])=>{const u=r?`${r}.${o}`:`${o}`,s=n.ignore?.includes(u);return{...t,...s?{[u]:c}:e(u,c,n)}}),{}):{[r]:t}}r.exports=function(r,t={}){return e(void 0,r,t)}},138:(r,e,t)=>{const n=t(666),o=t(961);r.exports={flatten:n,unflatten:o}},961:r=>{function e(...r){return r.reduce(((r,t)=>(Object.keys(t).forEach((n=>{const o=r[n],c=t[n];Array.isArray(o)&&Array.isArray(c)?r[n]=o.concat(...c):r[n]=o&&"object"==typeof o&&c&&"object"==typeof c?e(o,c):c})),r)),{})}r.exports=function(r){return Object.entries(r).reduce(((r,[t,n])=>e(r,function(r,e){return(t=r,t.match(/(\[\d+\])|([^\.\[]+)/gi)).reverse().reduce(((r,e)=>function(r){return/^\[\d+\]$/.test(r)}(e)?[r]:{[e]:r}),e);var t}(t,n))),{})}}},e={},t=function t(n){var o=e[n];if(void 0!==o)return o.exports;var c=e[n]={exports:{}};return r[n](c,c.exports,t),c.exports}(138);flatten=t}
@igrek8
igrek8 / collect-express-response.ts
Created September 12, 2022 09:19
Reads express.js response
import { Response } from "express";
type WriteCallback = (error: Error | null | undefined) => void;
type WriteArguments1 = [chunk: any, callback?: WriteCallback];
type WriteArguments2 = [chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void];
type EndCallback = () => void;
@igrek8
igrek8 / log-locator.js
Last active August 18, 2022 19:58
nodejs log locator
const regex = /([^ ]+) [^(]*\(([^:]+):(\d+)/;
function getLocator() {
// stack 3
const { stack } = new Error();
if (!stack) {
return null;
}
// how far is your stdout? std write is 2 steps away
const match = stack.split(" at ")?.[3].match(regex);
@igrek8
igrek8 / gen-token.js
Last active August 17, 2022 12:52
generate shopify multipass token
const crypto = require("crypto");
class Multipass {
constructor(multipass_secret) {
const key_material = crypto.createHash("sha256").update(multipass_secret).digest();
this.encryption_key = key_material.subarray(0, 16);
this.signature_key = key_material.subarray(16);
}
generate_token(customer_data_hash) {
@igrek8
igrek8 / bundle.sh
Created July 6, 2022 08:49
copy production node_modules
set -eo pipefail
node_modules=$(pwd)/node_modules
output="$1/nodejs/node_modules"
list=($(npm list --production --all --parseable))
mkdir -p $output
for item in "${list[@]}"; do
path=$(realpath --relative-to="$node_modules" "$item")
@igrek8
igrek8 / getUploadParts.ts
Created March 20, 2022 10:13
aws s3 calculate upload parts for multipart
const MIN_CHUNK_SIZE = 5242880; // 5MB in bytes
const DEFAULT_CHUNK_SIZE = 26214400; // 25MB in bytes
export function getUploadParts(contentLength: number, chunkSize: number = DEFAULT_CHUNK_SIZE): string[] {
if (contentLength <= 0) {
throw new Error('ContentLength should be greater than 0 bytes');
}
if (chunkSize < MIN_CHUNK_SIZE) {
throw new Error('ChunkSize should be greater or equal to 5 mb');
@igrek8
igrek8 / pack.sh
Last active March 5, 2022 20:49
Bundle a package and dependencies in a monorepo (bundle is controlled by "files" and "npm pack")
#!/usr/bin/env bash
set -e
while (( $# > 0 )); do
case "${1}" in
-w | --workspace)
workspace="${2}"
shift 2
;;