@hyphacommerce/cli 0.1.0-beta.2 → 0.1.0-beta.3

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 (3) hide show
  1. package/README.md +7 -0
  2. package/dist/main.mjs +257 -9
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -7,6 +7,8 @@ Rust. Hypha is in public beta: this CLI follows the API's version and may change
7
7
  ```bash
8
8
  npx @hyphacommerce/cli init # writes a deployment folder: settings, secrets, compose files
9
9
  npx @hyphacommerce/cli deploy # runs it on a server over SSH, or on this machine
10
+ npx @hyphacommerce/cli create storefront my-shop # a shop of your own, from Hypha's storefront
11
+ npx @hyphacommerce/cli create app my-app # an app for the apps platform
10
12
  ```
11
13
 
12
14
  `init` asks for the target (a server, this machine, or Cloudflare Workers), the domains
@@ -16,6 +18,11 @@ the folder to the server and starts Postgres, file storage, the API, the apps an
16
18
  with HTTPS. `status` and `logs [service]` look at it; `apps` and `spores` manage what's
17
19
  deployed beside the API.
18
20
 
21
+ `create <storefront|app> <dir>` makes a project of your own from one of Hypha's starters,
22
+ at this CLI's version: the files come from the release's tag and its `@hyphacommerce/*`
23
+ dependencies are that release's packages, so the project installs and builds on its own
24
+ (`--ref` takes them from another tag or branch).
25
+
19
26
  Building the images from source (`--build-from-source`), spores, co-located apps and the
20
27
  Cloudflare target need a checkout of the repository: run `pnpm hypha` from it.
21
28
 
package/dist/main.mjs CHANGED
@@ -7,10 +7,11 @@ import { request } from "node:http";
7
7
  import { request as request$1 } from "node:https";
8
8
  import { isIP } from "node:net";
9
9
  import { createHash, randomBytes, randomInt } from "node:crypto";
10
- import { chmod, mkdir, readFile, readlink, rm, stat, symlink, writeFile } from "node:fs/promises";
10
+ import { chmod, cp, mkdir, mkdtemp, readFile, readdir, readlink, rm, stat, symlink, writeFile } from "node:fs/promises";
11
11
  import { basename, join, relative, resolve, sep } from "node:path";
12
12
  import { existsSync, readdirSync } from "node:fs";
13
13
  import { spawn } from "node:child_process";
14
+ import { tmpdir } from "node:os";
14
15
  //#region src/api.ts
15
16
  var ApiError = class extends Error {
16
17
  status;
@@ -1095,7 +1096,7 @@ async function remoteHead(git, ref = "HEAD", runner = runHere) {
1095
1096
  /** `git` at commit `rev` in `clone`: cloned the first time, fetched when the commit is new
1096
1097
  * to it, and left as it is when it's there already. With this machine's git credentials. */
1097
1098
  async function cloneAt(git, rev, clone, runner = runHere) {
1098
- if (!await exists$1(join(clone, ".git"))) await runner("git", [
1099
+ if (!await exists$2(join(clone, ".git"))) await runner("git", [
1099
1100
  "clone",
1100
1101
  "--quiet",
1101
1102
  git,
@@ -1129,7 +1130,7 @@ async function cloneAt(git, rev, clone, runner = runHere) {
1129
1130
  capture: true
1130
1131
  });
1131
1132
  }
1132
- async function exists$1(path) {
1133
+ async function exists$2(path) {
1133
1134
  return stat(path).then(() => true, () => false);
1134
1135
  }
1135
1136
  /** Links `<build root>/hypha` to this checkout, so the apps' `../hypha/packages/*`
@@ -1155,7 +1156,7 @@ async function checkout(dir, a, runner = runHere) {
1155
1156
  await linkHypha(dir);
1156
1157
  const clone = cloneDir(dir, a);
1157
1158
  await cloneAt(a.git, a.rev, clone, runner);
1158
- if (!await exists$1(join(REPO, "node_modules"))) await runner("pnpm", ["install", "--frozen-lockfile"], {
1159
+ if (!await exists$2(join(REPO, "node_modules"))) await runner("pnpm", ["install", "--frozen-lockfile"], {
1159
1160
  cwd: REPO,
1160
1161
  capture: true
1161
1162
  });
@@ -1716,6 +1717,255 @@ const apps = defineCommand({
1716
1717
  }
1717
1718
  });
1718
1719
  //#endregion
1720
+ //#region src/version.ts
1721
+ const VERSION = "0.1.0-beta.3";
1722
+ //#endregion
1723
+ //#region src/create.ts
1724
+ /** The repository the starters are downloaded from. */
1725
+ const REPOSITORY = "hyphacommerce/hypha";
1726
+ const STARTERS = {
1727
+ storefront: {
1728
+ path: "apps/storefront",
1729
+ title: "Hypha's storefront: a server-rendered shop on Next.js, vinext and Astryx",
1730
+ next: [
1731
+ "cp .env.example .dev.vars # then fill in HYPHA_API_URL and a publishable key",
1732
+ "pnpm install",
1733
+ "pnpm dev # http://localhost:3002"
1734
+ ]
1735
+ },
1736
+ app: {
1737
+ path: "starters/app",
1738
+ title: "An app for Hypha's apps platform: installed over OAuth, answering webhooks and an extension point",
1739
+ next: [
1740
+ "pnpm install",
1741
+ "pnpm test",
1742
+ "APP_URL=http://localhost:8787 pnpm dev # then install it from your admin: Apps → Install app"
1743
+ ]
1744
+ }
1745
+ };
1746
+ function isStarter(name) {
1747
+ return Object.hasOwn(STARTERS, name);
1748
+ }
1749
+ /** What a copy leaves behind: a workspace's builds, caches and local secrets. */
1750
+ const SKIPPED = /* @__PURE__ */ new Set([
1751
+ "node_modules",
1752
+ "dist",
1753
+ ".next",
1754
+ ".vinext",
1755
+ ".cloudflare",
1756
+ ".wrangler",
1757
+ ".dev.vars",
1758
+ "next-env.d.ts",
1759
+ ".DS_Store"
1760
+ ]);
1761
+ function skipped(name) {
1762
+ return SKIPPED.has(name) || name.endsWith(".tsbuildinfo") || /^\.env.*\.local$/.test(name);
1763
+ }
1764
+ /** The tag a version was released as. */
1765
+ function tagOf(version) {
1766
+ return `v${version}`;
1767
+ }
1768
+ /** The release's source archive, and the folder inside it. */
1769
+ function archiveOf(ref) {
1770
+ const tag = ref.startsWith("v") || !/^\d/.test(ref) ? ref : tagOf(ref);
1771
+ return {
1772
+ url: `https://codeload.github.com/${REPOSITORY}/tar.gz/${encodeURIComponent(tag)}`,
1773
+ root: `hypha-${tag.replace(/^v/, "").replaceAll("/", "-")}`
1774
+ };
1775
+ }
1776
+ /** The starter's `.gitignore`: what the workspace's covered for it. */
1777
+ const GITIGNORE = `node_modules/
1778
+ dist/
1779
+ .next/
1780
+ .cloudflare/
1781
+ .wrangler/
1782
+ .vinext/
1783
+ *.tsbuildinfo
1784
+ .env*.local
1785
+ .dev.vars
1786
+ wrangler.toml
1787
+ next-env.d.ts
1788
+ .DS_Store
1789
+ `;
1790
+ /** pnpm's settings for the project (pnpm reads them from this file, not package.json). */
1791
+ function workspaceYaml() {
1792
+ return "# pnpm's settings for this project.\n# Hypha's packages are released together with this starter: never hold them back as too new.\nminimumReleaseAgeExclude:\n - \"@hyphacommerce/*\"\n# Dependency install scripts run only when listed here (pnpm refuses an install with one\n# it wasn't told about). workerd is the Workers runtime the dev server runs in; esbuild and\n# sharp find their binaries without their scripts; Astryx's script only prints a hint.\nallowBuilds:\n workerd: true\n esbuild: false\n sharp: false\n \"@astryxdesign/core\": false\n \"@astryxdesign/cli\": false\n";
1793
+ }
1794
+ function isRecord(value) {
1795
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1796
+ }
1797
+ /** A record of strings from a JSON value, or none. */
1798
+ function strings(value) {
1799
+ if (!isRecord(value)) return void 0;
1800
+ const out = {};
1801
+ for (const [key, item] of Object.entries(value)) if (typeof item === "string") out[key] = item;
1802
+ return out;
1803
+ }
1804
+ /** A JSON object from `text`; anything else is refused with `what`. */
1805
+ function parseObject(text, what) {
1806
+ const value = JSON.parse(text);
1807
+ if (!isRecord(value)) throw new Error(`${what} isn't a JSON object`);
1808
+ return value;
1809
+ }
1810
+ /**
1811
+ * The project's `package.json` from the starter's: named after its folder, its
1812
+ * `workspace:*` dependencies at `version` (Hypha's packages on npm), and the workspace's
1813
+ * `packageManager` and `engines`, which pnpm and Node read from the project.
1814
+ */
1815
+ function adaptManifest(source, name, version, root) {
1816
+ const swap = (deps) => deps && Object.fromEntries(Object.entries(deps).map(([dep, spec]) => [dep, spec.startsWith("workspace:") ? version : spec]));
1817
+ const { version: _version, ...rest } = source;
1818
+ return {
1819
+ ...rest,
1820
+ name,
1821
+ private: true,
1822
+ ...root.packageManager ? { packageManager: root.packageManager } : {},
1823
+ ...root.engines ? { engines: root.engines } : {},
1824
+ dependencies: swap(source.dependencies),
1825
+ devDependencies: swap(source.devDependencies)
1826
+ };
1827
+ }
1828
+ /** A project name from the folder: lowercase, what npm allows. */
1829
+ function projectName(dir) {
1830
+ return basename(resolve(dir)).toLowerCase().replaceAll(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+/, "") || "hypha-project";
1831
+ }
1832
+ /** Copies `from` into `to`, leaving builds, caches and local secrets behind. */
1833
+ async function copyStarter(from, to) {
1834
+ await cp(from, to, {
1835
+ recursive: true,
1836
+ filter: (path) => !skipped(basename(path))
1837
+ });
1838
+ }
1839
+ /** Downloads the release's archive and extracts the starter's folder from it. */
1840
+ async function downloadStarter(ref, path, to) {
1841
+ const { url, root } = archiveOf(ref);
1842
+ const work = await mkdtemp(join(tmpdir(), "hypha-create-"));
1843
+ try {
1844
+ const response = await fetch(url);
1845
+ if (!response.ok) throw new Error(response.status === 404 ? `no release ${ref} of ${REPOSITORY} (${url}): pass --ref to create from another tag or branch` : `downloading ${url}: HTTP ${response.status}`);
1846
+ const archive = join(work, "source.tar.gz");
1847
+ await writeFile(archive, new Uint8Array(await response.arrayBuffer()));
1848
+ await run("tar", [
1849
+ "-xzf",
1850
+ archive,
1851
+ "-C",
1852
+ to,
1853
+ `--strip-components=${path.split("/").length + 1}`,
1854
+ `${root}/${path}`
1855
+ ], { capture: true });
1856
+ } finally {
1857
+ await rm(work, {
1858
+ recursive: true,
1859
+ force: true
1860
+ });
1861
+ }
1862
+ }
1863
+ /** Makes `dir` from the starter `kind`; refuses a folder that isn't empty. */
1864
+ async function create(kind, dir, options = {}) {
1865
+ const starter = STARTERS[kind];
1866
+ const target = resolve(dir);
1867
+ if (await exists$1(target)) {
1868
+ if ((await readdir(target)).length > 0) throw new Error(`${dir} exists and isn't empty`);
1869
+ }
1870
+ const checkout = options.from ?? (options.ref === void 0 && inCheckout() ? REPO : void 0);
1871
+ let source;
1872
+ let root = {};
1873
+ if (checkout) {
1874
+ await copyStarter(join(checkout, starter.path), target);
1875
+ root = pick$1(parseObject(await readFile(join(checkout, "package.json"), "utf8"), "package.json"));
1876
+ source = `the checkout at ${checkout}`;
1877
+ } else {
1878
+ const ref = options.ref ?? tagOf(VERSION);
1879
+ await mkdir(target, { recursive: true });
1880
+ await downloadStarter(ref, starter.path, target);
1881
+ root = {
1882
+ packageManager: ROOT_PACKAGE_MANAGER,
1883
+ engines: ROOT_ENGINES
1884
+ };
1885
+ source = `${REPOSITORY} at ${ref}`;
1886
+ }
1887
+ const name = projectName(target);
1888
+ const manifestPath = join(target, "package.json");
1889
+ const raw = parseObject(await readFile(manifestPath, "utf8"), `${starter.path}/package.json`);
1890
+ const manifest = {
1891
+ ...raw,
1892
+ dependencies: strings(raw.dependencies),
1893
+ devDependencies: strings(raw.devDependencies)
1894
+ };
1895
+ await writeFile(manifestPath, JSON.stringify(adaptManifest(manifest, name, VERSION, root), null, 2) + "\n");
1896
+ await writeFile(join(target, ".gitignore"), GITIGNORE);
1897
+ await writeFile(join(target, "pnpm-workspace.yaml"), workspaceYaml());
1898
+ return {
1899
+ dir: target,
1900
+ name,
1901
+ source
1902
+ };
1903
+ }
1904
+ /** What the workspace's root package.json pins, read when creating from a checkout. */
1905
+ function pick$1(root) {
1906
+ const engines = strings(root.engines);
1907
+ return {
1908
+ ...typeof root.packageManager === "string" ? { packageManager: root.packageManager } : {},
1909
+ ...engines ? { engines } : {}
1910
+ };
1911
+ }
1912
+ const ROOT_PACKAGE_MANAGER = "pnpm@12.6.0";
1913
+ const ROOT_ENGINES = { node: ">=24" };
1914
+ async function exists$1(path) {
1915
+ return stat(path).then(() => true, () => false);
1916
+ }
1917
+ //#endregion
1918
+ //#region src/commands/create.ts
1919
+ const createCommand = defineCommand({
1920
+ meta: {
1921
+ name: "create",
1922
+ description: "A project of your own from a starter: the storefront, or an app"
1923
+ },
1924
+ args: {
1925
+ starter: {
1926
+ type: "positional",
1927
+ required: false,
1928
+ description: `One of ${Object.keys(STARTERS).join(", ")}`
1929
+ },
1930
+ dir: {
1931
+ type: "positional",
1932
+ required: false,
1933
+ description: "The new project's folder"
1934
+ },
1935
+ ref: {
1936
+ type: "string",
1937
+ description: `A tag or branch of hyphacommerce/hypha to take the starter from (default v${VERSION}, this CLI's release)`
1938
+ },
1939
+ yes: {
1940
+ type: "boolean",
1941
+ default: false,
1942
+ description: "Take defaults instead of asking"
1943
+ }
1944
+ },
1945
+ run: ({ args }) => guarded(async () => {
1946
+ setUnattended(args.yes);
1947
+ p.intro(`hypha create (v${VERSION})`);
1948
+ const starter = await ask(args.starter, void 0, () => p.select({
1949
+ message: "What are you starting?",
1950
+ options: Object.entries(STARTERS).map(([value, s]) => ({
1951
+ value,
1952
+ label: value,
1953
+ hint: s.title
1954
+ }))
1955
+ }));
1956
+ if (!isStarter(starter)) throw new Error(`no starter ${JSON.stringify(starter)}: one of ${Object.keys(STARTERS).join(", ")}`);
1957
+ const dir = await ask(args.dir, `my-${starter}`, () => p.text({
1958
+ message: "Its folder",
1959
+ placeholder: `my-${starter}`,
1960
+ defaultValue: `my-${starter}`
1961
+ }));
1962
+ const made = await create(starter, dir, { ref: args.ref });
1963
+ p.log.success(`${made.name} in ${made.dir}, from ${made.source}; Hypha's packages at ${VERSION}`);
1964
+ p.note([`cd ${dir}`, ...STARTERS[starter].next].join("\n"), "Next");
1965
+ p.outro(`${STARTERS[starter].title}.`);
1966
+ })
1967
+ });
1968
+ //#endregion
1719
1969
  //#region src/storefront.ts
1720
1970
  /** The events that change what a static page shows. */
1721
1971
  const EVENTS = [
@@ -2439,9 +2689,6 @@ function hereTools(dir, d, env) {
2439
2689
  };
2440
2690
  }
2441
2691
  //#endregion
2442
- //#region src/version.ts
2443
- const VERSION = "0.1.0-beta.2";
2444
- //#endregion
2445
2692
  //#region src/images.ts
2446
2693
  /** Where the release workflow publishes the images. */
2447
2694
  const REGISTRY = "ghcr.io/hyphacommerce";
@@ -3696,7 +3943,7 @@ const main = defineCommand({
3696
3943
  meta: {
3697
3944
  name: "hypha",
3698
3945
  version: VERSION,
3699
- description: "Host Hypha: the API, the admin, the storefront and the apps beside them"
3946
+ description: "Host Hypha: the API, the admin, the storefront and the apps beside them; start your own"
3700
3947
  },
3701
3948
  subCommands: {
3702
3949
  init,
@@ -3704,7 +3951,8 @@ const main = defineCommand({
3704
3951
  status,
3705
3952
  logs,
3706
3953
  apps,
3707
- spores
3954
+ spores,
3955
+ create: createCommand
3708
3956
  }
3709
3957
  });
3710
3958
  await runMain(main);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyphacommerce/cli",
3
- "version": "0.1.0-beta.2",
3
+ "version": "0.1.0-beta.3",
4
4
  "description": "Hosting Hypha: `hypha init` writes a deployment, `hypha deploy` runs it on a server or on Cloudflare Workers, with the apps `hypha apps` lists beside it.",
5
5
  "homepage": "https://hyphacommerce.com",
6
6
  "bugs": "https://github.com/hyphacommerce/hypha/issues",