znode-plugin 0.0.0-stage → 0.1.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.
@@ -0,0 +1,680 @@
1
+ #!/usr/bin/env node
2
+ // znode-plugin: build, pack and install Znode runtime packages (themes, plugins, widgets, content).
3
+ //
4
+ // znode build <packageDir|manifest.json> build into <packageDir>/dist
5
+ // znode pack <packageDir|manifest.json> build, then zip it as
6
+ // <packageDir>/releases/<name>-<version>.zpkg.zip
7
+ // znode install <zip|packageDir> [storeDir] validate and install into the store's plugin
8
+ // directory (default: RUNTIME_PLUGINS_DIR);
9
+ // the registry entry keeps its settings and stores
10
+ // znode create <theme|plugin|widget|content> <name> [dir]
11
+ // a starter package that builds as it is
12
+ // (default dir ./<name>)
13
+ // znode check <packageDir> marketplace review: metadata, permissions against
14
+ // the code, settings, size, server-render format
15
+ // znode deploy <packageDir> [storeDir] pack, then install into the store's plugin directory
16
+ // znode dev <packageDir> [storeDir] deploy, then again on every change under src/ or to the manifest
17
+ // znode link-store <storeRepoDir> [dir] the store's real types: writes tsconfig.store.json (see README)
18
+ //
19
+ // A package is a folder with znode-package.json (README.md shows a whole project, as create-znode-plugin makes it):
20
+ // {
21
+ // "name": "artifi", "version": "1.0.0", "kind": "plugin" | "theme" | "widget" | "content", "apiVersion": 1,
22
+ // "label": "...", "publisher": "...", "description": "...", "parent": "<theme>", (parent: themes only)
23
+ // "build": { "server": "src/server.ts", "browser": "src/browser.tsx" }, (TypeScript entry points)
24
+ // "styles": ["src/styles/*.css"], "assets": ["src/assets/fonts/*.woff2"], "messages": "src/i18n/labels.json",
25
+ // "pages": { "/": "src/pages/home.json" }, "widgets": ["HeroBanner"],
26
+ // code imports Next.js as an app does: next/image, next/link, next/navigation, next/font/google, react
27
+ // (next-imports.mjs: the store's own modules at runtime; Google fonts downloaded into the package when it builds)
28
+ // "overrides": { "/api/place-order": "place-order" }, (store BFF routes it takes over, by one of its routes)
29
+ // "serverPages": ["/my-page"], (whole pages at new URLs, rendered by its server part's serverPages)
30
+ // "dedupeStyles": true, (styles: drop the rules the store already has; STORE_URL = a page of a running store)
31
+ // "settingsSchema": { "websiteId": { "type": "string", "required": true, "browser": true, "label": "..." },
32
+ // "banner": { "type": "string", "browser": true, "attribute": "StoreBannerText" } },
33
+ // (attribute: the value comes from a Znode global attribute, "Code" for the store's, or
34
+ // { "code": "...", "levels": ["store", "account", "user"] }; the most specific level wins)
35
+ // marketplace: "license", "keywords", "homepage", "compatibility": { "webstore": ">=10.0.0" },
36
+ // "permissions": ["routes", "cartHooks", "overrides", "znodeApi", "externalNetwork", "uploads"] (what it does beyond UI;
37
+ // "uploads": its routes take files, multipart/form-data up to RUNTIME_PLUGIN_UPLOAD_BYTES)
38
+ // "sandbox": true (its server part runs in a separate, permission-limited Node process: routes and overrides only)
39
+ // }
40
+ import fs from "node:fs";
41
+ import path from "node:path";
42
+ import { execFileSync, spawnSync } from "node:child_process";
43
+ import { createRequire } from "node:module";
44
+ import { fileURLToPath, pathToFileURL } from "node:url";
45
+ import vm from "node:vm";
46
+ import { TEMPLATES } from "./templates.mjs";
47
+
48
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
49
+ const MANIFEST = "znode-package.json";
50
+ // the build tools (TypeScript, rollup, adm-zip, postcss): this package's own dependencies, wherever npm put them
51
+ // (ZNODE_TOOLS: a node_modules folder to use instead)
52
+ const require = process.env.ZNODE_TOOLS ? createRequire(path.join(process.env.ZNODE_TOOLS, "noop.js")) : createRequire(import.meta.url);
53
+ // a dependency's folder (its package.json's), found from what it resolves to
54
+ function packageDir(name) {
55
+ for (let dir = path.dirname(require.resolve(name)); dir !== path.dirname(dir); dir = path.dirname(dir)) {
56
+ const file = path.join(dir, "package.json");
57
+ if (fs.existsSync(file) && JSON.parse(fs.readFileSync(file, "utf8")).name === name) return dir;
58
+ }
59
+ throw new Error(`znode-plugin: ${name} is not installed`);
60
+ }
61
+ const TSC = () => path.join(packageDir("typescript"), "bin", "tsc");
62
+ const ROLLUP = () => path.join(packageDir("rollup"), "dist", "bin", "rollup");
63
+ const AdmZip = require("adm-zip");
64
+
65
+ const API_VERSION = 1;
66
+ const KINDS = ["theme", "plugin", "widget", "content"];
67
+ const NAME = /^[a-z0-9][a-z0-9-]{1,48}$/;
68
+ const VERSION = /^\d+\.\d+\.\d+(-[0-9a-z.-]+)?$/i;
69
+ const SERVED = new Set([".mjs", ".map", ".css", ".woff2", ".woff", ".ttf", ".otf", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".json"]);
70
+ const MAX_BYTES = 10 * 1024 * 1024;
71
+ const SETTING_TYPES = ["string", "number", "boolean", "list", "json", "object", "array"];
72
+ const ATTRIBUTE_LEVELS = ["store", "account", "user"];
73
+ const ATTRIBUTE_CODE = /^[A-Za-z][A-Za-z0-9_]{1,99}$/;
74
+ const PERMISSIONS = ["routes", "cartHooks", "overrides", "znodeApi", "externalNetwork", "uploads"];
75
+
76
+ const fail = (message) => {
77
+ console.error(`znode-package: ${message}`);
78
+ process.exit(1);
79
+ };
80
+ const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
81
+ const glob = (dir, pattern) => {
82
+ const folder = path.join(dir, path.dirname(pattern));
83
+ const re = new RegExp(
84
+ `^${path
85
+ .basename(pattern)
86
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
87
+ .replace(/\*/g, ".*")}$`
88
+ );
89
+ return fs.existsSync(folder)
90
+ ? fs
91
+ .readdirSync(folder)
92
+ .filter((name) => re.test(name))
93
+ .map((name) => path.join(folder, name))
94
+ : [];
95
+ };
96
+
97
+ function validateManifest(manifest, where) {
98
+ if (!NAME.test(manifest.name || "")) fail(`${where}: name must be lowercase letters, digits and dashes`);
99
+ if (!VERSION.test(manifest.version || "")) fail(`${where}: version must be semver (1.2.3)`);
100
+ if (!KINDS.includes(manifest.kind)) fail(`${where}: kind must be one of ${KINDS.join(", ")}`);
101
+ if (manifest.apiVersion !== API_VERSION) fail(`${where}: apiVersion ${manifest.apiVersion} isn't supported (this store runs ${API_VERSION})`);
102
+ if (manifest.parent && manifest.kind !== "theme") fail(`${where}: only a theme has a parent`);
103
+ // whole pages its server part renders (IRuntimePlugin.serverPages), at new lowercase URLs the store doesn't use
104
+ if (manifest.serverPages !== undefined) {
105
+ if (!Array.isArray(manifest.serverPages)) fail(`${where}: serverPages must be a list of paths ("/my-page")`);
106
+ // the source manifest names the entry (build.server), the built one the file (files.server)
107
+ if (manifest.serverPages.length && !manifest.build?.server && !manifest.files?.server) fail(`${where}: serverPages need a server part (build.server)`);
108
+ for (const page of manifest.serverPages) {
109
+ if (!/^\/[a-z0-9][a-z0-9-]*(\/[a-z0-9][a-z0-9-]*)*$/.test(String(page))) fail(`${where}: serverPages "${page}" must be a lowercase path like /my-page`);
110
+ if (/^\/(api|runtime-page|_next|login|signup|account|cart|checkout|search|product|category|404|error|maintenance)(\/|$)/.test(page)) fail(`${where}: serverPages "${page}" is a store route`);
111
+ }
112
+ }
113
+ // store BFF routes the package takes over: "/api/<path>" -> one of its own routes
114
+ for (const [route, target] of Object.entries(manifest.overrides || {})) {
115
+ if (!/^\/api\/[A-Za-z0-9/_-]+$/.test(route) || /^\/api\/extensions(\/|$)/.test(route)) fail(`${where}: override "${route}" must be a store route under /api/`);
116
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(String(target))) fail(`${where}: override "${route}" must name one of the package's routes`);
117
+ }
118
+ for (const [key, field] of Object.entries(manifest.settingsSchema || {})) {
119
+ if (field?.type !== undefined && !SETTING_TYPES.includes(field.type)) fail(`${where}: setting "${key}" has type "${field.type}" (one of ${SETTING_TYPES.join(", ")})`);
120
+ const attribute = field?.attribute;
121
+ if (attribute === undefined) continue;
122
+ const code = typeof attribute === "string" ? attribute : attribute?.code;
123
+ if (!ATTRIBUTE_CODE.test(String(code || ""))) fail(`${where}: setting "${key}" names attribute "${code}" (letters, digits and _, as Znode attribute codes)`);
124
+ const levels = typeof attribute === "string" ? ["store"] : attribute.levels || ["store"];
125
+ if (!Array.isArray(levels) || !levels.length || levels.some((level) => !ATTRIBUTE_LEVELS.includes(level))) {
126
+ fail(`${where}: setting "${key}" attribute levels must be some of ${ATTRIBUTE_LEVELS.join(", ")}`);
127
+ }
128
+ }
129
+ if (manifest.sandbox !== undefined && typeof manifest.sandbox !== "boolean") fail(`${where}: sandbox must be true or false`);
130
+ if (manifest.permissions !== undefined && (!Array.isArray(manifest.permissions) || manifest.permissions.some((item) => !PERMISSIONS.includes(item)))) {
131
+ fail(`${where}: permissions must be some of ${PERMISSIONS.join(", ")}`);
132
+ }
133
+ }
134
+
135
+ // ---- build: TypeScript entry points -> one ES module each (tsc + rollup), plus styles, assets, labels, pages ----
136
+ // a package folder (its znode-package.json) or one of several manifests in a folder (<name>.znode-package.json)
137
+ function resolvePackage(target) {
138
+ const isFile = fs.statSync(target).isFile();
139
+ const dir = isFile ? path.dirname(target) : target;
140
+ const manifestFile = isFile ? target : path.join(dir, MANIFEST);
141
+ return { dir, manifestFile, outName: path.basename(manifestFile) === MANIFEST ? "dist" : `dist-${path.basename(manifestFile, `.${MANIFEST}`)}` };
142
+ }
143
+
144
+ // The package's tsconfig check. tsc also checks the store files the package imports; their errors are the store's, not
145
+ // the package's: listed as warnings. An error in the package's own files stops the build.
146
+ function typeCheck(dir, tsconfigFile) {
147
+ let output = "";
148
+ try {
149
+ execFileSync(process.execPath, [TSC(), "-p", tsconfigFile, "--noEmit", "--pretty", "false"], {
150
+ cwd: dir,
151
+ encoding: "utf8",
152
+ stdio: ["ignore", "pipe", "pipe"],
153
+ });
154
+ return;
155
+ } catch (error) {
156
+ output = `${error.stdout || ""}${error.stderr || ""}`;
157
+ }
158
+ // one entry per error: "file(line,col): error TSnnnn: message" and its indented continuation lines
159
+ const errors = output.split(/\r?\n(?=\S)/).filter((entry) => /^.+?\(\d+,\d+\): error TS\d+:/.test(entry));
160
+ if (!errors.length) fail(`tsconfig check failed:\n${output}`);
161
+ const inPackage = (entry) => !path.relative(dir, path.resolve(dir, entry.slice(0, entry.indexOf("(")))).startsWith("..");
162
+ const own = errors.filter(inPackage);
163
+ const store = errors.filter((entry) => !inPackage(entry));
164
+ if (store.length) console.log(`warning ${store.length} type error(s) in store files the package imports (the store's to fix):\n ${store.join("\n ")}`);
165
+ if (own.length) fail(`type errors in the package:\n ${own.join("\n ")}`);
166
+ }
167
+
168
+ // every .ts / .tsx under srcRoot compiled to .js under outRoot, one file at a time and without resolving imports (the
169
+ // tsconfig check has done the types): types removed, JSX as Next.js compiles it (react/jsx-runtime)
170
+ function transpileSources(srcRoot, outRoot) {
171
+ const ts = require("typescript");
172
+ const walk = (folder) =>
173
+ fs.readdirSync(folder, { withFileTypes: true }).flatMap((item) => {
174
+ const file = path.join(folder, item.name);
175
+ if (item.isDirectory()) return walk(file);
176
+ return /\.tsx?$/.test(item.name) && !item.name.endsWith(".d.ts") ? [file] : [];
177
+ });
178
+ for (const file of walk(srcRoot)) {
179
+ const { outputText } = ts.transpileModule(fs.readFileSync(file, "utf8"), {
180
+ fileName: file,
181
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ES2022, jsx: ts.JsxEmit.ReactJSX, jsxImportSource: "react" },
182
+ });
183
+ const target = path.join(outRoot, path.relative(srcRoot, file)).replace(/\.tsx?$/, ".js");
184
+ fs.mkdirSync(path.dirname(target), { recursive: true });
185
+ fs.writeFileSync(target, outputText);
186
+ }
187
+ }
188
+
189
+ function build(target) {
190
+ const { dir, manifestFile, outName } = resolvePackage(target);
191
+ const manifest = readJson(manifestFile);
192
+ validateManifest(manifest, path.basename(manifestFile));
193
+ const out = path.join(dir, outName);
194
+ fs.rmSync(out, { recursive: true, force: true });
195
+ fs.mkdirSync(out, { recursive: true });
196
+ const tmp = path.join(dir, ".build");
197
+ const files = {};
198
+ const prefix = `${manifest.name}-${manifest.version}`;
199
+ // next/font/google fonts built into the package (next-imports.mjs): their files and @font-face CSS
200
+ const fonts = [];
201
+ // A package with its own tsconfig.json (extending the store's tsconfig.base.json) is checked against the store's real
202
+ // types (every @znode alias, no declarations to write), then compiled file by file without type information, JSX as
203
+ // Next.js does (react/jsx-runtime: the store's). Without one, the package compiles as before (tsc, JSX factory h).
204
+ const tsconfigFile = path.join(dir, "tsconfig.json");
205
+ const projectMode = fs.existsSync(tsconfigFile);
206
+ if (projectMode && Object.values(manifest.build || {}).length) typeCheck(dir, tsconfigFile);
207
+
208
+ for (const part of ["server", "browser"]) {
209
+ const entry = manifest.build?.[part];
210
+ if (!entry) continue;
211
+ fs.rmSync(tmp, { recursive: true, force: true });
212
+ if (projectMode) transpileSources(path.dirname(path.join(dir, entry)), tmp);
213
+ else execFileSync(
214
+ process.execPath,
215
+ [
216
+ TSC(),
217
+ "--target",
218
+ "es2022",
219
+ "--module",
220
+ "es2022",
221
+ "--moduleResolution",
222
+ "bundler",
223
+ "--lib",
224
+ "es2022,dom",
225
+ "--skipLibCheck",
226
+ // import React from "react", as the store's own components do
227
+ "--allowSyntheticDefaultImports",
228
+ "--jsx",
229
+ "react",
230
+ "--jsxFactory",
231
+ "h",
232
+ "--jsxFragmentFactory",
233
+ "Fragment",
234
+ "--outDir",
235
+ tmp,
236
+ path.join(dir, entry),
237
+ ],
238
+ { stdio: "inherit" }
239
+ );
240
+ const compiled = path.join(tmp, path.basename(entry).replace(/\.tsx?$/, ".js"));
241
+ const target = `${prefix}.${part}.mjs`;
242
+ // rollup with the Next.js imports plugin (next-imports.mjs), from a config file: the plugin downloads fonts, which
243
+ // is async, in rollup's own process; what it built comes back in fonts.json
244
+ const config = path.join(tmp, "rollup.config.mjs");
245
+ const fontsFile = path.join(tmp, "fonts.json");
246
+ fs.writeFileSync(
247
+ config,
248
+ [
249
+ `import fs from "node:fs";`,
250
+ `import { znodeNext } from ${JSON.stringify(pathToFileURL(path.join(HERE, "next-imports.mjs")).href)};`,
251
+ `const fonts = [];`,
252
+ `export default {`,
253
+ ` input: ${JSON.stringify(compiled)},`,
254
+ ` output: { file: ${JSON.stringify(path.join(out, target))}, format: "es", sourcemap: true },`,
255
+ ` plugins: [`,
256
+ ` znodeNext({ part: ${JSON.stringify(part)}, prefix: ${JSON.stringify(prefix)}, outDir: ${JSON.stringify(out)}, fonts }),`,
257
+ ` { name: "fonts-out", writeBundle() { fs.writeFileSync(${JSON.stringify(fontsFile)}, JSON.stringify(fonts)); } },`,
258
+ ` ],`,
259
+ `};`,
260
+ ].join("\n")
261
+ );
262
+ execFileSync(process.execPath, [ROLLUP(), "--config", config, "--silent"], { stdio: "inherit" });
263
+ if (fs.existsSync(fontsFile)) fonts.push(...JSON.parse(fs.readFileSync(fontsFile, "utf8")));
264
+ files[part] = target;
265
+ }
266
+ fs.rmSync(tmp, { recursive: true, force: true });
267
+
268
+ // styles: concatenated into one stylesheet, after the fonts next/font/google built; assets (fonts, images) keep their
269
+ // names, which the stylesheet refers to
270
+ if (manifest.styles?.length || fonts.length) {
271
+ const css = [
272
+ ...fonts.map((font) => font.css),
273
+ ...(manifest.styles || []).flatMap((pattern) => glob(dir, pattern)).map((file) => fs.readFileSync(file, "utf8")),
274
+ ].join("\n");
275
+ files.styles = [`${prefix}.css`];
276
+ fs.writeFileSync(path.join(out, files.styles[0]), css);
277
+ // rules the store's own stylesheets already have, loaded again later, would beat its responsive variants
278
+ if (manifest.dedupeStyles) {
279
+ const target = path.join(out, files.styles[0]);
280
+ execFileSync(process.execPath, [path.join(HERE, "css-dedupe.mjs"), target, process.env.STORE_URL || "http://staplespromo.localhost:3000/", target], { stdio: "inherit" });
281
+ }
282
+ }
283
+ files.assets = (manifest.assets || [])
284
+ .flatMap((pattern) => glob(dir, pattern))
285
+ .map((file) => {
286
+ fs.copyFileSync(file, path.join(out, path.basename(file)));
287
+ return path.basename(file);
288
+ })
289
+ // the font files next/font/google downloaded, already in dist
290
+ .concat(fonts.flatMap((font) => font.files));
291
+ if (manifest.messages) {
292
+ files.messages = `${prefix}.labels.json`;
293
+ fs.copyFileSync(path.join(dir, manifest.messages), path.join(out, files.messages));
294
+ }
295
+ if (manifest.pages) {
296
+ files.pages = Object.fromEntries(
297
+ Object.entries(manifest.pages).map(([route, file], index) => {
298
+ const target = `${prefix}.page${index}.json`;
299
+ fs.copyFileSync(path.join(dir, file), path.join(out, target));
300
+ return [route, target];
301
+ })
302
+ );
303
+ }
304
+ const { build: _build, styles: _styles, assets: _assets, dedupeStyles: _dedupe, ...rest } = manifest;
305
+ fs.writeFileSync(path.join(out, MANIFEST), JSON.stringify({ ...rest, files }, null, 2) + "\n");
306
+ console.log(`built ${manifest.kind} ${manifest.name}@${manifest.version}: ${fs.readdirSync(out).length} files`);
307
+ return { manifest, out };
308
+ }
309
+
310
+ function pack(target) {
311
+ const { manifest, out } = build(target);
312
+ const { dir } = resolvePackage(target);
313
+ const zip = new AdmZip();
314
+ for (const name of fs.readdirSync(out)) zip.addLocalFile(path.join(out, name));
315
+ fs.mkdirSync(path.join(dir, "releases"), { recursive: true });
316
+ const file = path.join(dir, "releases", `${manifest.name}-${manifest.version}.zpkg.zip`);
317
+ zip.writeZip(file);
318
+ console.log(`packed ${path.basename(file)} (${fs.statSync(file).size} bytes)`);
319
+ }
320
+
321
+ // ---- install: validate, copy into the plugin directory, upsert the registry entry -------------------------------
322
+ // Installs into one folder can run at the same time (several pipelines, an admin upload): each takes the folder's lock
323
+ // (an atomic mkdir) for the read-change-write of plugins.json, writes it atomically (a temp file renamed over it, so the
324
+ // running webstore never reads half a file) and keeps the previous registry in .history/ (the last HISTORY_KEEP).
325
+ const LOCK_WAIT_MS = 60000;
326
+ const LOCK_STALE_MS = 120000;
327
+ const HISTORY_KEEP = 50;
328
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
329
+
330
+ function lockRegistry(storeDir) {
331
+ fs.mkdirSync(storeDir, { recursive: true });
332
+ const lock = path.join(storeDir, ".plugins.lock");
333
+ const deadline = Date.now() + LOCK_WAIT_MS;
334
+ for (;;) {
335
+ try {
336
+ fs.mkdirSync(lock);
337
+ break;
338
+ } catch (error) {
339
+ if (error.code !== "EEXIST") throw error;
340
+ // a lock left by a crashed install
341
+ try {
342
+ if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) fs.rmSync(lock, { recursive: true, force: true });
343
+ } catch {
344
+ // removed meanwhile
345
+ }
346
+ if (Date.now() > deadline) fail(`the registry in ${storeDir} is locked by another install (remove ${lock} if none is running)`);
347
+ sleep(25 + Math.floor(Math.random() * 50));
348
+ }
349
+ }
350
+ const release = () => fs.rmSync(lock, { recursive: true, force: true });
351
+ process.on("exit", release);
352
+ return () => {
353
+ release();
354
+ process.off("exit", release);
355
+ };
356
+ }
357
+
358
+ function writeRegistry(registryFile, registry) {
359
+ const dir = path.dirname(registryFile);
360
+ if (fs.existsSync(registryFile)) {
361
+ const history = path.join(dir, ".history");
362
+ fs.mkdirSync(history, { recursive: true });
363
+ fs.copyFileSync(registryFile, path.join(history, `plugins-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}.json`));
364
+ const old = fs
365
+ .readdirSync(history)
366
+ .filter((name) => name.startsWith("plugins-"))
367
+ .sort();
368
+ for (const name of old.slice(0, Math.max(0, old.length - HISTORY_KEEP))) fs.rmSync(path.join(history, name), { force: true });
369
+ }
370
+ const temp = `${registryFile}.tmp-${process.pid}`;
371
+ fs.writeFileSync(temp, JSON.stringify(registry, null, 2) + "\n");
372
+ fs.renameSync(temp, registryFile);
373
+ }
374
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
375
+
376
+ // the store's settings over the package defaults; an object setting (labels, panels) keeps the store's values and
377
+ // gains the keys a new version adds
378
+ function mergeSettings(defaults, previous) {
379
+ const merged = { ...defaults, ...previous };
380
+ for (const [key, value] of Object.entries(defaults)) {
381
+ if (isPlainObject(value) && isPlainObject(previous[key])) merged[key] = { ...value, ...previous[key] };
382
+ }
383
+ return merged;
384
+ }
385
+
386
+ function install(source, storeDir) {
387
+ let entries;
388
+ if (fs.statSync(source).isDirectory()) {
389
+ // a package folder's build output (dist; package in packages built before the dist folder)
390
+ const built = ["dist", "package"].map((name) => path.join(source, name)).find((dir) => fs.existsSync(path.join(dir, MANIFEST)));
391
+ const dir = built || source;
392
+ entries = fs.readdirSync(dir).map((name) => ({ name, data: fs.readFileSync(path.join(dir, name)) }));
393
+ } else {
394
+ entries = new AdmZip(source)
395
+ .getEntries()
396
+ .filter((entry) => !entry.isDirectory)
397
+ .map((entry) => ({ name: entry.entryName, data: entry.getData() }));
398
+ }
399
+ const manifestEntry = entries.find((entry) => entry.name === "znode-package.json");
400
+ if (!manifestEntry) fail("no znode-package.json in the package");
401
+ const manifest = JSON.parse(manifestEntry.data.toString("utf8"));
402
+ validateManifest(manifest, "package");
403
+
404
+ const total = entries.reduce((sum, entry) => sum + entry.data.length, 0);
405
+ if (total > MAX_BYTES) fail(`package is ${total} bytes; the limit is ${MAX_BYTES}`);
406
+ const files = entries.filter((entry) => entry.name !== "znode-package.json");
407
+ for (const entry of files) {
408
+ if (entry.name !== path.basename(entry.name)) fail(`"${entry.name}": a package is flat, no folders`);
409
+ if (!SERVED.has(path.extname(entry.name).toLowerCase())) fail(`"${entry.name}": file type not allowed`);
410
+ }
411
+ const has = (name) => files.some((entry) => entry.name === name);
412
+ const referenced = [
413
+ manifest.files?.server,
414
+ manifest.files?.browser,
415
+ manifest.files?.messages,
416
+ ...(manifest.files?.styles || []),
417
+ ...Object.values(manifest.files?.pages || {}),
418
+ ].filter(Boolean);
419
+ for (const name of referenced) if (!has(name)) fail(`znode-package.json names "${name}", which isn't in the package`);
420
+
421
+ const registryFile = path.join(storeDir, "plugins.json");
422
+ const unlock = lockRegistry(storeDir);
423
+ const registry = fs.existsSync(registryFile) ? readJson(registryFile) : { plugins: [] };
424
+ // a package never replaces a file another installed package uses
425
+ const owners = new Map();
426
+ for (const item of registry.plugins) {
427
+ if (item.name === manifest.name) continue;
428
+ for (const name of [item.file, item.browser, item.messages, ...(item.styles || []), ...Object.values(item.pages || {})]) if (name) owners.set(name, item.name);
429
+ }
430
+ for (const entry of files) if (owners.has(entry.name)) fail(`"${entry.name}" belongs to package ${owners.get(entry.name)}`);
431
+
432
+ fs.mkdirSync(storeDir, { recursive: true });
433
+ for (const entry of files) fs.writeFileSync(path.join(storeDir, entry.name), entry.data);
434
+
435
+ const previous = registry.plugins.find((item) => item.name === manifest.name);
436
+ const defaults = Object.fromEntries(
437
+ Object.entries(manifest.settingsSchema || {})
438
+ .filter(([, field]) => field.default !== undefined)
439
+ .map(([key, field]) => [key, field.default])
440
+ );
441
+ const entry = {
442
+ name: manifest.name,
443
+ kind: manifest.kind === "widget" ? "plugin" : manifest.kind,
444
+ version: manifest.version,
445
+ label: manifest.label,
446
+ publisher: manifest.publisher,
447
+ ...(manifest.parent ? { parent: manifest.parent } : {}),
448
+ ...(manifest.files?.server ? { file: manifest.files.server } : {}),
449
+ ...(manifest.files?.browser ? { browser: manifest.files.browser } : {}),
450
+ ...(manifest.files?.styles?.length ? { styles: manifest.files.styles } : {}),
451
+ ...(manifest.files?.messages ? { messages: manifest.files.messages } : {}),
452
+ ...(manifest.files?.pages ? { pages: manifest.files.pages } : {}),
453
+ ...(manifest.widgets?.length ? { widgets: manifest.widgets } : {}),
454
+ ...(manifest.overrides ? { overrides: manifest.overrides } : {}),
455
+ ...(manifest.serverPages?.length ? { serverPages: manifest.serverPages } : {}),
456
+ ...(manifest.sandbox === true ? { sandbox: true } : {}),
457
+ // the webstore accepts files (multipart) only for a package that declares them
458
+ ...((manifest.permissions || []).includes("uploads") ? { uploads: true } : {}),
459
+ ...(manifest.settingsSchema ? { settingsSchema: manifest.settingsSchema } : {}),
460
+ // where it runs and its settings are the store owner's: an upgrade keeps them; a new package starts switched off
461
+ enabled: previous ? previous.enabled : false,
462
+ stores: previous ? previous.stores : [],
463
+ settings: mergeSettings(defaults, previous?.settings || {}),
464
+ };
465
+ if (previous) registry.plugins[registry.plugins.indexOf(previous)] = entry;
466
+ else registry.plugins.push(entry);
467
+ writeRegistry(registryFile, registry);
468
+ // the replaced version's files (an upgrade's old bundles and stylesheets) leave the plugin directory
469
+ const kept = new Set(files.map((file) => file.name));
470
+ for (const name of [previous?.file, previous?.browser, previous?.messages, ...(previous?.styles || []), ...Object.values(previous?.pages || {})]) {
471
+ if (name && !kept.has(name) && name === path.basename(name)) fs.rmSync(path.join(storeDir, name), { force: true });
472
+ }
473
+
474
+ unlock();
475
+
476
+ const missing = Object.entries(manifest.settingsSchema || {}).filter(([key, field]) => field.required && (entry.settings[key] === undefined || entry.settings[key] === ""));
477
+ console.log(
478
+ `installed ${manifest.kind} ${manifest.name}@${manifest.version}${previous ? ` (was ${previous.version || "unversioned"})` : ""}: ${files.length} files, ${entry.enabled ? "enabled" : "disabled"} for ${JSON.stringify(entry.stores)}`
479
+ );
480
+ if (missing.length) console.log(` settings to fill in before enabling: ${missing.map(([key]) => key).join(", ")}`);
481
+ }
482
+
483
+ // ---- create: a starter package of a kind (templates.mjs), with the API typings next to its sources ---------------
484
+ function create(kind, name, dir) {
485
+ if (!TEMPLATES[kind]) fail(`kind must be one of ${Object.keys(TEMPLATES).join(", ")}`);
486
+ if (!NAME.test(name || "")) fail("name must be lowercase letters, digits and dashes (2 to 49)");
487
+ const target = path.resolve(dir || path.join(process.cwd(), name));
488
+ if (fs.existsSync(target) && fs.readdirSync(target).length) fail(`${target} exists and is not empty`);
489
+ for (const [file, content] of Object.entries(TEMPLATES[kind](name))) {
490
+ const full = path.join(target, file);
491
+ fs.mkdirSync(path.dirname(full), { recursive: true });
492
+ fs.writeFileSync(full, typeof content === "string" ? content : JSON.stringify(content, null, 2) + "\n");
493
+ }
494
+ if (kind !== "content") fs.copyFileSync(path.join(HERE, "..", "types", "extension-api.d.ts"), path.join(target, "src", "extension-api.d.ts"));
495
+ console.log(`created ${kind} ${name} in ${target}`);
496
+ console.log(" next: fill in label, publisher and description in znode-package.json, then run its build-and-upload.sh");
497
+ }
498
+
499
+ // ---- check: what a marketplace review looks at, from the package's own files ------------------------------------
500
+ const HOOK_NAMES = ["onCartChanged", "beforeAddToCart", "afterAddToCart", "mapCartItems"];
501
+
502
+ // the code an entry pulls in: the entry and the files it imports by relative path, followed (a package's server and
503
+ // browser parts share a folder, so a folder read would mix them); type-only imports are skipped
504
+ function sourceOf(dir, entry) {
505
+ if (!entry) return "";
506
+ const seen = new Set();
507
+ const sources = [];
508
+ const visit = (file) => {
509
+ if (seen.has(file) || !fs.existsSync(file)) return;
510
+ seen.add(file);
511
+ const code = fs.readFileSync(file, "utf8");
512
+ sources.push(code);
513
+ for (const [, typeOnly, spec] of code.matchAll(/\bimport\s+(type\s+)?[^;]*?from\s+["'](\.[^"']+)["']/g)) {
514
+ if (typeOnly) continue;
515
+ const base = path.resolve(path.dirname(file), spec).replace(/\.(m?js)$/, "");
516
+ const found = [".ts", ".tsx", ".js", ".mjs", "/index.ts", "/index.tsx"].map((ext) => base + ext).find((candidate) => fs.existsSync(candidate));
517
+ if (found) visit(found);
518
+ }
519
+ };
520
+ visit(path.join(dir, entry));
521
+ return sources.join("\n");
522
+ }
523
+
524
+ // the server renders a browser bundle in this format from one compiled copy for all stores
525
+ // (packages/extensions/src/server-instances.ts); any other is imported once per store, and Node keeps every copy
526
+ function serverRenderFormat(code) {
527
+ const match = /\bexport\s*(?:\{\s*([A-Za-z_$][\w$]*)\s+as\s+default\s*,?\s*\}|default\s+([A-Za-z_$][\w$]*))\s*;?\s*(?:\/\/#\s*sourceMappingURL=\S*\s*)?$/.exec(code);
528
+ if (!match || /(^|[^\w$.])import\s*\(/.test(code.slice(0, match.index))) return false;
529
+ try {
530
+ new vm.Script(`(function () {\n"use strict";\n${code.slice(0, match.index)}\nreturn ${match[1] || match[2]};\n})`);
531
+ return true;
532
+ } catch {
533
+ return false;
534
+ }
535
+ }
536
+
537
+ function check(target) {
538
+ const { dir, manifestFile } = resolvePackage(target);
539
+ const manifest = readJson(manifestFile);
540
+ validateManifest(manifest, path.basename(manifestFile));
541
+ const errors = [];
542
+ const warnings = [];
543
+
544
+ // the listing
545
+ for (const key of ["label", "publisher", "description"]) if (!String(manifest[key] || "").trim()) errors.push(`"${key}" is missing (the marketplace shows it)`);
546
+ if (/describe what it does/i.test(manifest.description || "") || manifest.publisher === "Your company") errors.push("the starter's publisher or description is still in place");
547
+ else if (String(manifest.description || "").length < 30) warnings.push('"description" is short: say what it does for the store');
548
+ for (const key of ["license", "compatibility"]) if (!manifest[key]) warnings.push(`"${key}" is missing`);
549
+
550
+ // permissions against the code
551
+ const server = sourceOf(dir, manifest.build?.server);
552
+ const browser = sourceOf(dir, manifest.build?.browser);
553
+ const used = new Set();
554
+ if (/\broutes\s*[:=,}]/.test(server)) used.add("routes");
555
+ if (HOOK_NAMES.some((hook) => new RegExp(`\\b${hook}\\b`).test(server))) used.add("cartHooks");
556
+ if (Object.keys(manifest.overrides || {}).length) used.add("overrides");
557
+ if (/\bznode\s*\(/.test(server)) used.add("znodeApi");
558
+ if (/\bfetch\s*\(|\bhttps?\.request\s*\(/.test(server)) used.add("externalNetwork");
559
+ if (/\.files\b/.test(server)) used.add("uploads");
560
+ const declared = new Set(manifest.permissions || []);
561
+ for (const item of used) if (!declared.has(item)) errors.push(`uses "${item}" without declaring it in "permissions"`);
562
+ for (const item of declared) if (!used.has(item)) warnings.push(`declares "${item}" but no code uses it (the review asks why)`);
563
+ if (/\beval\s*\(|new Function\s*\(/.test(server + browser)) errors.push("uses eval or new Function");
564
+ if (/document\.cookie/.test(browser)) warnings.push("reads cookies in the browser: keep secrets on the server (routes)");
565
+
566
+ // settings
567
+ for (const [key, field] of Object.entries(manifest.settingsSchema || {})) {
568
+ if (!field.label) warnings.push(`setting "${key}" has no label (the admin shows it)`);
569
+ if (field.required && field.default !== undefined) warnings.push(`setting "${key}" is required but has a default`);
570
+ if (field.browser && /secret|password|token|api_?key/i.test(key)) errors.push(`setting "${key}" looks secret but is sent to the browser ("browser": true)`);
571
+ }
572
+ if (manifest.kind === "theme" && !Object.values(manifest.settingsSchema || {}).some((field) => field.attribute)) {
573
+ warnings.push("no setting is bound to a Znode attribute: per-store branding then needs a registry change per store");
574
+ }
575
+
576
+ // the built files (pack first)
577
+ const out = path.join(dir, "dist");
578
+ if (fs.existsSync(out)) {
579
+ let total = 0;
580
+ for (const name of fs.readdirSync(out)) {
581
+ const size = fs.statSync(path.join(out, name)).size;
582
+ total += size;
583
+ if (name.endsWith(".browser.mjs")) {
584
+ if (size > 512 * 1024) warnings.push(`${name} is ${Math.round(size / 1024)} KB: every page of the store loads it`);
585
+ if (!serverRenderFormat(fs.readFileSync(path.join(out, name), "utf8")))
586
+ warnings.push(`${name} is not in the server-render format (no imports, one default export): the server keeps a copy per store`);
587
+ }
588
+ if (name.endsWith(".css") && size > 200 * 1024) warnings.push(`${name} is ${Math.round(size / 1024)} KB`);
589
+ }
590
+ if (total > MAX_BYTES) errors.push(`dist is ${Math.round(total / 1048576)} MB (limit 10 MB)`);
591
+ } else warnings.push("not built yet: pack it to check sizes and the server-render format");
592
+
593
+ for (const item of errors) console.log(`error ${item}`);
594
+ for (const item of warnings) console.log(`warning ${item}`);
595
+ console.log(`check ${manifest.name}@${manifest.version}: ${errors.length} errors, ${warnings.length} warnings`);
596
+ if (errors.length) process.exit(1);
597
+ }
598
+
599
+ // ---- project commands: deploy, dev, link-store ------------------------------------------------------------------
600
+
601
+ const needStore = (storeDir) =>
602
+ storeDir || fail("needs the store's plugin folder: pass it after the package, or set RUNTIME_PLUGINS_DIR");
603
+
604
+ // pack, then install the zip it made into the store's plugin folder
605
+ function deploy(target, storeDir) {
606
+ pack(target);
607
+ const { dir, manifestFile } = resolvePackage(target);
608
+ const manifest = readJson(manifestFile);
609
+ install(path.join(dir, "releases", `${manifest.name}-${manifest.version}.zpkg.zip`), storeDir);
610
+ }
611
+
612
+ // deploy now, then again whenever the package's sources or manifest change; the store picks a new file up on the next
613
+ // request (it reloads a package when its files change), so a page refresh shows the change
614
+ function dev(target, storeDir) {
615
+ const { dir } = resolvePackage(target);
616
+ const self = fileURLToPath(import.meta.url);
617
+ const run = () => spawnSync(process.execPath, [self, "deploy", dir, storeDir], { stdio: "inherit" });
618
+ run();
619
+ let timer = null;
620
+ const changed = (file) => {
621
+ if (!file || /(^|[\\/])(dist|releases|\.build|node_modules)([\\/]|$)/.test(String(file))) return;
622
+ clearTimeout(timer);
623
+ timer = setTimeout(() => {
624
+ console.log(`znode dev: ${file} changed, deploying`);
625
+ run();
626
+ }, 300);
627
+ };
628
+ fs.watch(path.join(dir, "src"), { recursive: true }, (_event, file) => changed(file && path.join("src", file)));
629
+ fs.watch(dir, (_event, file) => file === MANIFEST && changed(file));
630
+ console.log(`znode dev: watching ${dir} (Ctrl+C to stop)`);
631
+ }
632
+
633
+ // the store's real types for the editor and the build check: tsconfig.store.json (git-ignored, per machine) is this
634
+ // package's preset plus the store repo's aliases (every @znode path of its tsconfig.base.json, from the store's folder).
635
+ // Only the aliases are taken: the store's own options (its rootDir among them) would refuse a project kept elsewhere.
636
+ function linkStore(storeRepo, project = ".") {
637
+ const base = path.resolve(storeRepo, "tsconfig.base.json");
638
+ if (!fs.existsSync(base)) fail(`${base} not found: pass the store repo's folder (the one with tsconfig.base.json)`);
639
+ const ts = require("typescript");
640
+ const { config, error } = ts.readConfigFile(base, ts.sys.readFile);
641
+ if (error) fail(`${base}: ${ts.flattenDiagnosticMessageText(error.messageText, "\n")}`);
642
+ const options = config.compilerOptions || {};
643
+ const toSlash = (value) => value.split(path.sep).join("/");
644
+ const file = path.resolve(project, "tsconfig.store.json");
645
+ const linked = {
646
+ extends: "znode-plugin/tsconfig.json",
647
+ compilerOptions: { baseUrl: toSlash(path.resolve(path.dirname(base), options.baseUrl || ".")), paths: options.paths || {} },
648
+ };
649
+ fs.writeFileSync(file, JSON.stringify(linked, null, 2) + "\n");
650
+ console.log(`linked ${file} to ${base} (${Object.keys(linked.compilerOptions.paths).length} store aliases)`);
651
+ }
652
+
653
+ const args = process.argv.slice(2);
654
+ // the store's plugin folder: the argument, else RUNTIME_PLUGINS_DIR, else the project's git-ignored znode.local.json
655
+ // ({ "pluginsDir": "…" }, written by create-znode-plugin --plugins-dir) in the folder the command runs in
656
+ function localPluginsDir() {
657
+ try {
658
+ return JSON.parse(fs.readFileSync(path.resolve("znode.local.json"), "utf8")).pluginsDir || undefined;
659
+ } catch {
660
+ return undefined;
661
+ }
662
+ }
663
+ const [command, target, storeDir = process.env.RUNTIME_PLUGINS_DIR || localPluginsDir()] = args;
664
+ if (command === "create") {
665
+ create(args[1], args[2], args[3]);
666
+ process.exit(0);
667
+ }
668
+ if (command === "link-store") {
669
+ if (!target) fail("usage: znode link-store <storeRepoDir> [projectDir]");
670
+ linkStore(target, args[2]);
671
+ process.exit(0);
672
+ }
673
+ if (!target) fail("usage: znode <build|pack|check|install|deploy|dev> <dir|zip> [storeDir], znode create <kind> <name> [dir], znode link-store <storeRepoDir>");
674
+ if (command === "check") check(path.resolve(target));
675
+ else if (command === "build") build(path.resolve(target));
676
+ else if (command === "pack") pack(path.resolve(target));
677
+ else if (command === "install") install(path.resolve(target), path.resolve(needStore(storeDir)));
678
+ else if (command === "deploy") deploy(path.resolve(target), path.resolve(needStore(storeDir)));
679
+ else if (command === "dev") dev(path.resolve(target), path.resolve(needStore(storeDir)));
680
+ else fail(`unknown command "${command}"`);