create-cellsweb-rpc-api 1.0.31 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,6 +4,8 @@
4
4
  </a>
5
5
  </p>
6
6
 
7
+ > **Version 2.0.1 safety:** the installation commands below require 2.0.1 to be available in the registry. During candidate review, use approved private artifacts; do not substitute published 2.0.0 when validating target-refusal safeguards.
8
+
7
9
  # create-cellsweb-rpc-api
8
10
 
9
11
  [![npm version](https://img.shields.io/npm/v/create-cellsweb-rpc-api.svg)](https://www.npmjs.com/package/create-cellsweb-rpc-api)
@@ -15,8 +17,7 @@ JSON/multipart handling, environment configuration and a project-local CLI.
15
17
  Choose native Node, Bun, Express, Fastify, Hono, Elysia or Ultimate Express while
16
18
  keeping function and middleware modules independent of the HTTP adapter.
17
19
 
18
- This **1.0.31 documentation patch** preserves the generator/template runtime from
19
- 1.0.30. Requires **Node>=24.0.0**, with Node 24 LTS the primary toolchain; Bun 1.3.11
20
+ Version **2.0.1** generates applications requiring `@cellsweb/rpc-core:^2.0.1`. Requires **Node>=24.0.0**, with Node 24 LTS the primary toolchain; Bun 1.3.11
20
21
  is tested separately. This package generates the project. The installed
21
22
  `@cellsweb/rpc-core` supplies the project's runtime and `crpc` executable.
22
23
 
@@ -52,10 +53,10 @@ npm run dev
52
53
  ```
53
54
 
54
55
  The correct npm initializer name is **cellsweb-rpc-api**, not
55
- create-create-cellsweb-rpc-api. For an exact generator version:
56
+ create-create-cellsweb-rpc-api. To pin the fixed generator once it is available:
56
57
 
57
58
  ```sh
58
- npx create-cellsweb-rpc-api@1.0.31 my-api --framework=node --yes --pm=npm
59
+ npx create-cellsweb-rpc-api@2.0.1 my-api --framework=node --yes --pm=npm
59
60
  ```
60
61
 
61
62
  Once running (port4000 by default), invoke the generated hello function:
@@ -73,7 +74,7 @@ Frontend applications install `@cellsweb/rpc-client` independently.
73
74
  ## Interactive and automated setup
74
75
 
75
76
  With an interactive terminal, the CLI asks for target directory (if omitted),
76
- package name, package manager and framework. Choose a fresh empty directory;
77
+ package name, package manager and framework. Choose a new destination path that does not exist;
77
78
  this is not an in-place migration tool for existing applications.
78
79
 
79
80
  ```sh
@@ -87,7 +88,7 @@ pnpm create cellsweb-rpc-api@latest my-api
87
88
  For automation, provide the target directory first and explicit flags:
88
89
 
89
90
  ```sh
90
- npx create-cellsweb-rpc-api@1.0.31 generated-api \
91
+ npx create-cellsweb-rpc-api@latest generated-api \
91
92
  --framework=fastify --name=example-api --pm=npm --yes --skip-install
92
93
  cd generated-api
93
94
  npm install
@@ -121,13 +122,13 @@ The CLI's framework aliases are conveniences; prefer the canonical names below.
121
122
  | `bun` | Native Bun.serve | Bun |
122
123
 
123
124
  ```sh
124
- npx create-cellsweb-rpc-api@1.0.31 node-api --framework=node --yes --skip-install
125
- npx create-cellsweb-rpc-api@1.0.31 express-api --framework=express --yes --skip-install
126
- npx create-cellsweb-rpc-api@1.0.31 fastify-api --framework=fastify --yes --skip-install
127
- npx create-cellsweb-rpc-api@1.0.31 ultimate-api --framework=ultimate-express --yes --skip-install
128
- npx create-cellsweb-rpc-api@1.0.31 hono-api --framework=hono --yes --skip-install
129
- npx create-cellsweb-rpc-api@1.0.31 elysia-api --framework=elysia --yes --skip-install
130
- npx create-cellsweb-rpc-api@1.0.31 bun-api --framework=bun --yes --skip-install
125
+ npx create-cellsweb-rpc-api@latest node-api --framework=node --yes --skip-install
126
+ npx create-cellsweb-rpc-api@latest express-api --framework=express --yes --skip-install
127
+ npx create-cellsweb-rpc-api@latest fastify-api --framework=fastify --yes --skip-install
128
+ npx create-cellsweb-rpc-api@latest ultimate-api --framework=ultimate-express --yes --skip-install
129
+ npx create-cellsweb-rpc-api@latest hono-api --framework=hono --yes --skip-install
130
+ npx create-cellsweb-rpc-api@latest elysia-api --framework=elysia --yes --skip-install
131
+ npx create-cellsweb-rpc-api@latest bun-api --framework=bun --yes --skip-install
131
132
  ```
132
133
 
133
134
  For a Bun application, install/run using Bun after generation:
@@ -164,10 +165,11 @@ my-api/
164
165
  test/ # test context and lifecycle helpers
165
166
  ```
166
167
 
167
- Inspect generated files as application-owned code. The initializer currently
168
- requests **core^1.0.34**; this compatible range includes the documentation-only
169
- 1.0.35 patch. It is intentionally unchanged because no new runtime dependency is
170
- required. Generated servers do not depend on rpc-client; your frontend does.
168
+ Inspect generated files as application-owned code. This v2 initializer requests
169
+ **@cellsweb/rpc-core ^2.0.1**. This minimum excludes unsafe2.0.0 scaffolders.
170
+ During candidate review, install the private core artifact; public installation
171
+ requires verified core2.0.1 availability first.
172
+ Generated servers do not depend on rpc-client; your frontend does.
171
173
 
172
174
  ## Functions and middleware
173
175
 
@@ -283,3 +285,11 @@ application's package manager and lockfile policy.
283
285
  [Security policy](https://github.com/CellsWeb/crpc-node/security/policy)
284
286
 
285
287
  MIT ©2026 CellsWeb. See [LICENSE](https://github.com/CellsWeb/crpc-node/blob/main/LICENSE).
288
+
289
+ ## Non-destructive scaffolding
290
+
291
+ The integrated safety fix refuses an existing final project/function/middleware
292
+ target, even an empty directory, without modifying it. Existing namespace parents
293
+ are allowed. Review, remove or rename conflicts manually; there is no force,
294
+ overwrite, replacement confirmation or automatic backup. This fix is not in the
295
+ historical2.0.0 tools. See [release availability](https://cellsweb.github.io/crpc-node/cli/#release-availability).
@@ -20,6 +20,7 @@
20
20
  import * as p from "@clack/prompts";
21
21
  import fs from "node:fs";
22
22
  import path from "node:path";
23
+ import { functionSegments, planScaffold, writeScaffolds } from "./scaffold-files.cjs";
23
24
  import { glob } from "tinyglobby";
24
25
 
25
26
  const MAX_RETRIES = 5;
@@ -502,7 +503,7 @@ describe("RPC Security & Execution Audit: ${ns}.${fn}", () => {
502
503
  /**
503
504
  * Programmatic function scaffolder.
504
505
  */
505
- export async function scaffoldFunction(options) {
506
+ function planFunction(options, projectRoot) {
506
507
  const namespace = options.namespace || options.ns;
507
508
  const name = options.name || options.fn || options.functionName;
508
509
  if (!namespace || !name) {
@@ -516,19 +517,17 @@ export async function scaffoldFunction(options) {
516
517
  contentType === "multipart/form-data" || contentType === "multipart";
517
518
 
518
519
  const targetDir = options.targetDir || FUNCTIONS_DIR;
519
- const nsDir = path.join(targetDir, namespace.replace(/\./g, path.sep));
520
- const fnDir = path.join(nsDir, name);
521
-
522
- fs.mkdirSync(fnDir, { recursive: true });
523
- fs.writeFileSync(path.join(fnDir, "constants.ts"), tplConstants(namespace, name, isMultipart, description));
524
- fs.writeFileSync(path.join(fnDir, "run.ts"), tplRun(namespace, name, isMultipart, middlewares));
525
- fs.writeFileSync(path.join(fnDir, "test.ts"), tplTest(namespace, name, isMultipart, middlewares));
526
-
527
- if (middlewares.length > 0) {
528
- fs.writeFileSync(path.join(fnDir, "middlewares.ts"), tplMiddlewares(namespace, name, middlewares));
529
- }
520
+ const files = [
521
+ ["constants.ts", tplConstants(namespace, name, isMultipart, description)],
522
+ ["run.ts", tplRun(namespace, name, isMultipart, middlewares)],
523
+ ["test.ts", tplTest(namespace, name, isMultipart, middlewares)],
524
+ ];
525
+ if (middlewares.length > 0) files.push(["middlewares.ts", tplMiddlewares(namespace, name, middlewares)]);
526
+ return planScaffold(targetDir, functionSegments(namespace, name), files, projectRoot);
527
+ }
530
528
 
531
- return fnDir;
529
+ export async function scaffoldFunction(options) {
530
+ return writeScaffolds([planFunction(options)])[0];
532
531
  }
533
532
 
534
533
  function parseCliArgs() {
@@ -601,8 +600,10 @@ async function main() {
601
600
  if (cliArgs.isCli) {
602
601
  if (cliArgs.batch) {
603
602
  console.log(`Scaffolding batch of ${cliArgs.batch.length} functions...`);
604
- for (const item of cliArgs.batch) {
605
- const fnDir = await scaffoldFunction(item);
603
+ const plans = cliArgs.batch.map(item => planFunction(item, ROOT));
604
+ const dirs = writeScaffolds(plans);
605
+ for (const [index, item] of cliArgs.batch.entries()) {
606
+ const fnDir = dirs[index];
606
607
  const nsName = item.namespace || item.ns;
607
608
  const fName = item.name || item.fn || item.functionName;
608
609
  console.log(` ✔ Created: ${nsName}.${fName} -> ${path.relative(ROOT, fnDir)}`);
@@ -612,7 +613,7 @@ async function main() {
612
613
  }
613
614
 
614
615
  if (cliArgs.single) {
615
- const fnDir = await scaffoldFunction(cliArgs.single);
616
+ const [fnDir] = writeScaffolds([planFunction(cliArgs.single, ROOT)]);
616
617
  console.log(`✔ Created ${cliArgs.single.namespace}.${cliArgs.single.name} -> ${path.relative(ROOT, fnDir)}`);
617
618
  return;
618
619
  }
@@ -666,15 +667,7 @@ async function main() {
666
667
  if (p.isCancel(raw)) { p.cancel("Cancelled."); process.exit(0); }
667
668
 
668
669
  const name = raw.trim();
669
- if (fs.existsSync(path.join(nsDir, name))) {
670
- const remaining = MAX_RETRIES - attempt - 1;
671
- if (remaining === 0) {
672
- p.log.error(`"${name}" already exists. Aborting.`);
673
- process.exit(1);
674
- }
675
- p.log.warn(`"${namespace}.${name}" already exists. (${remaining} left)`);
676
- continue;
677
- }
670
+ planScaffold(FUNCTIONS_DIR, functionSegments(namespace, name), [], ROOT);
678
671
 
679
672
  functionName = name;
680
673
  break;
@@ -708,12 +701,12 @@ async function main() {
708
701
  spin.start("Writing files…");
709
702
 
710
703
  try {
711
- await scaffoldFunction({
704
+ writeScaffolds([planFunction({
712
705
  namespace,
713
706
  name: functionName,
714
707
  contentType: isMultipart ? "multipart" : "json",
715
708
  middlewares: selectedMws,
716
- });
709
+ }, ROOT)]);
717
710
  spin.stop("Done");
718
711
  } catch (err) {
719
712
  spin.stop("Failed");
@@ -20,6 +20,7 @@
20
20
  import * as p from "@clack/prompts";
21
21
  import fs from "node:fs";
22
22
  import path from "node:path";
23
+ import { middlewareSegments, planScaffold, writeScaffolds } from "./scaffold-files.cjs";
23
24
 
24
25
  const MAX_RETRIES = 5;
25
26
  const ROOT = process.cwd();
@@ -191,17 +192,16 @@ describe("middleware: ${name}", () => {
191
192
  /**
192
193
  * Programmatic middleware scaffolder.
193
194
  */
194
- export async function scaffoldMiddleware(options) {
195
+ function planMiddleware(options, projectRoot) {
195
196
  const { name, description } = options;
196
197
  const targetDir = options.targetDir || MIDDLEWARES_DIR;
197
- const mwDir = path.join(targetDir, name);
198
-
199
- fs.mkdirSync(mwDir, { recursive: true });
200
- fs.writeFileSync(path.join(mwDir, "constants.ts"), tplConstants(name, description));
201
- fs.writeFileSync(path.join(mwDir, "run.ts"), tplRun(name));
202
- fs.writeFileSync(path.join(mwDir, "test.ts"), tplTest(name));
198
+ return planScaffold(targetDir, middlewareSegments(name), [
199
+ ["constants.ts", tplConstants(name, description)], ["run.ts", tplRun(name)], ["test.ts", tplTest(name)],
200
+ ], projectRoot);
201
+ }
203
202
 
204
- return mwDir;
203
+ export async function scaffoldMiddleware(options) {
204
+ return writeScaffolds([planMiddleware(options)])[0];
205
205
  }
206
206
 
207
207
  function parseCliArgs() {
@@ -267,8 +267,9 @@ async function main() {
267
267
  if (cliArgs.isCli) {
268
268
  if (cliArgs.batch) {
269
269
  console.log(`Scaffolding batch of ${cliArgs.batch.length} middlewares...`);
270
- for (const item of cliArgs.batch) {
271
- const mwDir = await scaffoldMiddleware(item);
270
+ const dirs = writeScaffolds(cliArgs.batch.map(item => planMiddleware(item, ROOT)));
271
+ for (const [index, item] of cliArgs.batch.entries()) {
272
+ const mwDir = dirs[index];
272
273
  console.log(` ✔ Created: ${item.name} -> ${path.relative(ROOT, mwDir)}`);
273
274
  }
274
275
  console.log("Batch middleware scaffolding complete.");
@@ -276,7 +277,7 @@ async function main() {
276
277
  }
277
278
 
278
279
  if (cliArgs.single) {
279
- const mwDir = await scaffoldMiddleware(cliArgs.single);
280
+ const [mwDir] = writeScaffolds([planMiddleware(cliArgs.single, ROOT)]);
280
281
  console.log(`✔ Created middleware ${cliArgs.single.name} -> ${path.relative(ROOT, mwDir)}`);
281
282
  return;
282
283
  }
@@ -302,15 +303,7 @@ async function main() {
302
303
  if (p.isCancel(raw)) { p.cancel("Cancelled."); process.exit(0); }
303
304
 
304
305
  const name = raw.trim();
305
- if (fs.existsSync(path.join(MIDDLEWARES_DIR, name))) {
306
- const remaining = MAX_RETRIES - attempt - 1;
307
- if (remaining === 0) {
308
- p.log.error(`"${name}" already exists. Aborting.`);
309
- process.exit(1);
310
- }
311
- p.log.warn(`Middleware "${name}" already exists. (${remaining} left)`);
312
- continue;
313
- }
306
+ planScaffold(MIDDLEWARES_DIR, middlewareSegments(name), [], ROOT);
314
307
 
315
308
  middlewareName = name;
316
309
  break;
@@ -321,7 +314,7 @@ async function main() {
321
314
  spin.start("Writing files…");
322
315
 
323
316
  try {
324
- await scaffoldMiddleware({ name: middlewareName });
317
+ writeScaffolds([planMiddleware({ name: middlewareName }, ROOT)]);
325
318
  spin.stop("Done");
326
319
  } catch (err) {
327
320
  spin.stop("Failed");
package/bin/create.js CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { execSync } from "node:child_process";
14
14
  import fs from "node:fs";
15
+ import { planScaffold, writeScaffolds } from "./scaffold-files.cjs";
15
16
  import path from "node:path";
16
17
  import readline from "node:readline";
17
18
  import { fileURLToPath } from "node:url";
@@ -55,17 +56,15 @@ const ask = (question, defaultVal) =>
55
56
  });
56
57
 
57
58
  // ─── Copy helper (recursive) ──────────────────────────────────────────────────
58
- function copyDir(src, dest) {
59
- fs.mkdirSync(dest, { recursive: true });
59
+ function collectTemplate(src, prefix = "", files = new Map()) {
60
60
  for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
61
- const srcPath = path.join(src, entry.name);
62
- const destPath = path.join(dest, entry.name);
63
- if (entry.isDirectory()) {
64
- copyDir(srcPath, destPath);
65
- } else {
66
- fs.copyFileSync(srcPath, destPath);
67
- }
61
+ const source = path.join(src, entry.name);
62
+ const name = path.join(prefix, entry.name);
63
+ if (entry.isDirectory()) collectTemplate(source, name, files);
64
+ else if (entry.isFile()) files.set(name, fs.readFileSync(source));
65
+ else throw new Error(`Unsupported template entry: ${source}`);
68
66
  }
67
+ return files;
69
68
  }
70
69
 
71
70
  // ─── Main ─────────────────────────────────────────────────────────────────────
@@ -146,6 +145,10 @@ async function main() {
146
145
  targetDir = path.resolve(process.cwd(), answer);
147
146
  }
148
147
 
148
+ const parent = path.dirname(targetDir);
149
+ const name = path.basename(targetDir);
150
+ planScaffold(parent, [name], []); // Refuse even an empty directory, before any write.
151
+
149
152
  const defaultName =
150
153
  path.basename(targetDir) === "" || path.basename(targetDir) === "/"
151
154
  ? "my-rpc-api"
@@ -182,20 +185,16 @@ async function main() {
182
185
  }
183
186
 
184
187
  // ── 2. Guard ───────────────────────────────────────────────────────────────
185
- if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
186
- console.log(`\n ${yellow("⚠")} ${bold(targetDir)} already exists and is not empty.`);
187
- console.log(` Files will be merged — existing files will NOT be overwritten.\n`);
188
- }
189
188
 
190
189
  // ── 3. Copy template ───────────────────────────────────────────────────────
191
190
  const templateDir = path.join(__dirname, "..", "template");
192
191
  console.log(`\n ${dim("Scaffolding into")} ${cyan(targetDir)} ...\n`);
193
- copyDir(templateDir, targetDir);
192
+ const files = collectTemplate(templateDir);
194
193
 
195
194
  // ── 3.5 Swap server.ts template if non-default framework selected ─────────
196
195
  const serverTemplatePath = path.join(__dirname, "..", "templates", "servers", `server.${framework}.ts`);
197
196
  if (fs.existsSync(serverTemplatePath)) {
198
- fs.copyFileSync(serverTemplatePath, path.join(targetDir, "src", "server.ts"));
197
+ files.set(path.join("src", "server.ts"), fs.readFileSync(serverTemplatePath));
199
198
  }
200
199
 
201
200
  // ── 4. Write package.json ──────────────────────────────────────────────────
@@ -220,7 +219,7 @@ async function main() {
220
219
  node: ">=24.0.0",
221
220
  },
222
221
  dependencies: {
223
- "@cellsweb/rpc-core": "^1.0.34",
222
+ "@cellsweb/rpc-core": "^2.0.1",
224
223
  "@aws-sdk/client-s3": "^3.700.0",
225
224
  "@paralleldrive/cuid2": "^2.2.2",
226
225
  "@sentry/node": "^8.40.0",
@@ -269,7 +268,7 @@ async function main() {
269
268
  // Bun native requires zero extra dependencies!
270
269
  }
271
270
 
272
- fs.writeFileSync(path.join(targetDir, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
271
+ files.set("package.json", JSON.stringify(pkg, null, 2) + "\n");
273
272
 
274
273
  // ── 5. Write tsconfig.json ─────────────────────────────────────────────────
275
274
  const tsconfig = {
@@ -292,23 +291,14 @@ async function main() {
292
291
  include: ["src/**/*"],
293
292
  exclude: ["node_modules", "dist"],
294
293
  };
295
- fs.writeFileSync(path.join(targetDir, "tsconfig.json"), JSON.stringify(tsconfig, null, 2) + "\n");
294
+ files.set("tsconfig.json", JSON.stringify(tsconfig, null, 2) + "\n");
296
295
 
297
296
  // ── 6. Write .gitignore & .npmrc ──────────────────────────────────────────
298
297
  const gitignore = ["node_modules", "dist", ".env", "*.log", ".DS_Store"].join("\n") + "\n";
299
- const giPath = path.join(targetDir, ".gitignore");
300
- if (!fs.existsSync(giPath)) fs.writeFileSync(giPath, gitignore);
301
-
302
- const npmrc = "onlyBuiltDependencies=esbuild\n";
303
- const npmrcPath = path.join(targetDir, ".npmrc");
304
- if (!fs.existsSync(npmrcPath)) fs.writeFileSync(npmrcPath, npmrc);
305
-
306
- // ── 7.5 Copy .env.example -> .env ────────────────────────────────────────
307
- const envExamplePath = path.join(targetDir, ".env.example");
308
- const envPath = path.join(targetDir, ".env");
309
- if (fs.existsSync(envExamplePath) && !fs.existsSync(envPath)) {
310
- fs.copyFileSync(envExamplePath, envPath);
311
- }
298
+ if (!files.has(".gitignore")) files.set(".gitignore", gitignore);
299
+ if (!files.has(".npmrc")) files.set(".npmrc", "onlyBuiltDependencies=esbuild\n");
300
+ if (files.has(".env.example") && !files.has(".env")) files.set(".env", files.get(".env.example"));
301
+ writeScaffolds([planScaffold(parent, [name], [...files])]);
312
302
 
313
303
  // ── 8. Install ────────────────────────────────────────────────────────────
314
304
  if (!skipInstall) {
@@ -0,0 +1,131 @@
1
+ // Shared by the packaged CLI and SDK. Never merge into an existing target.
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+
5
+ function conflict(target) {
6
+ return new Error(`Refusing to scaffold: target already exists or conflicts: ${target}. Manually review, remove, or rename the existing target, then rerun the generator.`);
7
+ }
8
+ function stat(target) {
9
+ try { return fs.lstatSync(target); } catch (e) { if (e.code === "ENOENT") return null; throw e; }
10
+ }
11
+ function within(parent, child) {
12
+ const rel = path.relative(parent, child);
13
+ return rel === "" || (!rel.startsWith(`..${path.sep}`) && rel !== ".." && !path.isAbsolute(rel));
14
+ }
15
+ function checkParents(dir) {
16
+ const parent = path.dirname(dir);
17
+ if (parent !== dir) checkParents(parent);
18
+ const s = stat(dir);
19
+ if (s && (!s.isDirectory() || s.isSymbolicLink())) throw conflict(dir);
20
+ }
21
+ function identifier(name, label, pattern) {
22
+ if (typeof name !== "string" || !pattern.test(name)) throw new Error(`Invalid ${label}: use a name, not a path.`);
23
+ return name;
24
+ }
25
+ exports.functionSegments = (namespace, name) => {
26
+ identifier(namespace, "namespace", /^[A-Za-z_$][A-Za-z0-9_$-]*(\.[A-Za-z_$][A-Za-z0-9_$-]*)*$/);
27
+ identifier(name, "function name", /^[A-Za-z_$][A-Za-z0-9_$.-]*$/);
28
+ return [...namespace.split("."), name];
29
+ };
30
+ exports.middlewareSegments = (name) => [identifier(name, "middleware name", /^[A-Za-z_$][A-Za-z0-9_$]*$/)];
31
+
32
+ exports.planScaffold = (root, segments, files, projectRoot) => {
33
+ let resolved = path.resolve(root);
34
+ if (projectRoot) {
35
+ const project = path.resolve(projectRoot);
36
+ if (!within(project, resolved)) throw new Error("Scaffold destination must stay inside the configured project directory.");
37
+ resolved = path.join(fs.realpathSync(project), path.relative(project, resolved));
38
+ checkParents(resolved);
39
+ } else {
40
+ // An explicit SDK targetDir is the configured root; canonicalize its existing
41
+ // parent (including OS aliases such as /tmp), never an untrusted child link.
42
+ const missing = []; let ancestor = resolved;
43
+ while (!stat(ancestor)) { missing.unshift(path.basename(ancestor)); ancestor = path.dirname(ancestor); }
44
+ const s = stat(ancestor);
45
+ if (!s.isDirectory() || s.isSymbolicLink()) throw conflict(ancestor);
46
+ resolved = path.join(fs.realpathSync(ancestor), ...missing);
47
+ }
48
+ for (const segment of segments) {
49
+ identifier(segment, "destination component", /^[^/\\\0]+$/);
50
+ if (segment === "." || segment === "..") throw new Error("Invalid destination component.");
51
+ }
52
+ const target = path.join(resolved, ...segments);
53
+ if (!within(resolved, target) || target === resolved) throw new Error("Invalid scaffold destination.");
54
+ checkParents(path.dirname(target));
55
+ if (stat(target)) throw conflict(target); // lstat also detects dangling links.
56
+ const names = new Set();
57
+ const output = files.map(([name, content]) => {
58
+ if (path.isAbsolute(name) || name.split(/[\\/]/).some(p => !p || p === "." || p === "..") || names.has(name)) throw new Error("Invalid generated filename.");
59
+ names.add(name);
60
+ return [name, Buffer.from(content)];
61
+ });
62
+ return { target, displayTarget: path.join(root, ...segments), files: output };
63
+ };
64
+ function same(a, b) { return a && b && a.dev === b.dev && a.ino === b.ino; }
65
+ function preflight(plans) {
66
+ const key = p => process.platform === "darwin" || process.platform === "win32" ? p.toLowerCase() : p;
67
+ const targets = [];
68
+ for (const p of plans) {
69
+ checkParents(path.dirname(p.target));
70
+ if (stat(p.target)) throw conflict(p.target);
71
+ const target = key(p.target);
72
+ if (targets.some(t => within(t, target) || within(target, t))) throw conflict(p.target);
73
+ targets.push(target);
74
+ }
75
+ }
76
+ exports.writeScaffolds = (plans) => {
77
+ preflight(plans); // Entire batch validates before the first mkdir/write.
78
+ const dirs = [], files = [];
79
+ function mkdir(dir, final = false) {
80
+ if (!final) {
81
+ const s = stat(dir);
82
+ if (s) { if (!s.isDirectory() || s.isSymbolicLink()) throw conflict(dir); return; }
83
+ mkdir(path.dirname(dir));
84
+ }
85
+ try { fs.mkdirSync(dir); }
86
+ catch (e) {
87
+ const s = stat(dir);
88
+ if (!final && e.code === "EEXIST" && s?.isDirectory() && !s.isSymbolicLink()) return;
89
+ if (e.code === "EEXIST") throw conflict(dir);
90
+ throw e;
91
+ }
92
+ dirs.push({ path: dir, info: fs.lstatSync(dir) });
93
+ }
94
+ try {
95
+ for (const p of plans) {
96
+ mkdir(path.dirname(p.target));
97
+ mkdir(p.target, true); // Exclusive reservation, never recursive on final.
98
+ const owned = dirs[dirs.length - 1];
99
+ for (const [name, content] of p.files) {
100
+ checkParents(p.target);
101
+ if (!same(stat(p.target), owned.info)) throw conflict(p.target);
102
+ const dest = path.join(p.target, name);
103
+ mkdir(path.dirname(dest));
104
+ let fd;
105
+ try { fd = fs.openSync(dest, "wx", 0o644); }
106
+ catch (error) { if (error.code === "EEXIST") throw conflict(dest); throw error; }
107
+ const file = { path: dest, info: fs.fstatSync(fd), content, complete: false };
108
+ files.push(file);
109
+ try { fs.writeFileSync(fd, content); file.complete = true; } finally { fs.closeSync(fd); }
110
+ }
111
+ }
112
+ } catch (error) {
113
+ // No recursive removal. Preserve injected/replaced/edited developer files.
114
+ for (const f of files.reverse()) {
115
+ try {
116
+ checkParents(path.dirname(f.path));
117
+ const s = stat(f.path);
118
+ if (same(s, f.info) && s.isFile() && s.size <= f.content.length) {
119
+ const actual = fs.readFileSync(f.path);
120
+ const unchanged = f.complete ? actual.equals(f.content) : actual.equals(f.content.subarray(0, actual.length));
121
+ if (actual.length <= f.content.length && unchanged) fs.unlinkSync(f.path);
122
+ }
123
+ } catch { /* Conservative: leave an artifact when ownership is uncertain. */ }
124
+ }
125
+ for (const d of dirs.reverse()) {
126
+ try { checkParents(path.dirname(d.path)); if (same(stat(d.path), d.info)) fs.rmdirSync(d.path); } catch { /* Nonempty/replaced directories are retained. */ }
127
+ }
128
+ throw error;
129
+ }
130
+ return plans.map(p => p.displayTarget ?? p.target);
131
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-cellsweb-rpc-api",
3
- "version": "1.0.31",
3
+ "version": "2.0.1",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -1,3 +1,5 @@
1
+ > **CellsWeb RPC 2.0.0 is published.** Install the packages from the public npm registry using the commands below.
2
+
1
3
  # Generated CellsWeb RPC application
2
4
 
3
5
  Node 24 LTS is primary (engines >=24.0.0). Bun/Elysia templates run under Bun,
@@ -10,7 +12,8 @@ npm run build
10
12
  npm start
11
13
  ```
12
14
 
13
- The generated core requirement is ^1.0.34 and resolves from public npm.
15
+ The generated core requirement is ^2.0.0 and resolves from public npm after v2 publication.
16
+ Install dependencies from public npm; the generated core dependency selects compatible v2 releases.
14
17
  Use ordinary package installation; no local SDK checkout or override is required.
15
18
 
16
19
  Use npm run dev for Node development. For Bun select Bun execution, for example
@@ -16,7 +16,7 @@ export const app = new CoreRPC({
16
16
  docs: env.NODE_ENV !== "production" || env.API_DOCS_ENABLED === true,
17
17
  });
18
18
 
19
- export const fetchHandler = async (req: Request): Promise<Response> => {
19
+ export const fetchHandler = async (req: Request, server?: { requestIP(request: Request): { address: string } | null }): Promise<Response> => {
20
20
  const url = new URL(req.url);
21
21
 
22
22
  // ── Static Files Route (/uploads/*) ──
@@ -46,7 +46,7 @@ export const fetchHandler = async (req: Request): Promise<Response> => {
46
46
  }
47
47
 
48
48
  // ── Dispatch to CellsWeb RPC (Handles /rpc, /docs, /health, OPTIONS) ──
49
- return await app.fetch(req);
49
+ return await app.fetch(req, server);
50
50
  };
51
51
 
52
52
  // Bun default export supports `bun run src/server.ts`