@parrel/ledger 0.0.0-stage → 5.0.0

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.
Files changed (239) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +793 -2
  3. package/dist/cli/commands.d.ts +51 -0
  4. package/dist/cli/commands.d.ts.map +1 -0
  5. package/dist/cli/commands.js +968 -0
  6. package/dist/cli/commands.js.map +1 -0
  7. package/dist/cli/index.d.ts +24 -0
  8. package/dist/cli/index.d.ts.map +1 -0
  9. package/dist/cli/index.js +35 -0
  10. package/dist/cli/index.js.map +1 -0
  11. package/dist/cli/parrel.d.ts +3 -0
  12. package/dist/cli/parrel.d.ts.map +1 -0
  13. package/dist/cli/parrel.js +5 -0
  14. package/dist/cli/parrel.js.map +1 -0
  15. package/dist/cli/utils/angular-setup.d.ts +14 -0
  16. package/dist/cli/utils/angular-setup.d.ts.map +1 -0
  17. package/dist/cli/utils/angular-setup.js +96 -0
  18. package/dist/cli/utils/angular-setup.js.map +1 -0
  19. package/dist/cli/utils/api-tree-builder.d.ts +24 -0
  20. package/dist/cli/utils/api-tree-builder.d.ts.map +1 -0
  21. package/dist/cli/utils/api-tree-builder.js +146 -0
  22. package/dist/cli/utils/api-tree-builder.js.map +1 -0
  23. package/dist/cli/utils/bundle-reader.d.ts +185 -0
  24. package/dist/cli/utils/bundle-reader.d.ts.map +1 -0
  25. package/dist/cli/utils/bundle-reader.js +518 -0
  26. package/dist/cli/utils/bundle-reader.js.map +1 -0
  27. package/dist/cli/utils/collision-detector.d.ts +21 -0
  28. package/dist/cli/utils/collision-detector.d.ts.map +1 -0
  29. package/dist/cli/utils/collision-detector.js +53 -0
  30. package/dist/cli/utils/collision-detector.js.map +1 -0
  31. package/dist/cli/utils/map-fields.d.ts +42 -0
  32. package/dist/cli/utils/map-fields.d.ts.map +1 -0
  33. package/dist/cli/utils/map-fields.js +90 -0
  34. package/dist/cli/utils/map-fields.js.map +1 -0
  35. package/dist/cli/utils/map-validator.d.ts +42 -0
  36. package/dist/cli/utils/map-validator.d.ts.map +1 -0
  37. package/dist/cli/utils/map-validator.js +119 -0
  38. package/dist/cli/utils/map-validator.js.map +1 -0
  39. package/dist/cli/utils/media-file.d.ts +41 -0
  40. package/dist/cli/utils/media-file.d.ts.map +1 -0
  41. package/dist/cli/utils/media-file.js +72 -0
  42. package/dist/cli/utils/media-file.js.map +1 -0
  43. package/dist/cli/utils/media-validator.d.ts +10 -0
  44. package/dist/cli/utils/media-validator.d.ts.map +1 -0
  45. package/dist/cli/utils/media-validator.js +85 -0
  46. package/dist/cli/utils/media-validator.js.map +1 -0
  47. package/dist/cli/utils/mock-augmenter.d.ts +19 -0
  48. package/dist/cli/utils/mock-augmenter.d.ts.map +1 -0
  49. package/dist/cli/utils/mock-augmenter.js +102 -0
  50. package/dist/cli/utils/mock-augmenter.js.map +1 -0
  51. package/dist/cli/utils/mock-validator.d.ts +27 -0
  52. package/dist/cli/utils/mock-validator.d.ts.map +1 -0
  53. package/dist/cli/utils/mock-validator.js +214 -0
  54. package/dist/cli/utils/mock-validator.js.map +1 -0
  55. package/dist/cli/utils/project-dir.d.ts +24 -0
  56. package/dist/cli/utils/project-dir.d.ts.map +1 -0
  57. package/dist/cli/utils/project-dir.js +32 -0
  58. package/dist/cli/utils/project-dir.js.map +1 -0
  59. package/dist/cli/utils/schema-loader.d.ts +19 -0
  60. package/dist/cli/utils/schema-loader.d.ts.map +1 -0
  61. package/dist/cli/utils/schema-loader.js +101 -0
  62. package/dist/cli/utils/schema-loader.js.map +1 -0
  63. package/dist/cli/utils/server-entry.d.ts +34 -0
  64. package/dist/cli/utils/server-entry.d.ts.map +1 -0
  65. package/dist/cli/utils/server-entry.js +111 -0
  66. package/dist/cli/utils/server-entry.js.map +1 -0
  67. package/dist/cli/utils/sync.d.ts +116 -0
  68. package/dist/cli/utils/sync.d.ts.map +1 -0
  69. package/dist/cli/utils/sync.js +134 -0
  70. package/dist/cli/utils/sync.js.map +1 -0
  71. package/dist/client/index.d.ts +39 -0
  72. package/dist/client/index.d.ts.map +1 -0
  73. package/dist/client/index.js +88 -0
  74. package/dist/client/index.js.map +1 -0
  75. package/dist/core/browser-session.d.ts +5 -0
  76. package/dist/core/browser-session.d.ts.map +1 -0
  77. package/dist/core/browser-session.js +12 -0
  78. package/dist/core/browser-session.js.map +1 -0
  79. package/dist/core/cache.d.ts +80 -0
  80. package/dist/core/cache.d.ts.map +1 -0
  81. package/dist/core/cache.js +95 -0
  82. package/dist/core/cache.js.map +1 -0
  83. package/dist/core/client.d.ts +64 -0
  84. package/dist/core/client.d.ts.map +1 -0
  85. package/dist/core/client.js +281 -0
  86. package/dist/core/client.js.map +1 -0
  87. package/dist/core/config.d.ts +20 -0
  88. package/dist/core/config.d.ts.map +1 -0
  89. package/dist/core/config.js +32 -0
  90. package/dist/core/config.js.map +1 -0
  91. package/dist/core/copy-read.d.ts +25 -0
  92. package/dist/core/copy-read.d.ts.map +1 -0
  93. package/dist/core/copy-read.js +123 -0
  94. package/dist/core/copy-read.js.map +1 -0
  95. package/dist/core/define-ledger.d.ts +38 -0
  96. package/dist/core/define-ledger.d.ts.map +1 -0
  97. package/dist/core/define-ledger.js +65 -0
  98. package/dist/core/define-ledger.js.map +1 -0
  99. package/dist/core/deprecated.d.ts +16 -0
  100. package/dist/core/deprecated.d.ts.map +1 -0
  101. package/dist/core/deprecated.js +14 -0
  102. package/dist/core/deprecated.js.map +1 -0
  103. package/dist/core/env.d.ts +103 -0
  104. package/dist/core/env.d.ts.map +1 -0
  105. package/dist/core/env.js +208 -0
  106. package/dist/core/env.js.map +1 -0
  107. package/dist/core/error-codes.generated.d.ts +12 -0
  108. package/dist/core/error-codes.generated.d.ts.map +1 -0
  109. package/dist/core/error-codes.generated.js +3 -0
  110. package/dist/core/error-codes.generated.js.map +1 -0
  111. package/dist/core/get-content.d.ts +62 -0
  112. package/dist/core/get-content.d.ts.map +1 -0
  113. package/dist/core/get-content.js +86 -0
  114. package/dist/core/get-content.js.map +1 -0
  115. package/dist/core/get-media.d.ts +58 -0
  116. package/dist/core/get-media.d.ts.map +1 -0
  117. package/dist/core/get-media.js +89 -0
  118. package/dist/core/get-media.js.map +1 -0
  119. package/dist/core/manifest.d.ts +38 -0
  120. package/dist/core/manifest.d.ts.map +1 -0
  121. package/dist/core/manifest.js +93 -0
  122. package/dist/core/manifest.js.map +1 -0
  123. package/dist/core/media-proxy.d.ts +41 -0
  124. package/dist/core/media-proxy.d.ts.map +1 -0
  125. package/dist/core/media-proxy.js +219 -0
  126. package/dist/core/media-proxy.js.map +1 -0
  127. package/dist/core/package-info.d.ts +34 -0
  128. package/dist/core/package-info.d.ts.map +1 -0
  129. package/dist/core/package-info.js +39 -0
  130. package/dist/core/package-info.js.map +1 -0
  131. package/dist/core/parrel-error.d.ts +160 -0
  132. package/dist/core/parrel-error.d.ts.map +1 -0
  133. package/dist/core/parrel-error.js +198 -0
  134. package/dist/core/parrel-error.js.map +1 -0
  135. package/dist/core/transform-content.d.ts +42 -0
  136. package/dist/core/transform-content.d.ts.map +1 -0
  137. package/dist/core/transform-content.js +185 -0
  138. package/dist/core/transform-content.js.map +1 -0
  139. package/dist/core/types.d.ts +406 -0
  140. package/dist/core/types.d.ts.map +1 -0
  141. package/dist/core/types.js +11 -0
  142. package/dist/core/types.js.map +1 -0
  143. package/dist/errors/error-messages.generated.d.ts +5 -0
  144. package/dist/errors/error-messages.generated.d.ts.map +1 -0
  145. package/dist/errors/error-messages.generated.js +971 -0
  146. package/dist/errors/error-messages.generated.js.map +1 -0
  147. package/dist/errors/get-error-info.d.ts +29 -0
  148. package/dist/errors/get-error-info.d.ts.map +1 -0
  149. package/dist/errors/get-error-info.js +43 -0
  150. package/dist/errors/get-error-info.js.map +1 -0
  151. package/dist/errors/index.d.ts +4 -0
  152. package/dist/errors/index.d.ts.map +1 -0
  153. package/dist/errors/index.js +4 -0
  154. package/dist/errors/index.js.map +1 -0
  155. package/dist/errors/types.d.ts +19 -0
  156. package/dist/errors/types.d.ts.map +1 -0
  157. package/dist/errors/types.js +2 -0
  158. package/dist/errors/types.js.map +1 -0
  159. package/dist/generated.d.ts +29 -0
  160. package/dist/generated.d.ts.map +1 -0
  161. package/dist/generated.js +29 -0
  162. package/dist/generated.js.map +1 -0
  163. package/dist/index.d.ts +19 -0
  164. package/dist/index.d.ts.map +1 -0
  165. package/dist/index.js +16 -0
  166. package/dist/index.js.map +1 -0
  167. package/dist/mock/dev-media.d.ts +15 -0
  168. package/dist/mock/dev-media.d.ts.map +1 -0
  169. package/dist/mock/dev-media.js +52 -0
  170. package/dist/mock/dev-media.js.map +1 -0
  171. package/dist/mock/file-store.d.ts +44 -0
  172. package/dist/mock/file-store.d.ts.map +1 -0
  173. package/dist/mock/file-store.js +170 -0
  174. package/dist/mock/file-store.js.map +1 -0
  175. package/dist/mock/index.d.ts +4 -0
  176. package/dist/mock/index.d.ts.map +1 -0
  177. package/dist/mock/index.js +3 -0
  178. package/dist/mock/index.js.map +1 -0
  179. package/dist/mock/media-fields.d.ts +25 -0
  180. package/dist/mock/media-fields.d.ts.map +1 -0
  181. package/dist/mock/media-fields.js +54 -0
  182. package/dist/mock/media-fields.js.map +1 -0
  183. package/dist/mock/mock-adapter.d.ts +65 -0
  184. package/dist/mock/mock-adapter.d.ts.map +1 -0
  185. package/dist/mock/mock-adapter.js +431 -0
  186. package/dist/mock/mock-adapter.js.map +1 -0
  187. package/dist/mock/mock-errors.d.ts +18 -0
  188. package/dist/mock/mock-errors.d.ts.map +1 -0
  189. package/dist/mock/mock-errors.js +56 -0
  190. package/dist/mock/mock-errors.js.map +1 -0
  191. package/dist/mock/node-import.d.ts +13 -0
  192. package/dist/mock/node-import.d.ts.map +1 -0
  193. package/dist/mock/node-import.js +16 -0
  194. package/dist/mock/node-import.js.map +1 -0
  195. package/dist/mock/seed-mock-store.d.ts +14 -0
  196. package/dist/mock/seed-mock-store.d.ts.map +1 -0
  197. package/dist/mock/seed-mock-store.js +106 -0
  198. package/dist/mock/seed-mock-store.js.map +1 -0
  199. package/dist/mock/shared-memory-store.d.ts +35 -0
  200. package/dist/mock/shared-memory-store.d.ts.map +1 -0
  201. package/dist/mock/shared-memory-store.js +46 -0
  202. package/dist/mock/shared-memory-store.js.map +1 -0
  203. package/dist/next/dev-rendering-helpers.d.ts +78 -0
  204. package/dist/next/dev-rendering-helpers.d.ts.map +1 -0
  205. package/dist/next/dev-rendering-helpers.js +103 -0
  206. package/dist/next/dev-rendering-helpers.js.map +1 -0
  207. package/dist/next/index.d.ts +35 -0
  208. package/dist/next/index.d.ts.map +1 -0
  209. package/dist/next/index.js +33 -0
  210. package/dist/next/index.js.map +1 -0
  211. package/dist/next/next-cache-adapter.d.ts +11 -0
  212. package/dist/next/next-cache-adapter.d.ts.map +1 -0
  213. package/dist/next/next-cache-adapter.js +12 -0
  214. package/dist/next/next-cache-adapter.js.map +1 -0
  215. package/dist/nuxt/index.d.ts +22 -0
  216. package/dist/nuxt/index.d.ts.map +1 -0
  217. package/dist/nuxt/index.js +57 -0
  218. package/dist/nuxt/index.js.map +1 -0
  219. package/dist/sveltekit/index.d.ts +35 -0
  220. package/dist/sveltekit/index.d.ts.map +1 -0
  221. package/dist/sveltekit/index.js +56 -0
  222. package/dist/sveltekit/index.js.map +1 -0
  223. package/dist/ui/content-editor.d.ts +9 -0
  224. package/dist/ui/content-editor.d.ts.map +1 -0
  225. package/dist/ui/content-editor.js +27 -0
  226. package/dist/ui/content-editor.js.map +1 -0
  227. package/dist/ui/index.d.ts +8 -0
  228. package/dist/ui/index.d.ts.map +1 -0
  229. package/dist/ui/index.js +8 -0
  230. package/dist/ui/index.js.map +1 -0
  231. package/dist/ui/ledger-overlay.d.ts +10 -0
  232. package/dist/ui/ledger-overlay.d.ts.map +1 -0
  233. package/dist/ui/ledger-overlay.js +27 -0
  234. package/dist/ui/ledger-overlay.js.map +1 -0
  235. package/dist/ui/media-uploader.d.ts +9 -0
  236. package/dist/ui/media-uploader.d.ts.map +1 -0
  237. package/dist/ui/media-uploader.js +27 -0
  238. package/dist/ui/media-uploader.js.map +1 -0
  239. package/package.json +134 -6
@@ -0,0 +1,968 @@
1
+ // @ts-nocheck (dynamic imports + loose JSON shapes)
2
+ /**
3
+ * `parrel ledger` commands (alias scope: `parrel cms`): install, init, generate,
4
+ * sync (alias: upload), seed, check-mock, clean, help.
5
+ *
6
+ * Shares the interactive helpers (framework detection, slug prompt, file
7
+ * writers, styling) with `@parrel/sentinel/cli` so `init` feels identical across
8
+ * packages.
9
+ */
10
+ import { existsSync } from "node:fs";
11
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
12
+ import path from "node:path";
13
+ import process, { stdin as input, stdout as output } from "node:process";
14
+ import { createInterface } from "node:readline/promises";
15
+ import { FRAMEWORK_LABELS, detectPackageManager, log, printCommandHelp, projectRoot, reportCliError, reportWrite, resolveFramework, resolveSlug, runCommand, style, svelteKitLibImport, writeFileSafe, } from "@parrel/sentinel/cli";
16
+ import { resolveParrelApiOrigin } from "../core/env.js";
17
+ import { ParrelError, isParrelError } from "../core/parrel-error.js";
18
+ import { loadAllSchemas } from "./utils/schema-loader.js";
19
+ import { displayPath, resolveLedgerDir } from "./utils/project-dir.js";
20
+ import { ANGULAR_ENVIRONMENTS_STEP, enableResolveJsonModule, prepareAngularEnvironments, } from "./utils/angular-setup.js";
21
+ import { serverEntryNextStep, writeNuxtServerEntry, writeSveltekitServerEntry, } from "./utils/server-entry.js";
22
+ import { detectCollisions, validateFlatNames } from "./utils/collision-detector.js";
23
+ import { assertMapSetWithinLimits } from "./utils/map-validator.js";
24
+ import { applyMapSync, previewMapSync } from "./utils/sync.js";
25
+ import { generateLedgerClientDeclaration } from "./utils/api-tree-builder.js";
26
+ import { augmentAllMockData } from "./utils/mock-augmenter.js";
27
+ import { validateAllResources, validateMediaFiles } from "./utils/mock-validator.js";
28
+ import { DEFAULT_BUNDLE_LIMITS, extractEntry, openBundle, readEntry, } from "./utils/bundle-reader.js";
29
+ import { isMediaObject } from "../mock/media-fields.js";
30
+ /** The Ledger API of the Parrel API origin: `PARREL_API_ORIGIN`, or the production API when it is not set. */
31
+ export function ledgerBaseUrl() {
32
+ return `${resolveParrelApiOrigin()}/cms/v1`;
33
+ }
34
+ function mapsDirLabel(root) {
35
+ return `${displayPath(root, path.join(resolveLedgerDir(root), "maps"))}/`;
36
+ }
37
+ function resolveProjectRoot() {
38
+ const initCwd = process.env.INIT_CWD;
39
+ if (initCwd) {
40
+ if (existsSync(path.join(resolveLedgerDir(initCwd), "maps"))) {
41
+ return initCwd;
42
+ }
43
+ }
44
+ return process.cwd();
45
+ }
46
+ // ── Sample content (so users see where data comes from) ───────────────────────
47
+ const SAMPLE_SCHEMA = `${JSON.stringify({
48
+ title: { type: "string" },
49
+ subtitle: { type: "string" },
50
+ heroImage: { type: "media", mediaType: "image" },
51
+ }, null, 2)}\n`;
52
+ const SAMPLE_MOCK = `${JSON.stringify({
53
+ homepage: {
54
+ title: "Welcome to Parrel Ledger",
55
+ subtitle: "Edit this mock.json file. In development, content is read from here.",
56
+ heroImage: { file: "hero.svg", alt: "Sample hero image" },
57
+ },
58
+ }, null, 2)}\n`;
59
+ const SAMPLE_HERO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180" viewBox="0 0 320 180">
60
+ <rect width="320" height="180" fill="#6d28d9"/>
61
+ <text x="160" y="96" font-family="sans-serif" font-size="20" fill="#fff" text-anchor="middle">Parrel Ledger</text>
62
+ </svg>
63
+ `;
64
+ // ── Next.js media route templates ─────────────────────────────────────────────
65
+ const NEXT_DEV_MEDIA_ROUTE = `import { NextRequest, NextResponse } from "next/server";
66
+ import path from "path";
67
+ import fs from "fs/promises";
68
+
69
+ // Development-only route: serves mock media files from
70
+ // node_modules/.cache/parrel/media/. Always returns 404 in production.
71
+
72
+ const MIME_TYPES: Record<string, string> = {
73
+ ".pdf": "application/pdf",
74
+ ".png": "image/png",
75
+ ".jpg": "image/jpeg",
76
+ ".jpeg": "image/jpeg",
77
+ ".gif": "image/gif",
78
+ ".webp": "image/webp",
79
+ ".svg": "image/svg+xml",
80
+ ".avif": "image/avif",
81
+ ".mp4": "video/mp4",
82
+ ".mp3": "audio/mpeg",
83
+ ".json": "application/json",
84
+ };
85
+
86
+ export async function GET(
87
+ _request: NextRequest,
88
+ { params }: { params: Promise<{ path: string[] }> },
89
+ ) {
90
+ if (process.env.NODE_ENV === "production") {
91
+ return new NextResponse("Not found", { status: 404 });
92
+ }
93
+
94
+ const { path: segments } = await params;
95
+ const mediaDir = path.resolve(process.cwd(), "node_modules/.cache/parrel/media");
96
+ const filePath = path.resolve(mediaDir, ...segments);
97
+
98
+ if (!filePath.startsWith(mediaDir + path.sep) && filePath !== mediaDir) {
99
+ return new NextResponse("Forbidden", { status: 403 });
100
+ }
101
+
102
+ try {
103
+ const file = await fs.readFile(filePath);
104
+ const ext = path.extname(filePath).toLowerCase();
105
+ const contentType = MIME_TYPES[ext] ?? "application/octet-stream";
106
+ return new NextResponse(file, {
107
+ headers: { "Content-Type": contentType },
108
+ });
109
+ } catch {
110
+ return new NextResponse("Not found", { status: 404 });
111
+ }
112
+ }
113
+ `;
114
+ const NEXT_PROD_MEDIA_ROUTE = `// Same-origin proxy for Ledger media assets (locked endpoint inside @parrel/ledger).
115
+ import { createLedgerMediaRouteHandlers } from "@parrel/ledger/next";
116
+
117
+ export const { GET } = createLedgerMediaRouteHandlers();
118
+ `;
119
+ const SVELTEKIT_DEV_MEDIA_ROUTE = `// Development-only route: serves the mock media files by file name. Answers 404 in production.
120
+ import { createLedgerDevMediaRoute } from "@parrel/ledger/sveltekit";
121
+
122
+ export const { GET } = createLedgerDevMediaRoute();
123
+ `;
124
+ const NUXT_DEV_MEDIA_ROUTE = `// Development-only route: serves the mock media files by file name. Answers 404 in production.
125
+ import { createLedgerDevMediaRoute } from "@parrel/ledger/nuxt";
126
+
127
+ export default createLedgerDevMediaRoute();
128
+ `;
129
+ const SVELTEKIT_MEDIA_ROUTE = `import { createLedgerMediaProxy } from "@parrel/ledger/sveltekit";
130
+
131
+ export const { GET } = createLedgerMediaProxy();
132
+ `;
133
+ const NUXT_MEDIA_ROUTE = `import { createLedgerMediaProxy } from "@parrel/ledger/nuxt";
134
+
135
+ export default createLedgerMediaProxy();
136
+ `;
137
+ /** What the server of a SvelteKit or Nuxt app needs from `init`: the configuration is loaded where reads happen. */
138
+ const LEDGER_SERVER_ENTRY = {
139
+ name: "ledger",
140
+ label: "Ledger",
141
+ define: "defineParrelLedger",
142
+ exportName: "ledger",
143
+ notConfiguredCode: "SD00100001",
144
+ };
145
+ // ── install ──────────────────────────────────────────────────────────────────
146
+ /** The help of each command, printed by `parrel ledger <command> --help`. */
147
+ const LEDGER_COMMAND_HELP = {
148
+ install: {
149
+ summary: "install @parrel/ledger (no setup)",
150
+ usage: "",
151
+ notes: ["Installs the package with the package manager of the project. Run init next to set it up."],
152
+ },
153
+ init: {
154
+ summary: "config, sample schema, content and media, and routes",
155
+ usage: "[--framework <f>] [--slug <slug>] [-f] [-y]",
156
+ options: ["framework", "slug", "force", "yes"],
157
+ notes: [
158
+ "Writes the config, a sample map with content and media, and the routes of the framework. An existing file is skipped unless you pass -f.",
159
+ ],
160
+ },
161
+ generate: { summary: "generate the typed ledgerClient from parrel/ledger/maps/", usage: "" },
162
+ sync: {
163
+ summary: "publish the local maps to the Ledger service",
164
+ usage: "[--force|-f] [--yes|-y]",
165
+ options: ["force", "yes"],
166
+ notes: [
167
+ "sync first asks Ledger what it would delete or retype and shows it. In a terminal it asks you to confirm; without a terminal (CI) a sync that needs a confirmation stops with SD05000015 and sends nothing, unless you pass --force (or --yes).",
168
+ "The maps are checked against the limits first: a body of 10 MB, 200 maps, 500 fields per map (nested included) and 8 levels.",
169
+ "sync publishes the whole set: it removes every map that has no file in parrel/ledger/maps/, together with its resources and media files.",
170
+ "It reads the deployment token from PARREL_LEDGER_DEPLOYMENT_TOKEN. Without it, it asks for the token in a terminal. Without a terminal it stops with SD05000008 and sends nothing.",
171
+ "A deployment token is valid for 5 minutes and only the newest token of the service works. The same token serves the preview and the sync after it.",
172
+ "It uses the production API unless PARREL_API_ORIGIN is set, for example to http://localhost:18700.",
173
+ ],
174
+ },
175
+ upload: {
176
+ summary: "deprecated name of sync",
177
+ usage: "",
178
+ notes: ["Prints a reminder, then runs sync. Use npx parrel ledger sync."],
179
+ },
180
+ seed: {
181
+ summary: "fill parrel/ledger/ with the content of a .parrel backup",
182
+ usage: "<file.parrel> [--force|-f]",
183
+ options: ["force"],
184
+ notes: [
185
+ "Download the backup of your Ledger service in the Parrel portal. seed writes its maps to maps/, its content to mock.json and its media to the mock media folder (public/parrel/ledger/ when that folder exists).",
186
+ "When the folder already has maps, content or mock media, seed stops with SD05000029 and lists what it would replace. Pass --force to replace it. A backup holds no token, origin or slug, so your config is not changed.",
187
+ ],
188
+ },
189
+ "check-mock": { summary: "validate mock.json against your schemas", usage: "" },
190
+ clean: { summary: "remove generated client files", usage: "" },
191
+ };
192
+ export async function runLedgerInstall(flags) {
193
+ if (flags.help) {
194
+ return printCommandHelp("ledger", "install", LEDGER_COMMAND_HELP.install);
195
+ }
196
+ const root = projectRoot();
197
+ const pm = detectPackageManager(root);
198
+ log.title("ledger install");
199
+ log.step(`Installing ${style.bold("@parrel/ledger")} with ${style.bold(pm.name)} …`);
200
+ const code = await runCommand(pm.name, [...pm.addArgs, "@parrel/ledger"], root);
201
+ if (code !== 0) {
202
+ log.err("Install failed. Run it manually: " + style.dim(`${pm.name} ${pm.addArgs.join(" ")} @parrel/ledger`));
203
+ process.exitCode = 1;
204
+ return;
205
+ }
206
+ log.ok("@parrel/ledger installed.");
207
+ log.hint(`Next: run ${style.bold("npx parrel ledger init")} to set it up.`);
208
+ }
209
+ // ── init ─────────────────────────────────────────────────────────────────────
210
+ function ledgerConfigPath(framework) {
211
+ switch (framework) {
212
+ case "sveltekit":
213
+ return path.join("src", "lib", "ledger.ts");
214
+ case "angular":
215
+ return path.join("src", "app", "ledger.config.ts");
216
+ case "vue":
217
+ case "react":
218
+ return path.join("src", "ledger.ts");
219
+ default:
220
+ return path.join("lib", "ledger.ts");
221
+ }
222
+ }
223
+ /** React, Vue and Angular run only in the browser: no server, no files, so the mock content is imported. */
224
+ function isBrowserOnly(framework) {
225
+ return framework === "react" || framework === "vue" || framework === "angular";
226
+ }
227
+ /** Where a browser-only app finds the mock media files: `public/parrel/ledger/`, served from `/parrel/ledger/`. */
228
+ const BROWSER_MEDIA_DIR = path.join("public", "parrel", "ledger");
229
+ /** The line a developer adds to the entry file of a browser-only app, so the config runs before the first render. */
230
+ function entryImport(framework) {
231
+ return framework === "angular"
232
+ ? { file: "src/main.ts", line: 'import "./app/ledger.config";' }
233
+ : { file: framework === "react" ? "src/main.tsx" : "src/main.ts", line: 'import "./ledger";' };
234
+ }
235
+ function ledgerConfigContent(slug, framework, mockImport = "../parrel/ledger/mock.json") {
236
+ if (isBrowserOnly(framework)) {
237
+ const angular = framework === "angular";
238
+ return `import { defineParrelLedger } from "@parrel/ledger";
239
+ import mockData from "${mockImport}";${angular ? '\nimport { environment } from "../environments/environment";' : ""}
240
+
241
+ export const ledger = defineParrelLedger({
242
+ \tslug: "${slug}",
243
+ \t// A local backend for tests: ${angular ? "set parrelApiOrigin in environment.ts" : "set VITE_PARREL_API_ORIGIN in .env"}. Leave it empty to use the Parrel API.
244
+ \tapiOrigin: ${angular ? "environment.parrelApiOrigin" : "import.meta.env.VITE_PARREL_API_ORIGIN"},
245
+ \t// A browser cannot read parrel/ledger/mock.json, so the content is imported and passed in. In development
246
+ \t// this is what getContent() returns; in production the Parrel Ledger service is used.
247
+ \tmockData,
248
+ \t// The files of the mock media live in public/parrel/ledger/ (served as /parrel/ledger/hero.svg).
249
+ \tmockMediaPath: "/parrel/ledger",${angular ? '\n\tmode: environment.production ? "live" : "auto",' : ""}
250
+ });
251
+ `;
252
+ }
253
+ return `import { defineParrelLedger } from "@parrel/ledger";
254
+
255
+ export const ledger = defineParrelLedger({
256
+ \tslug: "${slug}",
257
+ \t// Same-origin media proxy (route scaffolded below) so every media type
258
+ \t// (pdf, svg, image, video) embeds without X-Frame-Options/CORS issues.
259
+ \tmediaProxyPath: "/api/cms-media",
260
+ });
261
+ `;
262
+ }
263
+ function ledgerMediaRoute(framework) {
264
+ switch (framework) {
265
+ case "next":
266
+ return {
267
+ dev: { file: path.join("app", "api", "dev-cms-media", "[...path]", "route.ts"), content: NEXT_DEV_MEDIA_ROUTE },
268
+ prod: { file: path.join("app", "api", "cms-media", "[...path]", "route.ts"), content: NEXT_PROD_MEDIA_ROUTE },
269
+ };
270
+ case "sveltekit":
271
+ return {
272
+ dev: {
273
+ file: path.join("src", "routes", "api", "dev-cms-media", "[...path]", "+server.ts"),
274
+ content: SVELTEKIT_DEV_MEDIA_ROUTE,
275
+ },
276
+ prod: {
277
+ file: path.join("src", "routes", "api", "cms-media", "[...path]", "+server.ts"),
278
+ content: SVELTEKIT_MEDIA_ROUTE,
279
+ },
280
+ };
281
+ case "nuxt":
282
+ return {
283
+ dev: {
284
+ file: path.join("server", "routes", "api", "dev-cms-media", "[...path].ts"),
285
+ content: NUXT_DEV_MEDIA_ROUTE,
286
+ },
287
+ prod: { file: path.join("server", "routes", "api", "cms-media", "[...path].ts"), content: NUXT_MEDIA_ROUTE },
288
+ };
289
+ default:
290
+ return {};
291
+ }
292
+ }
293
+ export async function runLedgerInit(flags) {
294
+ if (flags.help) {
295
+ return printCommandHelp("ledger", "init", LEDGER_COMMAND_HELP.init);
296
+ }
297
+ const root = projectRoot();
298
+ log.title("ledger init");
299
+ log.plain(style.dim(" Let's set up Parrel Ledger with some sample content.\n"));
300
+ const framework = await resolveFramework(flags, root);
301
+ log.ok(`Framework: ${style.bold(FRAMEWORK_LABELS[framework])}`);
302
+ const slug = await resolveSlug(flags, "Ledger");
303
+ log.ok(`Slug: ${style.bold(slug)}`);
304
+ // 1. Config with defineParrelLedger.
305
+ const configRel = ledgerConfigPath(framework);
306
+ const ledgerDir = resolveLedgerDir(root);
307
+ const mockPath = path.join(ledgerDir, "mock.json");
308
+ const mockImport = path
309
+ .relative(path.dirname(path.join(root, configRel)), mockPath)
310
+ .split(path.sep)
311
+ .join("/");
312
+ reportWrite(root, path.join(root, configRel), await writeFileSafe(path.join(root, configRel), ledgerConfigContent(slug, framework, mockImport), flags.force));
313
+ // 2. Content scaffolding with SAMPLE data (schema + mock + media). A browser-only app has no server to serve
314
+ // mediamock/, so its mock media goes to public/.
315
+ const browserOnly = isBrowserOnly(framework);
316
+ const mapsDir = path.join(ledgerDir, "maps");
317
+ const mediaDir = browserOnly ? path.join(root, BROWSER_MEDIA_DIR) : path.join(ledgerDir, "mediamock");
318
+ await mkdir(mediaDir, { recursive: true });
319
+ reportWrite(root, path.join(mapsDir, "homepage.json"), await writeFileSafe(path.join(mapsDir, "homepage.json"), SAMPLE_SCHEMA, flags.force));
320
+ reportWrite(root, mockPath, await writeFileSafe(mockPath, SAMPLE_MOCK, flags.force));
321
+ reportWrite(root, path.join(mediaDir, "hero.svg"), await writeFileSafe(path.join(mediaDir, "hero.svg"), SAMPLE_HERO_SVG, flags.force));
322
+ // 3. Framework media routes.
323
+ const routes = ledgerMediaRoute(framework);
324
+ if (routes.dev) {
325
+ reportWrite(root, path.join(root, routes.dev.file), await writeFileSafe(path.join(root, routes.dev.file), routes.dev.content, flags.force));
326
+ }
327
+ if (routes.prod) {
328
+ reportWrite(root, path.join(root, routes.prod.file), await writeFileSafe(path.join(root, routes.prod.file), routes.prod.content, flags.force));
329
+ }
330
+ // The generated Angular config reads the environment files and imports JSON.
331
+ let angularEnvironments = true;
332
+ if (framework === "angular") {
333
+ angularEnvironments = await prepareAngularEnvironments(root);
334
+ await enableResolveJsonModule(root);
335
+ }
336
+ // 4. The server entry: SvelteKit and Nuxt do not import the config on the server by themselves.
337
+ if (framework === "sveltekit") {
338
+ await writeSveltekitServerEntry(root, LEDGER_SERVER_ENTRY, flags.force);
339
+ }
340
+ else if (framework === "nuxt") {
341
+ await writeNuxtServerEntry(root, LEDGER_SERVER_ENTRY, "@parrel/ledger", flags.force);
342
+ }
343
+ // 5. Generate the typed client immediately (if the package is installed).
344
+ if (existsSync(path.join(root, "node_modules", "@parrel", "ledger"))) {
345
+ log.plain("");
346
+ log.step("Generating the typed ledgerClient from your schemas …");
347
+ await runGenerate();
348
+ }
349
+ // 6. Next steps.
350
+ log.plain("");
351
+ log.title("ledger ready ✨");
352
+ if (browserOnly) {
353
+ const entry = entryImport(framework);
354
+ log.plain(` ${style.bold("1.")} Import the config in your app entry, before the first render: add ${style.cyan(entry.line)} to ${style.cyan(entry.file)}.`);
355
+ log.plain(` ${style.bold("2.")} Your sample content lives in ${style.cyan(`${displayPath(root, ledgerDir)}/`)}: schemas in ${style.cyan("maps/")}, content in ${style.cyan("mock.json")} (the config imports it for development). The mock media is in ${style.cyan(`${displayPath(root, mediaDir)}/`)}.`);
356
+ log.plain(` ${style.bold("3.")} Use it: ${style.cyan('import { ledgerClient } from "@parrel/ledger/client"')} → ${style.cyan("await ledgerClient.homepage.getContent()")}.`);
357
+ log.plain(` ${style.bold("4.")} ${framework === "angular" ? (angularEnvironments ? "Set parrelApiOrigin in both environment files (an empty text uses the Parrel API; a local backend such as http://localhost:18700 for tests)." : ANGULAR_ENVIRONMENTS_STEP + " An empty parrelApiOrigin uses the Parrel API; a local backend such as http://localhost:18700 is for tests.") : "To test against a local backend, set VITE_PARREL_API_ORIGIN in .env, for example http://localhost:18700."} In production the app reads from the Parrel Ledger service for slug ${style.cyan(slug)}.`);
358
+ log.plain(` ${style.bold("5.")} After editing schemas, run ${style.bold("npx parrel ledger generate")}. Publish maps with ${style.bold("npx parrel ledger sync")}.`);
359
+ log.plain("");
360
+ return;
361
+ }
362
+ let step = 0;
363
+ const next = (text) => log.plain(` ${style.bold(`${++step}.`)} ${text}`);
364
+ next(`Your sample content lives in ${style.cyan(`${displayPath(root, ledgerDir)}/`)}: schemas in ${style.cyan("maps/")}, content in ${style.cyan("mock.json")}, media in ${style.cyan("mediamock/")}.`);
365
+ if (framework === "sveltekit" || framework === "nuxt") {
366
+ const specifier = framework === "sveltekit" ? await svelteKitLibImport(root, "ledger") : "";
367
+ next(serverEntryNextStep(framework, LEDGER_SERVER_ENTRY, specifier));
368
+ }
369
+ next(`Use it: ${style.cyan('import { ledgerClient } from "@parrel/ledger/client"')} → ${style.cyan("await ledgerClient.homepage.getContent()")}.`);
370
+ next(`Pages that write (an admin page) run in the browser and need their own ${style.cyan("defineParrelLedger")} call there, with ${style.cyan("apiOrigin")} from the public variable of your framework and ${style.cyan("mockData")} outside production. Import it in browser code only: see "Browser configuration for pages that write" in the README of @parrel/ledger.`);
371
+ next(`After editing schemas, run ${style.bold("npx parrel ledger generate")}. Publish maps with ${style.bold("npx parrel ledger sync")}.`);
372
+ next(`In production it reads from the Parrel Ledger service for slug ${style.cyan(slug)}, with no extra config.`);
373
+ log.plain("");
374
+ }
375
+ // ── generate ─────────────────────────────────────────────────────────────────
376
+ export async function runGenerate() {
377
+ const root = resolveProjectRoot();
378
+ log.step("Generating the typed ledgerClient declaration …");
379
+ const schemas = await loadAllSchemas(root);
380
+ if (schemas.length === 0) {
381
+ log.warn(`No schemas found in ${mapsDirLabel(root)}. Add a JSON map there, or run npx parrel ledger init.`);
382
+ return;
383
+ }
384
+ const schemaNames = schemas.map((s) => s.name);
385
+ const flatNameErrors = validateFlatNames(schemaNames);
386
+ if (flatNameErrors.length > 0) {
387
+ for (const error of flatNameErrors)
388
+ console.error(error);
389
+ process.exitCode = 1;
390
+ return;
391
+ }
392
+ const collisions = detectCollisions(schemaNames);
393
+ if (collisions.length > 0) {
394
+ for (const error of collisions)
395
+ console.error(error);
396
+ process.exitCode = 1;
397
+ return;
398
+ }
399
+ const mockPath = path.join(resolveLedgerDir(root), "mock.json");
400
+ let mockData = {};
401
+ if (existsSync(mockPath)) {
402
+ mockData = JSON.parse(await readFile(mockPath, "utf8"));
403
+ }
404
+ const schemaMap = new Map(schemas.map((s) => [s.name, s.schema]));
405
+ const augmentResult = augmentAllMockData(mockData, schemaMap);
406
+ if (augmentResult.modified) {
407
+ await writeFile(mockPath, `${JSON.stringify(mockData, null, 2)}\n`, "utf8");
408
+ log.hint(`Updated ${path.relative(root, mockPath)}`);
409
+ }
410
+ const packageDir = path.join(root, "node_modules", "@parrel", "ledger");
411
+ const distClientDir = path.join(packageDir, "dist", "client");
412
+ if (!existsSync(distClientDir)) {
413
+ log.warn(`@parrel/ledger is not installed, or not built, in ${path.relative(root, packageDir) || packageDir}, so there is no declaration to type. Install the package, then run npx parrel ledger generate again.`);
414
+ return;
415
+ }
416
+ // The client is one runtime for every project; only its declaration depends on the maps.
417
+ const declarationFile = path.join(distClientDir, "index.d.ts");
418
+ await writeFile(declarationFile, generateLedgerClientDeclaration(schemaMap), "utf8");
419
+ // Earlier versions also wrote unused helper files to node_modules/@parrel/ledger/client.
420
+ await removeLegacyGeneratedDir(root);
421
+ log.ok(`Generated ${schemas.length} resource(s) → ${path.relative(root, declarationFile)}`);
422
+ }
423
+ /** The folder that earlier versions of `generate` filled with helper files that nothing imports. */
424
+ function legacyGeneratedDir(root) {
425
+ return path.join(root, "node_modules", "@parrel", "ledger", "client");
426
+ }
427
+ /** Removes the folder of {@link legacyGeneratedDir} when `generate` wrote it (it holds the marker file). */
428
+ async function removeLegacyGeneratedDir(root) {
429
+ const dir = legacyGeneratedDir(root);
430
+ if (existsSync(path.join(dir, "__generated-do-not-edit.txt"))) {
431
+ await rm(dir, { recursive: true, force: true });
432
+ }
433
+ }
434
+ // ── clean ────────────────────────────────────────────────────────────────────
435
+ export async function runClean() {
436
+ const root = resolveProjectRoot();
437
+ const generatedDir = legacyGeneratedDir(root);
438
+ if (!existsSync(generatedDir)) {
439
+ log.hint(`No generated files at ${path.relative(root, generatedDir)}`);
440
+ return;
441
+ }
442
+ await rm(generatedDir, { recursive: true, force: true });
443
+ log.ok(`Cleaned ${path.relative(root, generatedDir)}`);
444
+ }
445
+ // ── sync (alias: upload) ──────────────────────────────────────────────────────
446
+ function isPlainObject(value) {
447
+ return value !== null && typeof value === "object" && !Array.isArray(value);
448
+ }
449
+ /** The environment variable that holds the Ledger deployment token for `parrel ledger sync`. */
450
+ export const LEDGER_DEPLOYMENT_TOKEN_ENV = "PARREL_LEDGER_DEPLOYMENT_TOKEN";
451
+ function missingDeploymentTokenError() {
452
+ return new ParrelError("SD05000008", `The command-line tool needs a Ledger deployment token, but none was given. Set the ${LEDGER_DEPLOYMENT_TOKEN_ENV} environment variable, or run the command in a terminal to paste the token.`);
453
+ }
454
+ /**
455
+ * Finds the deployment token for `sync`. It reads the `PARREL_LEDGER_DEPLOYMENT_TOKEN` environment variable first, so a job
456
+ * without a terminal (CI) can pass the token. Only in a terminal does it ask for the token. Without a terminal, or when
457
+ * the input closes before an answer, it throws `SD05000008` instead of waiting. The token is never printed.
458
+ */
459
+ export async function resolveDeploymentToken() {
460
+ const fromEnvironment = process.env[LEDGER_DEPLOYMENT_TOKEN_ENV]?.trim();
461
+ if (fromEnvironment) {
462
+ return fromEnvironment;
463
+ }
464
+ if (!input.isTTY) {
465
+ throw missingDeploymentTokenError();
466
+ }
467
+ const rl = createInterface({ input, output });
468
+ try {
469
+ const answer = await new Promise((resolve, reject) => {
470
+ rl.once("close", () => reject(missingDeploymentTokenError()));
471
+ rl.question("[parrel] Map deployment token: ").then(resolve, () => reject(missingDeploymentTokenError()));
472
+ });
473
+ const token = answer.trim();
474
+ if (!token) {
475
+ throw missingDeploymentTokenError();
476
+ }
477
+ return token;
478
+ }
479
+ finally {
480
+ rl.close();
481
+ }
482
+ }
483
+ const TOKEN_HINTS = {
484
+ LE04000021: "Create a deployment token in the Parrel portal and paste it when asked, or set PARREL_LEDGER_DEPLOYMENT_TOKEN.",
485
+ LE04000022: "A deployment token is valid for 5 minutes. Create a new one in the Parrel portal and run the sync again.",
486
+ LE04000023: "Copy the whole deployment token from the Parrel portal, without spaces.",
487
+ LE04000024: "This token belongs to another Ledger service. Check that the slug in defineParrelLedger is the one of the token.",
488
+ LE04000029: "A newer deployment token was made. Make a new token in the Parrel portal and run the sync again.",
489
+ };
490
+ /** The hints for the `409` answers of the sync: it was not confirmed, or the preview is too old or out of date. */
491
+ const SYNC_CONFLICT_HINTS = {
492
+ LE01000042: "Ledger refused the sync because it deletes or changes content and was not confirmed (MAP_SYNC_CONFIRMATION_REQUIRED). Run the sync again and confirm, or use --force.",
493
+ LE01000043: "The preview is older than 5 minutes or was already used (MAP_SYNC_PREVIEW_EXPIRED). Run the sync again. A deployment token is valid for 5 minutes too, so make a new one if yours is older.",
494
+ LE01000044: "The maps or the content of the service changed after the preview (MAP_SYNC_PREVIEW_STALE). Run the sync again and check the new list.",
495
+ };
496
+ /** Asks a yes or no question in a terminal. Only `y` and `yes` count as yes; a closed input is no. */
497
+ async function askYesNo(question) {
498
+ const rl = createInterface({ input, output });
499
+ try {
500
+ const answer = await new Promise((resolve) => {
501
+ rl.once("close", () => resolve(""));
502
+ rl.question(`[parrel] ${question} `).then(resolve, () => resolve(""));
503
+ });
504
+ return /^y(es)?$/i.test(answer.trim());
505
+ }
506
+ finally {
507
+ rl.close();
508
+ }
509
+ }
510
+ function printList(title, lines) {
511
+ if (lines.length === 0)
512
+ return;
513
+ log.plain(` ${style.bold(title)}`);
514
+ for (const line of lines)
515
+ log.plain(` - ${line}`);
516
+ }
517
+ /** Prints what the preview says the sync would do: added, updated and unchanged maps, then everything that is lost. */
518
+ function printSyncPreview(preview) {
519
+ log.title("Sync preview");
520
+ log.hint(`add ${preview.mapsAdded.length} · update ${preview.mapsUpdated.length} · delete ${preview.mapsDeleted.length} · unchanged ${preview.mapsUnchanged.length}`);
521
+ printList("Maps that the sync deletes (with their resources and media files):", preview.mapsDeleted.map((m) => `${m.name}: ${m.resourceCount} resource(s), ${m.mediaCount} media file(s)`));
522
+ printList("Fields that the sync removes (their values are lost):", preview.fieldsRemoved.map((f) => `${f.map}.${f.field}: in ${f.resourceCount} resource(s)`));
523
+ printList("Fields that the sync gives another type:", preview.fieldsRetyped.map((f) => `${f.map}.${f.field}: ${f.fromType} to ${f.toType}, in ${f.resourceCount} resource(s)`));
524
+ if (preview.mediaDeleted > 0) {
525
+ const more = preview.mediaDeleted - preview.mediaDeletedNames.length;
526
+ printList(`Media files that the sync deletes (${preview.mediaDeleted}):`, [
527
+ ...preview.mediaDeletedNames,
528
+ ...(more > 0 ? [`and ${more} more`] : []),
529
+ ]);
530
+ }
531
+ }
532
+ function confirmationPrompt(preview) {
533
+ const fields = preview.fieldsRemoved.length + preview.fieldsRetyped.length;
534
+ return `This sync deletes ${preview.mediaDeleted} media files and removes or retypes ${fields} fields. Continue? (y/N)`;
535
+ }
536
+ function notConfirmedError() {
537
+ return new ParrelError("SD05000015", "The sync was not confirmed, so nothing was sent. Run it again and confirm, or use --force in CI.");
538
+ }
539
+ /** The hint that the command prints below an error of Ledger, when it has one. */
540
+ function syncErrorHint(error) {
541
+ return isParrelError(error) ? (TOKEN_HINTS[error.code] ?? SYNC_CONFLICT_HINTS[error.code]) : undefined;
542
+ }
543
+ /**
544
+ * `parrel ledger sync [--force|-f] [--yes|-y]`. Checks the local limits, asks Ledger for a preview of what the sync
545
+ * deletes or retypes, shows it, and applies the sync after a confirmation. A terminal asks once; without a terminal a
546
+ * sync that needs a confirmation stops with `SD05000015` and sends nothing, unless `--force` (or `--yes`) is given.
547
+ * A preview that fails stops the command with the error of Ledger, and nothing is synced (LED-4).
548
+ */
549
+ export async function runSync(flags) {
550
+ if (flags.help) {
551
+ return printCommandHelp("ledger", "sync", LEDGER_COMMAND_HELP.sync);
552
+ }
553
+ // Refuse a bad PARREL_API_ORIGIN before the command asks for a deployment token.
554
+ const apiOrigin = resolveParrelApiOrigin();
555
+ ledgerBaseUrl();
556
+ const root = resolveProjectRoot();
557
+ const schemas = await loadAllSchemas(root);
558
+ if (schemas.length === 0) {
559
+ log.err(`No schemas found in ${mapsDirLabel(root)}. Add a JSON map there before you sync.`);
560
+ process.exitCode = 1;
561
+ return;
562
+ }
563
+ const config = await resolveLedgerConfig(root);
564
+ const slug = (config.slug ?? "").trim();
565
+ if (!slug) {
566
+ log.err("Could not find the Ledger slug in a defineParrelLedger({ slug }) call in this project.");
567
+ log.hint('Add defineParrelLedger({ slug: "your-service-slug" }) to your Ledger config file, or run npx parrel ledger init.');
568
+ process.exitCode = 1;
569
+ return;
570
+ }
571
+ const mapPayload = {};
572
+ for (const schema of schemas) {
573
+ let parsed;
574
+ try {
575
+ parsed = JSON.parse(await readFile(schema.filePath, "utf8"));
576
+ }
577
+ catch (error) {
578
+ log.err(`Invalid JSON map: ${schema.name}: ${String(error)}`);
579
+ process.exitCode = 1;
580
+ return;
581
+ }
582
+ if (!isPlainObject(parsed)) {
583
+ log.err(`Map '${schema.name}' must be a JSON object.`);
584
+ process.exitCode = 1;
585
+ return;
586
+ }
587
+ mapPayload[schema.name] = parsed;
588
+ }
589
+ // The local limits come before the token prompt and before any request.
590
+ assertMapSetWithinLimits(mapPayload);
591
+ const token = await resolveDeploymentToken();
592
+ const options = { apiOrigin };
593
+ const forced = flags.force || flags.yes;
594
+ const hasTerminal = Boolean(input.isTTY);
595
+ try {
596
+ const preview = await previewMapSync(slug, token, mapPayload, options);
597
+ printSyncPreview(preview);
598
+ let confirmation;
599
+ if (forced) {
600
+ confirmation = { confirm: true };
601
+ }
602
+ else if (!preview.requiresConfirmation) {
603
+ confirmation = { previewId: preview.previewId };
604
+ }
605
+ else if (hasTerminal && (await askYesNo(confirmationPrompt(preview)))) {
606
+ confirmation = { previewId: preview.previewId };
607
+ }
608
+ else {
609
+ throw notConfirmedError();
610
+ }
611
+ const report = await applyMapSync(slug, token, mapPayload, confirmation, options);
612
+ printSyncReport(slug, Object.keys(mapPayload).length, report);
613
+ }
614
+ catch (error) {
615
+ if (isParrelError(error) && /^SD050000(1[0-3]|15)$/.test(error.code)) {
616
+ throw error;
617
+ }
618
+ reportCliError(error);
619
+ const hint = syncErrorHint(error);
620
+ if (hint)
621
+ log.hint(hint);
622
+ }
623
+ }
624
+ function printSyncReport(slug, localMapCount, report) {
625
+ const arr = (k) => (Array.isArray(report[k]) ? report[k] : []);
626
+ log.ok(`Synced ${localMapCount} map(s) to slug ${style.cyan(String(report.slug ?? slug))}`);
627
+ log.hint(`added ${arr("mapsAdded").length} · updated ${arr("mapsUpdated").length} · deleted ${arr("mapsDeleted").length} · unchanged ${arr("mapsUnchanged").length}`);
628
+ if (report.message)
629
+ log.hint(String(report.message));
630
+ const errors = arr("errors");
631
+ if (errors.length > 0) {
632
+ log.err(`Sync completed with ${errors.length} error(s):`);
633
+ for (const e of errors)
634
+ console.error(` - ${String(e)}`);
635
+ process.exitCode = 1;
636
+ }
637
+ }
638
+ async function resolveLedgerConfig(root) {
639
+ for (const filePath of await collectCandidateConfigFiles(root)) {
640
+ let raw = "";
641
+ try {
642
+ raw = await readFile(filePath, "utf8");
643
+ }
644
+ catch {
645
+ continue;
646
+ }
647
+ if (!raw.includes("defineParrelLedger") && !raw.includes("defineParrelCms"))
648
+ continue;
649
+ const match = /defineParrel(?:Ledger|Cms)\s*\(\s*\{([\s\S]*?)\}\s*\)/m.exec(raw);
650
+ if (!match)
651
+ continue;
652
+ const slugMatch = /slug\s*:\s*["'`]([^"'`]+)["'`]/.exec(match[1]);
653
+ return { slug: slugMatch?.[1]?.trim() };
654
+ }
655
+ return {};
656
+ }
657
+ async function collectCandidateConfigFiles(root) {
658
+ const allowed = new Set([".ts", ".tsx", ".js", ".mjs", ".cjs"]);
659
+ const ignore = new Set(["node_modules", ".next", ".git", "dist", "build", "target"]);
660
+ const queue = [root];
661
+ const files = [];
662
+ while (queue.length > 0 && files.length < 4000) {
663
+ const current = queue.pop();
664
+ if (!current)
665
+ continue;
666
+ let entries;
667
+ try {
668
+ entries = await readdir(current, { withFileTypes: true });
669
+ }
670
+ catch {
671
+ continue;
672
+ }
673
+ for (const entry of entries) {
674
+ const fullPath = path.join(current, entry.name);
675
+ if (entry.isDirectory()) {
676
+ if (!ignore.has(entry.name))
677
+ queue.push(fullPath);
678
+ }
679
+ else if (entry.isFile() && allowed.has(path.extname(entry.name))) {
680
+ files.push(fullPath);
681
+ }
682
+ }
683
+ }
684
+ return files;
685
+ }
686
+ // ── seed ─────────────────────────────────────────────────────────────────────
687
+ /** The last segment of a media URL or file, decoded: `/read/<slug>/media/hero%20one.png` gives `hero one.png`. */
688
+ function mediaFileName(reference) {
689
+ const last = (reference.split(/[?#]/)[0] ?? "").split(/[\\/]/).filter(Boolean).pop() ?? "";
690
+ try {
691
+ return decodeURIComponent(last);
692
+ }
693
+ catch {
694
+ return last;
695
+ }
696
+ }
697
+ /**
698
+ * Turns the stored content of a resource into its `mock.json` form: every media object becomes `{ file, alt }`, with
699
+ * the file name taken from its `url` (or `file`). Calls `onMedia` with each file name.
700
+ */
701
+ function contentToMock(value, onMedia) {
702
+ if (isMediaObject(value)) {
703
+ const reference = typeof value.url === "string" ? value.url : typeof value.file === "string" ? value.file : "";
704
+ const file = mediaFileName(reference);
705
+ onMedia(file);
706
+ return { file, alt: value.alt };
707
+ }
708
+ if (Array.isArray(value)) {
709
+ return value.map((item) => contentToMock(item, onMedia));
710
+ }
711
+ if (value !== null && typeof value === "object") {
712
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, contentToMock(item, onMedia)]));
713
+ }
714
+ return value;
715
+ }
716
+ /** The files of `dir` (not those in its subfolders), or none when it does not exist. */
717
+ async function filesIn(dir, filter = () => true) {
718
+ if (!existsSync(dir)) {
719
+ return [];
720
+ }
721
+ const entries = await readdir(dir, { withFileTypes: true });
722
+ return entries
723
+ .filter((entry) => entry.isFile() && filter(entry.name))
724
+ .map((entry) => path.join(dir, entry.name))
725
+ .sort();
726
+ }
727
+ /** True when `mock.json` exists and holds more than an empty object. */
728
+ async function hasMockContent(mockPath) {
729
+ if (!existsSync(mockPath)) {
730
+ return false;
731
+ }
732
+ const text = (await readFile(mockPath, "utf8")).trim();
733
+ if (text === "") {
734
+ return false;
735
+ }
736
+ try {
737
+ const value = JSON.parse(text);
738
+ return !(value !== null && typeof value === "object" && Object.keys(value).length === 0);
739
+ }
740
+ catch {
741
+ return true;
742
+ }
743
+ }
744
+ /**
745
+ * `parrel ledger seed <file.parrel> [--force]`: fills `parrel/ledger/` with the maps, content and media of a `.parrel`
746
+ * backup of a Ledger service, so development reads the same content as the service. The backup is checked as a whole
747
+ * before anything is written, and existing maps, mock content and mock media are replaced only with `--force`. The
748
+ * second argument changes the limits of the reader, for tests.
749
+ *
750
+ * @example
751
+ * ```ts
752
+ * await runSeed({ force: false, yes: false, positionals: ["seed", "Ab3xYz9_kQ1w-20261007.parrel"] });
753
+ * ```
754
+ */
755
+ export async function runSeed(flags, limits = DEFAULT_BUNDLE_LIMITS) {
756
+ if (flags.help) {
757
+ return printCommandHelp("ledger", "seed", LEDGER_COMMAND_HELP.seed);
758
+ }
759
+ const [, given] = flags.positionals;
760
+ if (given === undefined) {
761
+ throw new ParrelError("SD05000024", "No backup file was given. Download the backup of your Ledger service in the Parrel portal and pass its path: npx parrel ledger seed <file.parrel>.");
762
+ }
763
+ const root = process.cwd();
764
+ const bundle = await openBundle(path.resolve(root, given), limits);
765
+ try {
766
+ const ledgerDir = resolveLedgerDir(root);
767
+ const mediaDir = mockMediaDir(root);
768
+ const mapsDir = path.join(ledgerDir, "maps");
769
+ const mockPath = path.join(ledgerDir, "mock.json");
770
+ const oldMaps = await filesIn(mapsDir, (name) => name.endsWith(".json"));
771
+ const oldMedia = await filesIn(mediaDir);
772
+ const oldMock = (await hasMockContent(mockPath)) ? [mockPath] : [];
773
+ const replaced = [...oldMaps, ...oldMock, ...oldMedia];
774
+ if (replaced.length > 0 && !flags.force) {
775
+ log.warn(`seed would replace ${replaced.length} file(s):`);
776
+ for (const target of replaced) {
777
+ log.hint(displayPath(root, target));
778
+ }
779
+ throw new ParrelError("SD05000029", `The folder ${displayPath(root, ledgerDir)} already has maps or content. Run again with --force to replace it.`);
780
+ }
781
+ for (const target of [...oldMaps, ...oldMedia]) {
782
+ await rm(target, { force: true });
783
+ }
784
+ await mkdir(mapsDir, { recursive: true });
785
+ await mkdir(mediaDir, { recursive: true });
786
+ for (const entry of bundle.maps) {
787
+ await writeFile(path.join(mapsDir, `${entry.name}.json`), await readEntry(bundle, entry));
788
+ }
789
+ const mediaNames = new Set(bundle.media.map((entry) => entry.name));
790
+ const mock = {};
791
+ for (const entry of bundle.content) {
792
+ const value = JSON.parse((await readEntry(bundle, entry)).toString("utf8"));
793
+ mock[entry.name] = contentToMock(value, (mediaFile) => {
794
+ if (!mediaNames.has(mediaFile)) {
795
+ log.warn(`The resource "${entry.name}" refers to the media file "${mediaFile}", which is not in the bundle. It was kept as it is.`);
796
+ }
797
+ });
798
+ }
799
+ await writeFile(mockPath, `${JSON.stringify(mock, null, 2)}\n`, "utf8");
800
+ for (const entry of bundle.media) {
801
+ await extractEntry(bundle, entry, path.join(mediaDir, entry.name));
802
+ }
803
+ log.ok(`Seeded ${displayPath(root, ledgerDir)} from ${given.replaceAll("\\", "/")}: ${bundle.maps.length} maps, ${bundle.content.length} resources, ${bundle.media.length} media files.`);
804
+ if (bundle.extrasSkipped > 0) {
805
+ log.hint(`Skipped ${bundle.extrasSkipped} Extras file(s) (logs, activity, statistics and audit entries): they are not content.`);
806
+ }
807
+ await checkMock(root, mediaDir);
808
+ log.plain(`Next: run ${style.bold("npx parrel ledger generate")} to update the typed client.`);
809
+ }
810
+ finally {
811
+ await bundle.close();
812
+ }
813
+ }
814
+ // ── check-mock ────────────────────────────────────────────────────────────────
815
+ export async function runCheckMock() {
816
+ const root = resolveProjectRoot();
817
+ return checkMock(root, mockMediaDir(root));
818
+ }
819
+ /**
820
+ * The folder of the mock media: `public/parrel/ledger/` when it exists (where `init` puts the media of a browser-only app),
821
+ * else `parrel/ledger/mediamock/`. `check-mock` and `seed` use the same folder.
822
+ */
823
+ function mockMediaDir(root) {
824
+ const browserMediaDir = path.join(root, BROWSER_MEDIA_DIR);
825
+ return existsSync(browserMediaDir) ? browserMediaDir : path.join(resolveLedgerDir(root), "mediamock");
826
+ }
827
+ /** The checks of `check-mock` on the project in `root`, with the mock media in `mediaDir`. */
828
+ async function checkMock(root, mediaDir) {
829
+ const ledgerDir = resolveLedgerDir(root);
830
+ const mockPath = path.join(ledgerDir, "mock.json");
831
+ if (!existsSync(mockPath)) {
832
+ log.err(`mock.json not found at ${displayPath(root, mockPath)}. Run npx parrel ledger init to create it.`);
833
+ process.exitCode = 1;
834
+ return;
835
+ }
836
+ let mockData;
837
+ try {
838
+ mockData = JSON.parse(await readFile(mockPath, "utf8"));
839
+ }
840
+ catch (error) {
841
+ log.err(`Invalid JSON in mock.json: ${String(error)}`);
842
+ process.exitCode = 1;
843
+ return;
844
+ }
845
+ if (typeof mockData !== "object" || mockData === null || Array.isArray(mockData)) {
846
+ log.err("mock.json must be a flat object: {resourceName: {...}, ...}");
847
+ process.exitCode = 1;
848
+ return;
849
+ }
850
+ const schemas = await loadAllSchemas(root);
851
+ if (schemas.length === 0) {
852
+ log.hint("check-mock: No schemas found to validate against");
853
+ return;
854
+ }
855
+ const schemaMap = new Map(schemas.map((s) => [s.name, s.schema]));
856
+ const errors = validateAllResources(mockData, schemaMap);
857
+ errors.push(...(await validateMediaFiles(mockData, mediaDir, schemaMap, `${displayPath(root, mediaDir)}/`)));
858
+ if (errors.length > 0) {
859
+ log.err(`check-mock failed with ${errors.length} error(s):`);
860
+ for (const error of errors) {
861
+ console.error(` [${error.severity === "error" ? "ERROR" : "WARN"}] ${error.path}: ${error.message}`);
862
+ }
863
+ process.exitCode = 1;
864
+ return;
865
+ }
866
+ log.ok(`check-mock OK: ${schemas.length} resource(s) validated`);
867
+ }
868
+ // ── help ─────────────────────────────────────────────────────────────────────
869
+ export function ledgerHelp() {
870
+ log.title("ledger: structured content and media");
871
+ log.plain(`
872
+ ${style.bold("Usage")}
873
+ npx parrel ledger <command> [options]
874
+
875
+ ${style.bold("Commands")}
876
+ ${style.cyan("install")} Install @parrel/ledger (no setup)
877
+ ${style.cyan("init")} Set up Ledger: config, sample schema/content/media, routes
878
+ ${style.cyan("generate")} Generate the typed ledgerClient from parrel/ledger/maps/
879
+ ${style.cyan("sync")} Publish local maps to the Ledger service (needs a deployment token)
880
+ ${style.cyan("upload")} Deprecated name of sync: prints a reminder, then runs sync
881
+ ${style.cyan("seed")} Fill parrel/ledger/ with the content of a .parrel backup
882
+ ${style.cyan("check-mock")} Validate mock.json against your schemas
883
+ ${style.cyan("clean")} Remove generated client files
884
+ ${style.cyan("help")} ${style.dim("(or ?)")} Show this help
885
+
886
+ ${style.bold("Options")}
887
+ --framework <f> next | nuxt | sveltekit | angular | vue | react (init)
888
+ --slug <slug> Service slug, skips the prompt (init)
889
+ -f, --force Overwrite existing files (init, seed); confirm a sync that deletes or retypes (sync)
890
+ -y, --yes Accept all defaults, non-interactive (init); same as --force (sync)
891
+ -h, --help Show this help
892
+
893
+ ${style.bold("Notes")}
894
+ ${style.dim("sync shows what it would delete or retype and asks to confirm. Without a terminal it needs --force or --yes then.")}
895
+ ${style.dim("sync checks the limits (10 MB, 200 maps, 500 fields per map, 8 levels) before it sends anything.")}
896
+ ${style.dim("sync publishes the whole set: it removes every map that has no file in parrel/ledger/maps/,")}
897
+ ${style.dim("together with its resources and media files.")}
898
+ ${style.dim("sync reads the deployment token from PARREL_LEDGER_DEPLOYMENT_TOKEN. Without it, it asks for the token")}
899
+ ${style.dim("in a terminal. Without a terminal (a CI job) it stops with SD05000008 and sends nothing.")}
900
+ ${style.dim("A deployment token is valid for 5 minutes and only the newest token works. The same token serves the")}
901
+ ${style.dim("preview and the sync after it.")}
902
+ ${style.dim("sync uses the production API unless PARREL_API_ORIGIN is set, for example to http://localhost:18700.")}
903
+ ${style.dim("seed replaces the maps, mock.json and the mock media only with --force. It never changes your config.")}
904
+ ${style.dim("parrel cms <command> still works as an alias of parrel ledger <command>.")}
905
+ ${style.dim("Projects with a parrel/cms/ folder keep using it until they move it to parrel/ledger/.")}
906
+
907
+ ${style.bold("Examples")}
908
+ npx parrel ledger init
909
+ npx parrel ledger generate
910
+ npx parrel ledger sync
911
+ npx parrel ledger seed Ab3xYz9_kQ1w-20261007.parrel
912
+ `);
913
+ }
914
+ export async function runLedgerCommands(argv, flags) {
915
+ const [command] = argv;
916
+ const commandHelp = command !== undefined && Object.prototype.hasOwnProperty.call(LEDGER_COMMAND_HELP, command)
917
+ ? LEDGER_COMMAND_HELP[command]
918
+ : undefined;
919
+ if (flags.help && commandHelp) {
920
+ return printCommandHelp("ledger", command, commandHelp);
921
+ }
922
+ switch (command) {
923
+ case "install":
924
+ return runLedgerInstall(flags);
925
+ case "init":
926
+ return runLedgerInit(flags);
927
+ case "generate":
928
+ return runGenerate();
929
+ case "upload":
930
+ log.hint(`"upload" is now "sync". Run ${style.bold("npx parrel ledger sync")} next time.`);
931
+ return runSync(flags);
932
+ case "sync":
933
+ return runSync(flags);
934
+ case "seed":
935
+ return runSeed(flags);
936
+ case "check-mock":
937
+ return runCheckMock();
938
+ case "clean":
939
+ return runClean();
940
+ case "help":
941
+ case "?":
942
+ case "--help":
943
+ case "-h":
944
+ case undefined:
945
+ return ledgerHelp();
946
+ default:
947
+ log.err(`Unknown command: ledger ${command}`);
948
+ ledgerHelp();
949
+ process.exitCode = 1;
950
+ }
951
+ }
952
+ // ── deprecated names (kept until the next major version) ─────────────────────
953
+ /**
954
+ * Runs a `parrel cms …` command. `cms` is the old name of the `ledger` scope.
955
+ *
956
+ * @deprecated Use {@link runLedgerCommands}. `parrel cms <command>` keeps working until the next major version.
957
+ */
958
+ export async function runCmsCommands(argv, flags) {
959
+ log.hint(`"parrel cms" is now "parrel ledger". Run ${style.bold(`npx parrel ledger ${argv.join(" ")}`.trim())} next time.`);
960
+ return runLedgerCommands(argv, flags);
961
+ }
962
+ /** @deprecated Use {@link runLedgerInstall}. */
963
+ export const runCmsInstall = runLedgerInstall;
964
+ /** @deprecated Use {@link runLedgerInit}. */
965
+ export const runCmsInit = runLedgerInit;
966
+ /** @deprecated Use {@link ledgerHelp}. */
967
+ export const cmsHelp = ledgerHelp;
968
+ //# sourceMappingURL=commands.js.map