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

推荐订阅源

P
Privacy & Cybersecurity Law Blog
Engineering at Meta
Engineering at Meta
Forbes - Security
Forbes - Security
MongoDB | Blog
MongoDB | Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
About on SuperTechFans
量子位
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
雷峰网
雷峰网
腾讯CDC
P
Proofpoint News Feed
S
Schneier on Security
S
Secure Thoughts
V
Visual Studio Blog
Help Net Security
Help Net Security
The Hacker News
The Hacker News
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Privacy International News Feed
SecWiki News
SecWiki News
S
SegmentFault 最新的问题
T
Threatpost
小众软件
小众软件
MyScale Blog
MyScale Blog
F
Fortinet All Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
T
Tailwind CSS Blog
I
Intezer
C
CERT Recently Published Vulnerability Notes
U
Unit 42
V
V2EX
Cyberwarzone
Cyberwarzone
Recorded Future
Recorded Future
O
OpenAI News
Project Zero
Project Zero
有赞技术团队
有赞技术团队
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
Know Your Adversary
Know Your Adversary
C
Cybersecurity and Infrastructure Security Agency CISA
Scott Helme
Scott Helme
V2EX - 技术
V2EX - 技术
博客园 - 叶小钗
S
Securelist
A
Arctic Wolf
The Cloudflare Blog
W
WeLiveSecurity
T
Threat Research - Cisco Blogs
博客园 - Franky

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
Building a Universal Drafts System in a VS Code Extension — Part 1: Types & Storage
freerave · 2026-04-26 · via DEV Community

How I designed the Draft type, DraftsService, and the save/upsert flow that powers DotShare v3.2.5 — with full TypeScript code and the decisions behind every choice.

Before v3.2.5, DotShare had zero persistence. Write a 2,000-word Dev.to article in the WebView, switch tabs to check something, come back — gone. Reset. Empty form.

So I built a drafts system. This is Part 1: how I modeled the data and built the storage layer.

Part 2 covers the Two-Way Markdown Sync, Remote Dev.to Drafts, the WebView UI, and the Split-Editor workflow.


The Problem with WebViews

VS Code WebViews are iframes. They get suspended when not visible and fully reset on restart. For a tweet that's annoying. For a structured blog article with frontmatter, tags, cover image, and thousands of words — it's a real productivity loss.

Split screen showing a full 2000-word article draft on the right, and a completely empty reset form on the left after switching tabs

The naive fix is "just auto-save to a file." But that creates new questions: which file? What about social posts that have no file? What if the user has multiple articles open? What about platform-specific metadata like Dev.to series or Medium publish status?

The solution needed to be universal — one system for social posts and blog articles, all 9 platforms, zero config for the user.


Designing the Draft Type

The first thing I did was sit down and define exactly what a "draft" means across all use cases.

A LinkedIn post draft needs: text content, platform, timestamp.
A Dev.to article draft needs: title, tags, description, cover image, canonical URL, series, body markdown, publish status, platform.

One interface had to cover both:

// src/types.ts

export type DraftType = 'social' | 'article';

export interface Draft {
    id: string;
    type: DraftType;
    timestamp: string;
    platforms: SocialPlatform[];
    data: PostData | BlogPost;
    title?: string;      // Human-readable label in the UI
    isRemote?: boolean;  // true = fetched from Dev.to API, not local
    remoteId?: string;   // Dev.to article ID for remote drafts
}

Enter fullscreen mode Exit fullscreen mode

The data field is a union. PostData for social:

export interface PostData {
    text: string;
    media?: string[];  // local file paths
}

Enter fullscreen mode Exit fullscreen mode

BlogPost for long-form articles:

export interface BlogPost {
    id?: string;
    title: string;
    bodyMarkdown: string;
    tags: string[];
    canonicalUrl?: string;
    description?: string;
    coverImage?: string;
    series?: string;
    status: 'draft' | 'published' | 'unlisted';
    platformId: 'devto' | 'medium';
    publishedAt?: string;
    url?: string;
}

Enter fullscreen mode Exit fullscreen mode

Data model diagram showing the Draft Interface parent node branching into two child types: PostData for social posts and BlogPost for articles

This union lets a single draftsLoaded WebView message carry both types. The WebView switches behavior on draft.type — no separate message commands, no separate storage keys per platform.

The isRemote flag is critical: it marks drafts fetched from the Dev.to API. Remote drafts look identical to local ones in the UI but have different save semantics — you update them via API, not globalState.


Choosing the Storage Backend

I evaluated three options:

Option A — Write to a file in the workspace. Simple, but creates git noise, doesn't work if there's no workspace open, and fails for social post drafts that have no natural file home.

Option B — SQLite via a native module. Powerful, but native modules in VS Code extensions are a packaging nightmare. Cross-platform builds, .vsix size, and esbuild bundling issues ruled this out fast.

Option C — VS Code globalState. This is a key-value store backed by VS Code's own storage layer. It survives restarts, is encrypted at rest on macOS (Keychain), works even without a workspace, requires zero config, and the API is synchronous to read and async to write.

globalState was the obvious choice. The only real limitation is that it's not designed for large datasets — but a list of drafts with text content will comfortably stay under the internal limits for years.


The DraftsService

DraftsService wraps globalState with a clean CRUD interface. The full implementation:

// src/services/DraftsService.ts
import * as vscode from 'vscode';
import { Draft } from '../types';

const DRAFTS_KEY = 'dotshare_drafts_v1';

export class DraftsService {
    constructor(private globalState: vscode.Memento) {}

    getDrafts(): Draft[] {
        return this.globalState.get<Draft[]>(DRAFTS_KEY, []);
    }

    getDraft(id: string): Draft | undefined {
        return this.getDrafts().find(d => d.id === id);
    }

    saveDraft(data: Omit<Draft, 'id' | 'timestamp'>): Draft {
        const drafts = this.getDrafts();
        const draft: Draft = {
            ...data,
            id: `draft_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,
            timestamp: new Date().toISOString(),
        };
        this.globalState.update(DRAFTS_KEY, [draft, ...drafts]);
        return draft;
    }

    updateDraft(id: string, updates: Partial<Draft>): Draft | undefined {
        const drafts = this.getDrafts();
        const idx = drafts.findIndex(d => d.id === id);
        if (idx === -1) return undefined;
        drafts[idx] = {
            ...drafts[idx],
            ...updates,
            timestamp: new Date().toISOString(),
        };
        this.globalState.update(DRAFTS_KEY, drafts);
        return drafts[idx];
    }

    deleteDraft(id: string): void {
        this.globalState.update(
            DRAFTS_KEY,
            this.getDrafts().filter(d => d.id !== id)
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

Three decisions worth explaining:

_v1 on the key. If I ever change the schema, I read dotshare_drafts_v1, transform the data, write to dotshare_drafts_v2, then delete the old key. No migration scripts, no breaking changes for existing users.

Omit<Draft, 'id' | 'timestamp'> at save. This forces the compiler to prevent callers from passing a stale ID or a hand-crafted timestamp. IDs and timestamps are always generated internally, guaranteed fresh.

Newest first. [draft, ...drafts] prepends instead of appending. The WebView grid always shows the most recent work at the top without any sort step.


Wiring It Into the Handler Chain

DraftsService is instantiated once in MessageHandler and injected down into PostHandler. This keeps a single instance — one source of truth — across the extension's lifetime:

// src/handlers/MessageHandler.ts

export class MessageHandler {
    private draftsService: DraftsService;
    private postHandler: PostHandler;

    constructor(
        private view: vscode.WebviewView,
        private context: vscode.ExtensionContext,
        private historyService: HistoryService,
        private analyticsService: AnalyticsService,
        private mediaService: MediaService
    ) {
        this.draftsService = new DraftsService(context.globalState);

        this.postHandler = new PostHandler(
            view,
            context,
            historyService,
            analyticsService,
            mediaService,
            this.draftsService  // ← injected
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

Routing is handled by a string check — any command that includes the word Draft goes to PostHandler:

if (
    cmd.startsWith('share') ||
    cmd === 'generatePost'  ||
    cmd === 'readMarkdownFile' ||
    cmd.includes('Draft')      // ← catches all 7 draft commands
) {
    await this.postHandler.handleMessage(message);
}

Enter fullscreen mode Exit fullscreen mode

This keeps the routing table flat and readable. Adding a new draft command in the future requires zero changes to MessageHandler.


The Save/Upsert Pattern

The saveLocalDraft handler is the most-called draft command. It does an upsert — not a blind insert:

Logic flowchart illustrating the save process: checking if an ID exists, then either updating the existing draft or creating a new one in the global state

private async handleSaveLocalDraft(message: Message): Promise<void> {
    const draft = message.draft as Omit<Draft, 'id' | 'timestamp'>;

    if (!draft) {
        this.sendError('Draft data is required.');
        return;
    }

    // Guard: remote drafts cannot be cloned locally
    if ((draft as Draft).isRemote) {
        this.sendError('Cannot save a remote draft locally. Use "Update" instead.');
        return;
    }

    const existingId = message.draftId as string | undefined;

    if (existingId) {
        // Update existing draft in place
        const updated = this.draftsService.updateDraft(existingId, draft);
        if (updated) {
            this.sendInfo('Draft updated!');
            this.view.webview.postMessage({ command: 'draftLoaded', draft: updated });
        } else {
            this.sendError('Draft not found for update.');
        }
    } else {
        // Create new draft
        const saved = this.draftsService.saveDraft(draft);
        this.sendInfo('Draft saved locally!');
        this.view.webview.postMessage({ command: 'draftLoaded', draft: saved });
    }

    // Always refresh the list
    await this.handleListLocalDrafts();
}

Enter fullscreen mode Exit fullscreen mode

The upsert is essential. The first save creates a new draft and the WebView receives its ID via draftLoaded. Every subsequent save passes that ID back in message.draftId. Without this, every Ctrl+S would create a duplicate entry.

The remote guard is equally important. If someone somehow triggers a save on a remote draft, the handler rejects it with a clear error rather than silently creating a stale local copy that would immediately diverge from the Dev.to version.

After every save or update, handleListLocalDrafts runs and pushes the full refreshed list to the WebView — so the draft grid always reflects the current state without a manual refresh.


What's in Part 2

The storage layer is done. In Part 2, we cover:

  • loadLocalDraft — the Two-Way Markdown Sync that rewrites the active .md editor file when you load a draft
  • fetchDevToDrafts — fetching remote Dev.to articles and mapping them to the Draft interface
  • resetBlogMarkdown — the Reset Boilerplate button
  • The WebView UI — the HTML, draft card CSS, and how {{PLATFORM_NAME}} tokens get injected
  • Split-Editor workflow — how opening Dev.to or Medium auto-creates a named .md file beside the WebView panel

Try It

DotShare is free and open source under Apache 2.0:

If this saved you time, a ⭐ on the repo means a lot!


Built by @FreeRave