惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Forbes - Security
Forbes - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Fortinet All Blogs
B
Blog
T
The Blog of Author Tim Ferriss
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
Y
Y Combinator Blog
Microsoft Azure Blog
Microsoft Azure Blog
L
LangChain Blog
Recent Announcements
Recent Announcements
U
Unit 42
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Register - Security
The Register - Security
Recorded Future
Recorded Future
C
Check Point Blog
V
V2EX
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
F
Full Disclosure
小众软件
小众软件
A
About on SuperTechFans
云风的 BLOG
云风的 BLOG
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
爱范儿
爱范儿
P
Proofpoint News Feed
罗磊的独立博客
量子位
D
Docker
博客园_首页
D
DataBreaches.Net
Project Zero
Project Zero
博客园 - 司徒正美
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - Franky
Security Latest
Security Latest
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
Netflix TechBlog - Medium
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 三生石上(FineUI控件)
H
Hackread – Cybersecurity News, Data Breaches, AI and More
大猫的无限游戏
大猫的无限游戏

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
KickJS Asset Manager — Type-Safe File Resolution from Dev to Dist
Orinda Felix · 2026-04-25 · via DEV Community

There is a familiar little discomfort that shows up the first time a Node.js service needs to read something off disk that is not source code. An email template. A JSON schema. A seed fixture. A vendored PDF. The first version is always a one-liner: fs.readFile(path.join(__dirname, '../templates/welcome.ejs')). That works on your laptop. It also works in CI. And then you ship to production, your bundler flattens the output, __dirname points at dist/handlers/ instead of src/handlers/, the relative climb misses the templates directory, and the first user who triggers a password reset gets a 500.

The pragmatic fix is to scatter process.env.NODE_ENV === 'production' ? '../../dist/templates' : '../templates' across the codebase. The principled fix is to admit that on-disk assets are a build-time concern that deserves its own little type system. That is what the KickJS Asset Manager is.

The shape of the problem

Server-side asset resolution has three properties that conspire against you.

First, the path differs between dev and dist. Dev runs against src/, dist runs against a built output that may have a different layout, possibly minified, possibly bundled, possibly emitted by a different tool than the one that compiled your handlers.

Second, the keys are stringly-typed. readFile('templates/welcome.ejs') is just a string. Rename the file, forget to update the call site, and TypeScript gives you nothing — you find out at runtime, usually from a Sentry alert, usually from an end user.

Third, the cleanup story is bad. NODE_ENV checks, try/catch fallbacks, conditional __dirname math, helper functions that paper over the asymmetry — every codebase with on-disk assets accretes a small graveyard of these. They are correct individually and incoherent collectively.

The Asset Manager replaces all three problems with a single mental model: at build time, every asset you care about is copied into a known location and recorded in a manifest. At runtime, you address those assets through a typed proxy whose shape is generated from the manifest. There is no NODE_ENV, no __dirname arithmetic, and no string keys that the compiler cannot check.

The mental model: a manifest plus a typed proxy

Two artifacts do the heavy lifting.

The first is .kickjs-assets.json, a manifest emitted into dist/ during build. It is the canonical answer to "where, on this filesystem, is the asset named mails.welcome?". It is a flat JSON object — categories at the top level, slugs underneath, absolute or dist-relative paths as values.

The second is .kickjs/types/assets.d.ts, a generated declaration file that augments the framework-supplied KickAssets interface. The interface mirrors the manifest's shape exactly: KickAssets['mails']['welcome'] exists if and only if the manifest has an entry for mails.welcome. That augmentation is what gives the proxy its types.

The runtime side is a Proxy (or several flavours of one — see below). When you write assets.mails.welcome(), the proxy walks the path ['mails', 'welcome'], looks the slug up in the manifest, and returns the resolved file path. No filesystem reads, no environment checks, no path.join math in your handlers.

The result is that asset resolution becomes a pure function from a typed key to a string path, and every typo is a compile error.

The four ways to consume an asset

KickJS gives you four consumption patterns. They all resolve through the same manifest — the difference is purely ergonomic.

1. The ambient nested proxy

The default and most common pattern. Import once, address anywhere.

import { assets } from '@forinda/kickjs';

const path = assets.mails.welcome();
const html = await renderEjs(await readFile(path, 'utf8'), { user });

Enter fullscreen mode Exit fullscreen mode

assets is a deeply-nested proxy whose shape comes from the augmented KickAssets interface. IDE autocomplete works at every level: assets. shows categories, assets.mails. shows slugs.

2. useAssets() — the hook factory

Sometimes you want the resolver as a value, not a singleton. useAssets() returns the same proxy but as a factory call, which is convenient when you want to swap implementations in tests or pass the resolver through a DI container.

import { useAssets } from '@forinda/kickjs';

class MailService {
  constructor(private readonly assets = useAssets()) {}
  welcome() { return this.assets.mails.welcome(); }
}

Enter fullscreen mode Exit fullscreen mode

This is the form to reach for when you would otherwise be tempted to mock the import.

3. @Asset() — the class field decorator

For class-based services where you want the resolution to be lazy and declarative.

import { Asset } from '@forinda/kickjs';

class MailService {
  @Asset('mails/welcome') private welcomeTpl!: string;

  async send(user: User) {
    const html = await renderEjs(await readFile(this.welcomeTpl, 'utf8'), { user });
  }
}

Enter fullscreen mode Exit fullscreen mode

The decorator installs a getter that resolves on first access. The string argument is type-checked against the manifest, so @Asset('mails/does-not-exist') is a compile error.

4. resolveAsset() — the dynamic escape hatch

When the key really is dynamic — an admin choosing a template at runtime, a feature-flagged variant — fall back to the function form.

import { resolveAsset } from '@forinda/kickjs';

const path = resolveAsset('mails', slug); // slug: string

Enter fullscreen mode Exit fullscreen mode

You lose the per-key compile-time check, but the category is still typed and a missing slug throws a meaningful runtime error rather than returning a bogus path.

Build → manifest → runtime

The split between build and runtime is what makes the whole thing tractable.

kick build (or the focused kick build:assets) reads assetMap from kick.config.ts. Each entry has a src path (required), an optional dest (defaults to the entry's name), and an optional glob (defaults to **/*). For every entry, the builder walks the glob, copies matching files to dist/<dest>/, and records each one in .kickjs-assets.json. After the copy, kick typegen regenerates .kickjs/types/assets.d.ts so the type system reflects what was actually emitted.

// kick.config.ts
export default defineConfig({
  assetMap: {
    mails:   { src: 'src/templates/mails',   glob: '**/*.ejs' },
    schemas: { src: 'src/schemas',           glob: '**/*.json' },
    fixtures:{ src: 'src/fixtures',          dest: 'fixtures' }
  }
});

Enter fullscreen mode Exit fullscreen mode

At runtime, resolution follows a strict order. First, the manager checks KICK_ASSETS_ROOT — if set, that directory is treated as the asset root and every lookup is rooted there. Second, it tries to load .kickjs-assets.json from dist/ (or wherever the manager was initialized). Third — and only when running from source with no manifest present — it synthesizes a manifest by walking src/ according to assetMap, so that pnpm dev works without a build step.

The contract is straightforward: in production you have a manifest and the proxy is essentially a hash lookup; in dev you have a synthesized one and the proxy is essentially a filesystem walk plus a cache. Same API, same types, different machinery.

Type safety via typegen

kick typegen is the piece that closes the loop. It reads the manifest and writes a single .d.ts that augments the KickAssets interface declared by @forinda/kickjs:

declare module '@forinda/kickjs' {
  interface KickAssets {
    mails: { welcome: AssetRef; 'password-reset': AssetRef };
    schemas: { user: AssetRef };
  }
}

Enter fullscreen mode Exit fullscreen mode

Once that file is on disk, assets.mails.does_not_exist() is a compile error, not a runtime exception. Filenames that are not valid identifiers — anything with a hyphen, a leading digit, a dot — are still safely addressable through bracket notation: assets.mails['password-reset'](). The generated interface uses string-literal keys for everything, so the bracket form keeps full autocomplete.

Run kick typegen (or let kick build do it for you) after any change to assetMap or to the files those entries point at. CI should treat a stale .kickjs/types/assets.d.ts as a failure.

Testing — fixture swapping

Because every lookup goes through the manifest, you can override the entire asset root at the process level by setting KICK_ASSETS_ROOT before the manager is first touched. Combined with clearAssetCache() to reset the manager between tests, this gives you a clean way to swap in fixtures without mocking.

beforeEach(() => {
  process.env.KICK_ASSETS_ROOT = path.join(__dirname, 'fixtures');
  clearAssetCache();
});

Enter fullscreen mode Exit fullscreen mode

In a unit test for MailService, you can point at a fixtures/mails/welcome.ejs containing <h1>Hello {{name}}</h1> and assert on the rendered output without touching the real templates. The same trick works for snapshot fixtures, JSON-schema variants, anything where you want a known-good input.

When to reach for it

The Asset Manager is the right tool whenever the runtime answer is fs.readFile. Email templates rendered with EJS, Handlebars, or MJML. JSON schemas loaded by Ajv. Seed fixtures. PDFs and CSVs that ship with the app. Anything that lives on disk in dev, needs to live on disk in dist, and is consumed by your own server-side code.

It is not the right tool for HTTP-served static assets. Public images, downloadable user-facing files, anything a browser fetches — those want a static-file adapter or a CDN, not the Asset Manager. The line is "who reads this file?". If the answer is your handlers, use the manager. If the answer is a browser, use a serving layer.

The payoff for the in-scope cases is that you stop writing path math, you stop scattering environment checks, and you find typos at compile time instead of at 2 a.m. Once the manifest exists, the type system does the rest.

References