@effected/templates

中文文档
0.20.0发布于 2026/11/10MITTypeScriptES Module构建来源已验证近 30 天下载 5691

Managed-section blocks in user-editable files: parse, reconcile, sync and check delimited regions.

原始使用文档
文档目录6 节
  1. Why @effected/templates
  2. Install
  3. Quick start
  4. Marker attributes
  5. Features
  6. License

@effected/templates

npm License: MIT Node.js %3E%3D24.11.0 TypeScript 7.0

Managed sections: delimited BEGIN/END blocks inside files whose surrounding content belongs to the user. A tool owns the block, the user owns everything else, and neither destroys the other — the mechanism behind a generated hook, a managed config fragment, or any file your tool and your user both need to edit.

Pre-1.0.0. This package is part of the @effected/* kit, built on stable Effect v4 (effect ~4.1.0) and still in 0.x development. Stable Effect makes a kit 1.0.0 possible, not automatic. To keep your effect and @effect/* versions on the line the kit is built and tested against, install @effected/pnpm-plugin-effected.

Stability: unstable. This package's API surface is not yet considered complete and may change across 0.x releases. Pin an exact version — even a package marked stable before 1.0.0 can introduce a breaking change by accident, and an exact pin turns that into a type-check error rather than a runtime surprise. Full policy: release strategy.

Why @effected/templates

Most "managed section" implementations put the whole algorithm inside a service that also does file IO, so the hardest logic — deciding what changed, and where a new block belongs — can only be tested by writing files to disk. This package splits the two apart. SectionDocument is a pure string-to-string core with no Effect, no IO and no runtime: parse a document, compare a declared section against what is already there, reconcile a whole set of them, render the result. ManagedSection is a thin service that reads a file, calls the pure core, and writes back only when the text actually changed.

Ambiguity fails typed rather than being resolved by guessing: an unterminated marker, an orphaned END, two overlapping sections, or the same identity declared twice are all a typed SectionParseError naming the line, never a silent skip that leaves a duplicate block on the next run. Line endings are a first-class invariant too — the document's dominant EOL is detected at parse and every comparison is EOL-normalized, so a CRLF file does not report drift forever.

Install

npm install @effected/templates effect
pnpm add @effected/templates effect

Requires Node.js >=24.11.0. effect v4 is the only peer dependency. @effected/files comes along as an ordinary dependency, and it backs the atomic write.

All @effected/* packages are ESM-only: the exports maps publish only import conditions, so require() — including tools that resolve in CJS mode — fails with Node's ERR_PACKAGE_PATH_NOT_EXPORTED rather than loading a CJS build that does not exist. Import from an ES module.

FileSystem comes from effect core, not from a platform package, so a consumer provides it once at the edge (NodeFileSystem.layer from @effect/platform-node on Node). Path is required as well (NodePath.layer on Node): a sync replaces the file through a temp file beside it and a rename, so a crash cannot leave a truncated file.

Quick start

Declare two sections and sync them into a file in one call. Declared order becomes file order, so base always precedes tool, however a user may have reordered the file by hand:

import { CommentStyle, ManagedSection, SectionId } from "@effected/templates";
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
import * as NodePath from "@effect/platform-node/NodePath";
import { Effect, Layer } from "effect";

const Base = SectionId.make({ key: "base", commentStyle: CommentStyle.hash });
const Tool = SectionId.make({ key: "tool", commentStyle: CommentStyle.hash });

const program = Effect.gen(function* () {
  const sections = yield* ManagedSection;
  return yield* sections.syncAll(".husky/pre-commit", [Base.section("#!/usr/bin/env sh"), Tool.section("npx tool run")]);
});

Effect.runPromise(program.pipe(Effect.provide(ManagedSection.layer), Effect.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer)))).then((outcomes) =>
  console.log(outcomes.map((o) => o._tag)),
);
// example output on a fresh file: [ "Created", "Created" ]
// example output on a second, identical run: [ "Unchanged", "Unchanged" ]

Marker attributes

A BEGIN marker can carry name="value" pairs, so a tool reads a block's provenance — which run wrote it, and when — off the marker line without opening the block:

import { CommentStyle, SectionDocument, SectionId } from "@effected/templates";
import { Result } from "effect";

const Tool = SectionId.make({ key: "tool", commentStyle: CommentStyle.hash });
const doc = SectionDocument.parseResult("#!/usr/bin/env sh\n");

if (Result.isSuccess(doc)) {
  const next = doc.success.reconcile([Tool.section("npx tool run", { origin: "ci", runId: "1873" })]);
  console.log(Result.isSuccess(next) ? next.success.text : next.failure.message);
  // #!/usr/bin/env sh
  //
  // # --- BEGIN tool MANAGED SECTION origin="ci" runId="1873" ---
  // npx tool run
  // # --- END tool MANAGED SECTION ---
}

Attributes are metadata, never identity: a section is found by key and comment style alone, so bumping runId updates that block in place instead of orphaning it and appending a second one. They do count as difference — check answers Drifted when a declared attribute disagrees with the marker on disk, which is what lets a tool rewrite a block whose only change is its metadata. Omitting the argument and passing {} are the same section, so a caller that never uses attributes sees no drift against a bare marker.

The grammar has no escaping, deliberately: names match [A-Za-z][A-Za-z0-9_-]*, values are double-quoted and carry neither " nor a line break, and anything outside that fails typed as a SectionRenderError with reason: "invalidAttribute" naming the attribute — before a byte is written. An END marker never carries attributes, and an attribute run that does not parse cleanly (a mangled pair, one name declared twice) makes the whole line ordinary content rather than a marker.

Attributed markers are a one-way compatibility break: a scanner predating this feature does not recognize one at all, so the block it opens stops being a managed section for that tool. Writing attributes into a file another tool also manages is a decision, not a detail.

Features

  • SectionDocument — the pure core: parse / read / has / check / reconcile / remove over a plain string, with no Effect, no IO and no runtime needed to test it.
  • ManagedSection — the service: read, readAll, isManaged, sync, syncAll, check, checkAll and remove, each writing back only when the text changed.
  • CommentStyle — an open set of {prefix, suffix?} presets (hash, slash, semicolon, dash, html, block) covering both line comments and wrapped ones like <!-- … -->, so a managed section can live in Markdown or HTML, not just source files.
  • Marker attributes — name="value" pairs on a BEGIN marker, via SectionId.section(content, attributes) and Section.attributes: metadata for the tool, never part of a section's identity.
  • SyncOutcome / CheckOutcome — tagged results (Created / Updated / Unchanged, Absent / UpToDate / Drifted) that carry the sections involved rather than a diff, so a caller renders exactly the comparison it needs.
  • Byte-preserving outside managed blocks: every character outside a declared section's span survives a sync, in order, including a leading BOM.
  • Idempotent by construction: syncing an already-up-to-date document writes nothing and touches no mtime.

License

MIT

版本与发布记录

@effected/templates 共发布 26 个版本,首次发布于 2026/07/26;过去 12 个月发布了 26 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.20.0latest2026/11/103 天前
0.19.12026/11/103 天前
0.19.02026/11/094 天前
0.18.02026/11/067 天前
0.17.02026/11/0310 天前
0.16.02026/11/0112 天前

关于 @effected/templates 的常见问题

@effected/templates 是什么?

Managed-section blocks in user-editable files: parse, reconcile, sync and check delimited regions.

如何安装 @effected/templates?

在项目目录运行 npm install @effected/templates,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:effect(~4.1.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@effected/templates 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@effected/templates 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@effected/templates 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.11.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@effected/templates 可以商用吗?

@effected/templates 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@effected/templates 的下载量有多少?

根据 npm 官方下载统计,@effected/templates 在 2026/10/13 – 2026/11/11 这 30 天内被下载 5,691 次,日均约 190 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@effected/templates 还在维护吗?

最新版本 0.20.0 发布于 2026/11/10(3 天前);至今共发布 26 个版本,其中过去 12 个月发布了 26 个;首次发布于 2026/07/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。