
Security News
vlt Launches "reproduce": A New Tool Challenging the Limits of Package Provenance
vlt's new "reproduce" tool verifies npm packages against their source code, outperforming traditional provenance adoption in the JavaScript ecosystem.
snow-splash
Advanced tools
~1kB inversion of control container for Typescript/Javascrith with a focus on async flow
🚧 library is in alpha dev mode 🚧
~2kB inversion of control container for Typescript/Javascript for constructor injection with a focus on async flow
@decorators
or framework extends
in your application logicreflect-metadata
or decoratorsreflect-metadata
or decorators so there are no need to hack in decorator and "decoratorMetadata"
support into Create React App, node.js, next.js, snowpack, esbuild etc.Snow-Splash is an alternative to InversifyJS and microsoft/tsyringe. It relies on plain JS functions, objects and familiar patterns. There is no need to learn complex API to use it in a full capacity.
npm install -S snow-splash
// Step 1: Your application logic is stays clean
class Oven {}
class Kitchen {
constructor(public oven: Oven) {}
}
// Step 2: Connect your app to container and define tokens
import { RootContainer } from "snow-splash"
const ovenContainer = async () => ({
oven: new Oven(),
})
const kitchenContainer = async ({ oven }) => {
await oven.preheat()
return {
kitchen: new Kitchen(oven),
}
}
const kitchenApp = new RootContainer((ctx) => ({
// you can use tokens (`oven`, `kitchen`) here and later on
oven: async () => ovenContainer(),
kitchen: async () => kitchenContainer(await ctx.oven()),
}))
// Step 3: Use it
// Node.js
const { oven, kitchen } = await kitchenApp.containers
console.log(`In Oven: ${oven.pizzasInOven()}`)
// React
export const PizzaData = () => {
const kitchenSet = useContainerSet(["oven", "kitchen"])
if (!kitchenSet) return <>Kitchen is loading </>
let inOven = kitchenSet.oven.pizzasInOven()
return <>Pizzaz In Oven: {inOven}</>
}
If you don't want to wait for containers in every React component check generateEnsureContainerSet
hook example.
Libraries like InversifyJS or tsyringe rely on decorators and reflect-metadata
.
Firstly, decorators unnecessary couple your application logic with a framework.
Secondly, it is very hard to use with starters like CRA, Next.js etc. To use reflect-metadata
you need to configure your compiler (babel, typescrip, esbuild, swc etc.) configuratoin which is not trivial. So if you can’t use reflect-metadata
you can't use inversify.
import { Oven, Kitchen } from "./kitchen/"
export async function provideKitchenContainer() {
const oven = new Oven()
await oven.preheat()
return {
kitchen: new Kitchen(),
oven: oven,
}
}
import { Oven, Kitchen } from "./kitchen/"
export async function provideKitchenContainer() {
return {
kitchen: () => new Kitchen(),
oven: async () => {
const oven = new Oven()
await oven.preheat()
return oven
},
}
}
export async function provideKitchenContainer() {
const { Kitchen } = await import("./kitchen/kitchen")
return {
kitchen: () => new Kitchen(),
oven: async () => {
const { Oven } = await import("./kitchen/oven")
const oven = new Oven()
await oven.preheat()
return oven
},
}
}
The best way to get started is to check a CRA Pizza example
Initial wiring
import { makeRoot, RootContainer } from "../../library.root-container"
import { provideAContainer } from "./container.a"
import { provideBContainer } from "./container.b"
import { provideCContainer } from "./container.c"
interface Registry {
aCont: () => ReturnType<typeof provideAContainer>
bCont: () => ReturnType<typeof provideBContainer>
cCont: () => ReturnType<typeof provideCContainer>
}
type Lib = (...args: any) => { [K in keyof Registry]: Registry[K] }
export type MockAppContainer = RootContainer<Lib, ReturnType<Lib>>
function getProviders(ctx: Registry, root: MockAppContainer) {
return {
aCont: async () => provideAContainer(),
bCont: async () => provideBContainer(await ctx.aCont()),
cCont: async () =>
provideCContainer(await ctx.aCont(), await ctx.bCont(), root),
}
}
export function getMainMockAppContainer() {
return makeRoot(getProviders)
}
Snow-Splash has a good typescript support
Containers are an important unit. If you replace them, users will be notified. In React it happens automatically
const kitchenApp = new RootContainer((ctx) => ({
// you can use tokens (`oven`, `kitchen`) here and later on
oven: async () => ovenContainer(),
kitchen: async () => kitchenContainer(await ctx.oven()),
}))
kitchenApp.on("containerCreated", (event) => {
console.log(`event: 'containerCreated' ~~> token: '${event.key}'`)
// `event.container` is also avaliable here
})
kitchenApp.on("containerRequested", (event) => {
console.log(`event: 'containerRequested' ~~> token: '${event.key}' `)
})
kitchenApp.on("containerRemoved", (event) => {
console.log(`event: 'containerRemoved' ~~> token: '${event.key}' `)
})
await kitchenApp.containers.kitchen
// event: 'containerRequested' ~~> token: 'kitchen'
// event: 'containerRequested' ~~> token: 'oven'
// event: 'containerCreated' ~~> token: 'oven'
// event: 'containerCreated' ~~> token: 'kitchen'
// Notice how oven was created before kitchen.
// This is because kitcen depends on oven
makeRoot
Setting app rootimport { makeRoot, RootContainer } from "../../library.root-container"
export function getMainMockAppContainer() {
// check get providers above
return makeRoot(getProviders)
}
containers
getterlet appRoot = getMainPizzaAppContainer()
let kitchen = await appRoot.containers.kitchen
kitchen.oven.pizzaCapacity // 4
getContainerSet
getContainerSetNew
replaceContainerInstantly
When containers are updated React is updated too via hooks
getContainerSetHooks
Generates a set of app specific container hooks
// my-app-hooks.ts
import React, { useContext } from "react"
import { getContainerSetHooks } from "snow-splash"
import { getProviders, PizzaAppContainer } from "./_root.store"
export const MyRootCont = React.createContext(<PizzaAppContainer>{})
let mega = getContainerSetHooks(getProviders, MyRootCont)
export const useContainerSet = mega.useContainerSet
export const useContainerSet = mega.useContainerSet
// PizzaData.tsx
import { useContainerSet } from "./my-app-hooks"
export const PizzaData = () => {
const containerSet = useContainerSet((containers) => [containers.kitchen])
console.log(containerSet)
return 123
}
useContainer
export const PizzaData = () => {
const [kitchenContainer, err] = useContainer().kitchen
if (!kitchenContainer || err) {
return <>Kitchen is loading</>
}
return <>{kitchenContainer.oven.pizzasInOven}</>
}
useContainerSet
Get multiple containers and autosubscribes to change.
export const PizzaData = () => {
const containerSet = useContainerSet((containers) => [
containers.kitchen,
containers.auth,
])
if (!containerSet) {
return <>Kitchen is loading</>
}
return <>{containerSet.kitchen.oven.pizzasInOven}</>
}
generateEnsureContainerSet
You can create a simpler API for a portion of your applicatoin to avoid dealing with async in every component. There are some helpfull Context helpers at your service. Also you can use classic props drilling to avoid dealing with async flow in every component
import React, { useContext } from "react"
import { useContainerSet } from "../containers/_container.hooks"
import { generateEnsureContainerSet } from "snow-splash"
const x = generateEnsureContainerSet(() =>
useContainerSet(["kitchen", "pizzaContainer", "auth"]),
)
export const EnsureNewKitchenConainer = x.EnsureWrapper
export const useNewKitchenContext = x.contextHook
export const PizzaApp = () => {
return (
<div>
Pizza App:
<EnsureNewKitchenConainer
fallback={<>Pizza App is still loading please wait</>}
>
<NewPizzaPlaceControls />
</EnsureNewKitchenConainer>
</div>
)
}
export const PizzaData = () => {
const { kitchen, pizzaContainer } = useNewKitchenContext()
return (
<div>
<div>Name: {kitchen.kitchen.kitchenName}</div>
<div>Tables: {pizzaContainer.diningTables.tables}</div>
</div>
)
}
inversifyjs
, tsyringe
and othersInversion of Control (IoC) is a great way to decouple the application and the most popular pattern of IoC is dependency injection (DI) but it is not limited to one.
In JavaScript there is not way to create a dependency injection without mixing application logic with a specific IoC library code or hacking a compiler (reflect-metadata).
inversifyjs
and tsyringe
use decorators and reflect-metada
import { injectable } from "tsyringe"
@injectable()
class Foo {
constructor(private database: Database) {}
}
// some other file
import "reflect-metadata"
import { container } from "tsyringe"
import { Foo } from "./foo"
const instance = container.resolve(Foo)
typed-inject
uses monkey-patching
import { createInjector } from "typed-inject"
function barFactory(foo: number) {
return foo + 1
}
barFactory.inject = ["foo"] as const
class Baz {
constructor(bar: number) {
console.log(`bar is: ${bar}`)
}
static inject = ["bar"] as const
}
With Snow-Splash your application logic is not mixed with the framework code
import type { Ingredients } from "./store.ingrediets"
import type { Oven } from "./store.oven"
export class Kitchen {
constructor(private oven: Oven, private ingredients: Ingredients) {}
}
// provider / factory
import { IngredientsService } from "../services/ingredients-manager"
import { Kitchen } from "../stores/store.kitchen"
import { Oven } from "../stores/store.oven"
export async function provideKitchenContainer() {
let oven = new Oven()
let ingredients = await IngredientsService.buySomeIngredients()
let kitchen = new Kitchen(oven, ingredients)
return {
oven: oven,
ingredients: ingredients,
kitchen: kitchen,
}
}
Notable inspirations:
Can I have multiple application containers?
Yes, no problem at all. If you want, they can even share tokens and hence instances!
FAQs
~1kB inversion of control container for Typescript/Javascrith with a focus on async flow
The npm package snow-splash receives a total of 2 weekly downloads. As such, snow-splash popularity was classified as not popular.
We found that snow-splash demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt's new "reproduce" tool verifies npm packages against their source code, outperforming traditional provenance adoption in the JavaScript ecosystem.
Research
Security News
Socket researchers uncovered a malicious PyPI package exploiting Deezer’s API to enable coordinated music piracy through API abuse and C2 server control.
Research
The Socket Research Team discovered a malicious npm package, '@ton-wallet/create', stealing cryptocurrency wallet keys from developers and users in the TON ecosystem.