shopnex 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -5
- package/dist/main.mjs +274 -52
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,7 +1,42 @@
|
|
|
1
1
|
# shopnex
|
|
2
2
|
|
|
3
|
-
Look after a ShopNex shop that you started with [`create-shopnex`](../create-shopnex)
|
|
4
|
-
|
|
3
|
+
Look after a ShopNex shop that you started with [`create-shopnex`](../create-shopnex), and start new apps for it.
|
|
4
|
+
|
|
5
|
+
| Command | What it does |
|
|
6
|
+
| ----------------------------- | --------------------------------------------------------------- |
|
|
7
|
+
| `shopnex migrate-db` | Moves the shop's data from the embedded database to PostgreSQL. |
|
|
8
|
+
| `shopnex generate app <name>` | Makes a new ShopNex app in the folder `<name>`, ready to run. |
|
|
9
|
+
|
|
10
|
+
Options: `--to <url>` and `--to-env <NAME>` (migrate-db), `--dir <folder>` and `--port <n>` (migrate-db), `-h, --help`
|
|
11
|
+
and `-v, --version`. `npx shopnex@latest --help` prints the same list.
|
|
12
|
+
|
|
13
|
+
## generate app
|
|
14
|
+
|
|
15
|
+
Run it in the shop folder that `create-shopnex` made:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
cd my-shop
|
|
19
|
+
npx shopnex@latest generate app my-app # makes apps/my-app
|
|
20
|
+
cd apps/my-app
|
|
21
|
+
cp .env.example .env # fill in SHOPNEX_CLIENT_ID and SHOPNEX_APP_KEY from your app's page
|
|
22
|
+
pnpm install && pnpm dev # npm or yarn work too
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
It writes a small, self-contained project (the shop can be running):
|
|
26
|
+
|
|
27
|
+
- `src/server.tsx`: the whole app. A page inside the admin, an endpoint that saves a note in the shop's app data, and
|
|
28
|
+
an `order.created` webhook.
|
|
29
|
+
- `package.json` (depends on `@shopnex/app` at this CLI's version), `tsconfig.json`, `.env.example`, `.gitignore` and
|
|
30
|
+
a `README.md` with the steps to run and install it.
|
|
31
|
+
|
|
32
|
+
The app goes to `<shop folder>/apps/<name>` when the folder has a `.env` (use `--dir` for another shop folder), and to
|
|
33
|
+
`./<name>` anywhere else. `<name>` is the folder and the package name: lowercase letters, numbers, `-`, `_` and `.`. The
|
|
34
|
+
folder must not exist yet or must be empty; nothing is overwritten.
|
|
35
|
+
|
|
36
|
+
The admin does not find a generated app by itself: it is its own server (port 4500). Register
|
|
37
|
+
`http://localhost:4500` as the App URL and install the app from the admin.
|
|
38
|
+
|
|
39
|
+
## migrate-db
|
|
5
40
|
|
|
6
41
|
```sh
|
|
7
42
|
cd my-shop # the folder create-shopnex made (it has the .env)
|
|
@@ -12,7 +47,7 @@ npx shopnex@latest migrate-db --to postgres://user:password@host:5432/shopnex
|
|
|
12
47
|
The new database must exist and be empty. To keep the password out of your shell history, put the address in an
|
|
13
48
|
environment variable and give its name: `--to-env SHOPNEX_TARGET`.
|
|
14
49
|
|
|
15
|
-
|
|
50
|
+
### What it does
|
|
16
51
|
|
|
17
52
|
1. Checks that the shop is stopped (nothing answers on the admin's port, 3000; use `--port` if you started it on
|
|
18
53
|
another) and that its database is at the schema of this version.
|
|
@@ -26,14 +61,14 @@ environment variable and give its name: `--to-env SHOPNEX_TARGET`.
|
|
|
26
61
|
If anything fails, PostgreSQL is left as empty as it was found, the `.env` is not touched, and the extra copy is
|
|
27
62
|
removed. The old data is only ever read.
|
|
28
63
|
|
|
29
|
-
|
|
64
|
+
### What it does not do
|
|
30
65
|
|
|
31
66
|
- **The optional apps' data** (`apps/<name>/.pglite`: Stripe, CJ Dropshipping, Shippo) is not moved. They start empty
|
|
32
67
|
on PostgreSQL, and the command names the ones that had data.
|
|
33
68
|
- It never merges into a database that already has tables.
|
|
34
69
|
- It does not move data back, or between two PostgreSQL servers (use `pg_dump` for that).
|
|
35
70
|
|
|
36
|
-
|
|
71
|
+
### The version rule
|
|
37
72
|
|
|
38
73
|
Like `create-shopnex`, this CLI runs the packaged build of **its own version** (downloaded once into
|
|
39
74
|
`~/.shopnex/app/<version>`, shared with `create-shopnex`). A shop last started by an older version must be started once
|
package/dist/main.mjs
CHANGED
|
@@ -36,11 +36,110 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
36
36
|
mod
|
|
37
37
|
));
|
|
38
38
|
|
|
39
|
+
// <define:__APP_STARTER__>
|
|
40
|
+
var define_APP_STARTER_default;
|
|
41
|
+
var init_define_APP_STARTER = __esm({
|
|
42
|
+
"<define:__APP_STARTER__>"() {
|
|
43
|
+
define_APP_STARTER_default = { "src/server.tsx": `// ShopNex app starter: an embedded app with no database and no OAuth code (@shopnex/app does both).
|
|
44
|
+
//
|
|
45
|
+
// GET / The app's page inside the ShopNex admin
|
|
46
|
+
// POST /api/notes Saves a note in the shop's app data (called by the page's form)
|
|
47
|
+
// POST /webhooks order.created deliveries, checked against the shop's published keys
|
|
48
|
+
import { serve } from '@hono/node-server'
|
|
49
|
+
import { Hono } from 'hono'
|
|
50
|
+
import { HTTPException } from 'hono/http-exception'
|
|
51
|
+
import { createShopnexApp, type ShopContext } from '@shopnex/app'
|
|
52
|
+
import { Button, Card, Form, Inline, Page, Stat, Text, TextField } from '@shopnex/app/ui'
|
|
53
|
+
|
|
54
|
+
const APP_URL = (process.env.APP_URL ?? 'http://localhost:4500').replace(/\\/$/, '')
|
|
55
|
+
// Listens on the URL's port unless the platform sets PORT (behind a proxy the public URL has none)
|
|
56
|
+
const PORT = Number(process.env.PORT || new URL(APP_URL).port || 4500)
|
|
57
|
+
const shopnex = createShopnexApp()
|
|
58
|
+
|
|
59
|
+
const app = new Hono()
|
|
60
|
+
app.route('/', shopnex.routes)
|
|
61
|
+
|
|
62
|
+
async function stats(shop: ShopContext) {
|
|
63
|
+
const [products, orders] = await Promise.all([
|
|
64
|
+
shop.admin.get<{ total: number }>('/products?limit=1'),
|
|
65
|
+
shop.admin.get<{ total: number }>('/orders?limit=1'),
|
|
66
|
+
])
|
|
67
|
+
return { products: products.total, orders: orders.total }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
app.get('/', async (c) => {
|
|
71
|
+
const { shop, ...ctx } = await shopnex.authenticate(c)
|
|
72
|
+
const [s, note] = await Promise.all([stats(ctx), ctx.data.get<string>('note'), subscribe(ctx)])
|
|
73
|
+
return c.html(
|
|
74
|
+
<Page
|
|
75
|
+
title="App starter"
|
|
76
|
+
subtitle={\`Connected to \${shop.name}\`}
|
|
77
|
+
actions={
|
|
78
|
+
<Button action="/api/ping" reload variant="secondary">
|
|
79
|
+
Refresh
|
|
80
|
+
</Button>
|
|
81
|
+
}
|
|
82
|
+
>
|
|
83
|
+
<Card title="Your shop">
|
|
84
|
+
<Inline gap={8}>
|
|
85
|
+
<Stat label="Products" value={s.products} />
|
|
86
|
+
<Stat label="Orders" value={s.orders} />
|
|
87
|
+
</Inline>
|
|
88
|
+
<Text tone="subdued">New orders are logged by this app's server (order.created webhook).</Text>
|
|
89
|
+
</Card>
|
|
90
|
+
<Card title="Note" description="Kept in the shop's ShopNex (app data): this app stores nothing itself.">
|
|
91
|
+
<Form action="/api/notes" success="Saved">
|
|
92
|
+
<TextField label="Note" name="note" value={note} multiline />
|
|
93
|
+
<div>
|
|
94
|
+
<Button>Save</Button>
|
|
95
|
+
</div>
|
|
96
|
+
</Form>
|
|
97
|
+
</Card>
|
|
98
|
+
</Page>,
|
|
99
|
+
)
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
app.post('/api/ping', async (c) => {
|
|
103
|
+
await shopnex.authenticate(c)
|
|
104
|
+
return c.json({ message: 'Refreshed' })
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
app.post('/api/notes', async (c) => {
|
|
108
|
+
const { data } = await shopnex.authenticate(c)
|
|
109
|
+
const { note } = await c.req.json<{ note?: string }>()
|
|
110
|
+
await data.set('note', note ?? '')
|
|
111
|
+
return c.json({ ok: true })
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
// Subscribe once per shop (the subscription belongs to the app's installation)
|
|
115
|
+
async function subscribe(shop: ShopContext) {
|
|
116
|
+
const url = \`\${APP_URL}/webhooks\`
|
|
117
|
+
const hooks = await shop.admin.get<{ url: string }[]>('/webhooks')
|
|
118
|
+
if (!hooks.some((h) => h.url === url)) await shop.admin.post('/webhooks', { url, topics: ['order.created'] })
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
app.post('/webhooks', async (c) => {
|
|
122
|
+
const { event, shop } = await shopnex.verifyWebhook<{ orderNumber?: number }>(c)
|
|
123
|
+
console.log(\`[webhook] \${shop.instance} shop \${shop.shopId}: \${event.type}\`, event.data.orderNumber ?? '')
|
|
124
|
+
return c.body(null, 204)
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
app.onError((error, c) => {
|
|
128
|
+
if (error instanceof HTTPException) return error.getResponse()
|
|
129
|
+
console.error(error)
|
|
130
|
+
return c.json({ error: error.message }, 500)
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
serve({ fetch: app.fetch, port: PORT }, () => console.log(\`App starter on \${APP_URL}\`))
|
|
134
|
+
`, ".env.example": "# From your app's page in the marketplace developer dashboard (or Admin \u2192 Apps \u2192 Custom apps). Leave the app's\n# Redirect URLs empty: it's a managed app, installed and opened right in the ShopNex admin.\nSHOPNEX_CLIENT_ID=app_\u2026\nSHOPNEX_APP_KEY=snxk_\u2026\n# Marketplace apps: only serve installs the marketplace knows about (anyone can run a ShopNex instance)\nSHOPNEX_MARKETPLACE_URL=http://localhost:3200\n# Where this app runs: register it as the App URL. It listens on this URL's port; set PORT only when the\n# platform assigns one (behind a proxy the public URL has no port)\nAPP_URL=http://localhost:4500\n", ".gitignore": ".env\n" };
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
|
|
39
138
|
// <define:__PKG__>
|
|
40
139
|
var define_PKG_default;
|
|
41
140
|
var init_define_PKG = __esm({
|
|
42
141
|
"<define:__PKG__>"() {
|
|
43
|
-
define_PKG_default = { version: "0.16.
|
|
142
|
+
define_PKG_default = { version: "0.16.1", engines: { node: ">=22.22.0" } };
|
|
44
143
|
}
|
|
45
144
|
});
|
|
46
145
|
|
|
@@ -48,6 +147,7 @@ var init_define_PKG = __esm({
|
|
|
48
147
|
var require_src = __commonJS({
|
|
49
148
|
"../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
|
|
50
149
|
"use strict";
|
|
150
|
+
init_define_APP_STARTER();
|
|
51
151
|
init_define_PKG();
|
|
52
152
|
var ESC = "\x1B";
|
|
53
153
|
var CSI = `${ESC}[`;
|
|
@@ -104,6 +204,7 @@ var require_src = __commonJS({
|
|
|
104
204
|
// ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
|
|
105
205
|
var require_picocolors = __commonJS({
|
|
106
206
|
"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
|
|
207
|
+
init_define_APP_STARTER();
|
|
107
208
|
init_define_PKG();
|
|
108
209
|
var p = process || {};
|
|
109
210
|
var argv = p.argv || [];
|
|
@@ -175,16 +276,21 @@ var require_picocolors = __commonJS({
|
|
|
175
276
|
});
|
|
176
277
|
|
|
177
278
|
// src/main.ts
|
|
279
|
+
init_define_APP_STARTER();
|
|
178
280
|
init_define_PKG();
|
|
179
281
|
|
|
180
282
|
// src/cli.ts
|
|
283
|
+
init_define_APP_STARTER();
|
|
181
284
|
init_define_PKG();
|
|
182
|
-
import { readFileSync as
|
|
285
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
286
|
+
import { relative, resolve as resolve5 } from "node:path";
|
|
183
287
|
|
|
184
288
|
// ../../node_modules/.pnpm/@clack+prompts@0.7.0/node_modules/@clack/prompts/dist/index.mjs
|
|
289
|
+
init_define_APP_STARTER();
|
|
185
290
|
init_define_PKG();
|
|
186
291
|
|
|
187
292
|
// ../../node_modules/.pnpm/@clack+core@0.3.5/node_modules/@clack/core/dist/index.mjs
|
|
293
|
+
init_define_APP_STARTER();
|
|
188
294
|
init_define_PKG();
|
|
189
295
|
var import_sisteransi = __toESM(require_src(), 1);
|
|
190
296
|
import { stdin as $, stdout as k } from "node:process";
|
|
@@ -382,6 +488,7 @@ var de = () => {
|
|
|
382
488
|
};
|
|
383
489
|
|
|
384
490
|
// ../cli-core/src/errors.ts
|
|
491
|
+
init_define_APP_STARTER();
|
|
385
492
|
init_define_PKG();
|
|
386
493
|
var UsageError = class extends Error {
|
|
387
494
|
};
|
|
@@ -389,6 +496,7 @@ var UnavailableError = class extends Error {
|
|
|
389
496
|
};
|
|
390
497
|
|
|
391
498
|
// ../cli-core/src/node-version.ts
|
|
499
|
+
init_define_APP_STARTER();
|
|
392
500
|
init_define_PKG();
|
|
393
501
|
var atLeast = (version, minimum) => version.replace(/^v/, "").localeCompare(minimum, void 0, { numeric: true }) >= 0;
|
|
394
502
|
function assertNode(version, enginesRange) {
|
|
@@ -401,6 +509,7 @@ function assertNode(version, enginesRange) {
|
|
|
401
509
|
}
|
|
402
510
|
|
|
403
511
|
// ../cli-core/src/theme.ts
|
|
512
|
+
init_define_APP_STARTER();
|
|
404
513
|
init_define_PKG();
|
|
405
514
|
var import_picocolors2 = __toESM(require_picocolors(), 1);
|
|
406
515
|
var BRAND = [67, 192, 122];
|
|
@@ -409,10 +518,11 @@ var truecolor = import_picocolors2.default.isColorSupported && /^(truecolor|24bi
|
|
|
409
518
|
var brandBadge = (text) => truecolor ? `\x1B[48;2;${BRAND.join(";")}m\x1B[38;2;${ON_BRAND.join(";")}m${text}\x1B[39m\x1B[49m` : import_picocolors2.default.bgGreen(import_picocolors2.default.black(text));
|
|
410
519
|
|
|
411
520
|
// src/args.ts
|
|
521
|
+
init_define_APP_STARTER();
|
|
412
522
|
init_define_PKG();
|
|
413
523
|
import { parseArgs } from "node:util";
|
|
414
524
|
var DEFAULT_PORT = 3e3;
|
|
415
|
-
var COMMANDS = ["migrate-db"];
|
|
525
|
+
var COMMANDS = ["migrate-db", "generate"];
|
|
416
526
|
var options = {
|
|
417
527
|
to: { type: "string" },
|
|
418
528
|
"to-env": { type: "string" },
|
|
@@ -431,13 +541,15 @@ function parse(argv) {
|
|
|
431
541
|
throw new UsageError(`${error.message}
|
|
432
542
|
Run shopnex --help for the options.`);
|
|
433
543
|
}
|
|
434
|
-
if (positionals
|
|
544
|
+
if (positionals[0] !== "generate" && positionals.length > 1)
|
|
545
|
+
throw new UsageError(`Give one command, got: ${positionals.join(" ")}`);
|
|
435
546
|
const port = values.port === void 0 ? DEFAULT_PORT : Number(values.port);
|
|
436
547
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
437
548
|
throw new UsageError(`--port must be a port number (1-65535), got "${values.port}"`);
|
|
438
549
|
}
|
|
439
550
|
return {
|
|
440
551
|
command: positionals[0],
|
|
552
|
+
rest: positionals.slice(1),
|
|
441
553
|
to: values.to,
|
|
442
554
|
toEnv: values["to-env"],
|
|
443
555
|
dir: values.dir ?? ".",
|
|
@@ -447,42 +559,136 @@ Run shopnex --help for the options.`);
|
|
|
447
559
|
};
|
|
448
560
|
}
|
|
449
561
|
|
|
562
|
+
// src/generate.ts
|
|
563
|
+
init_define_APP_STARTER();
|
|
564
|
+
init_define_PKG();
|
|
565
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
566
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
567
|
+
var KINDS = ["app"];
|
|
568
|
+
var STARTER_FILES = ["src/server.tsx", ".env.example", ".gitignore"];
|
|
569
|
+
var starterFile = (path) => typeof define_APP_STARTER_default !== "undefined" ? define_APP_STARTER_default[path] ?? "" : readFileSync(new URL(`../../../templates/app-starter/${path}`, import.meta.url), "utf8");
|
|
570
|
+
function checkName(name) {
|
|
571
|
+
if (!name) throw new UsageError("Give the app a name: shopnex generate app <name>");
|
|
572
|
+
if (!/^[a-z0-9][a-z0-9._-]*$/.test(basename(name))) {
|
|
573
|
+
throw new UsageError(`"${name}" is not a usable app name: use lowercase letters, numbers, - and _.`);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
var title = (name) => {
|
|
577
|
+
const words = basename(name).replace(/[-_.]+/g, " ");
|
|
578
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
579
|
+
};
|
|
580
|
+
function appFiles(name, version) {
|
|
581
|
+
const id = basename(name);
|
|
582
|
+
const files = {};
|
|
583
|
+
for (const path of STARTER_FILES) files[path] = starterFile(path);
|
|
584
|
+
files["src/server.tsx"] = files["src/server.tsx"].replaceAll("App starter", title(name));
|
|
585
|
+
files["package.json"] = JSON.stringify(
|
|
586
|
+
{
|
|
587
|
+
name: id,
|
|
588
|
+
private: true,
|
|
589
|
+
type: "module",
|
|
590
|
+
scripts: {
|
|
591
|
+
dev: "tsx watch --env-file-if-exists=.env src/server.tsx",
|
|
592
|
+
start: "tsx --env-file-if-exists=.env src/server.tsx",
|
|
593
|
+
typecheck: "tsc"
|
|
594
|
+
},
|
|
595
|
+
dependencies: { "@hono/node-server": "^2.1.6", "@shopnex/app": `^${version}`, hono: "^4.13.17" },
|
|
596
|
+
devDependencies: { "@types/node": "^22.20.5", tsx: "^4.23.15", typescript: "5.9.3" }
|
|
597
|
+
},
|
|
598
|
+
null,
|
|
599
|
+
2
|
|
600
|
+
) + "\n";
|
|
601
|
+
files["tsconfig.json"] = JSON.stringify(
|
|
602
|
+
{
|
|
603
|
+
compilerOptions: {
|
|
604
|
+
target: "ES2022",
|
|
605
|
+
lib: ["ES2022", "DOM"],
|
|
606
|
+
module: "ESNext",
|
|
607
|
+
moduleResolution: "Bundler",
|
|
608
|
+
strict: true,
|
|
609
|
+
noUncheckedIndexedAccess: true,
|
|
610
|
+
esModuleInterop: true,
|
|
611
|
+
skipLibCheck: true,
|
|
612
|
+
isolatedModules: true,
|
|
613
|
+
noEmit: true,
|
|
614
|
+
jsx: "react-jsx",
|
|
615
|
+
jsxImportSource: "hono/jsx",
|
|
616
|
+
types: ["node"]
|
|
617
|
+
},
|
|
618
|
+
include: ["src"]
|
|
619
|
+
},
|
|
620
|
+
null,
|
|
621
|
+
2
|
|
622
|
+
) + "\n";
|
|
623
|
+
files["README.md"] = `# ${title(name)}
|
|
624
|
+
|
|
625
|
+
A ShopNex app, made with \`npx shopnex generate app ${id}\`.
|
|
626
|
+
|
|
627
|
+
## Run it
|
|
628
|
+
|
|
629
|
+
1. \`cp .env.example .env\`, then fill in \`SHOPNEX_CLIENT_ID\` and \`SHOPNEX_APP_KEY\` from your app's page in the
|
|
630
|
+
marketplace developer dashboard (or Admin \u2192 Apps \u2192 Custom apps).
|
|
631
|
+
2. \`pnpm install\` (or npm, yarn), then \`pnpm dev\`.
|
|
632
|
+
3. Register \`http://localhost:4500\` as the App URL, install the app from the admin, and open it there.
|
|
633
|
+
|
|
634
|
+
\`src/server.tsx\` is the whole app: a page inside the admin, an endpoint that saves a note in the shop's app data,
|
|
635
|
+
and an \`order.created\` webhook.
|
|
636
|
+
`;
|
|
637
|
+
return files;
|
|
638
|
+
}
|
|
639
|
+
function generateApp({ name, dir, version }) {
|
|
640
|
+
checkName(name);
|
|
641
|
+
const folder = resolve(existsSync(join(dir, ".env")) ? join(dir, "apps") : dir, name);
|
|
642
|
+
if (existsSync(folder) && readdirSync(folder).length > 0) {
|
|
643
|
+
throw new UsageError(`${folder} is not empty. Pick another name, or empty the folder.`);
|
|
644
|
+
}
|
|
645
|
+
for (const [path, content] of Object.entries(appFiles(name, version))) {
|
|
646
|
+
const file = join(folder, path);
|
|
647
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
648
|
+
writeFileSync(file, content);
|
|
649
|
+
}
|
|
650
|
+
return folder;
|
|
651
|
+
}
|
|
652
|
+
|
|
450
653
|
// src/migrate-db.ts
|
|
654
|
+
init_define_APP_STARTER();
|
|
451
655
|
init_define_PKG();
|
|
452
|
-
import { cpSync, existsSync as
|
|
453
|
-
import { join as
|
|
656
|
+
import { cpSync, existsSync as existsSync4, readdirSync as readdirSync3, rmSync as rmSync2 } from "node:fs";
|
|
657
|
+
import { join as join5, resolve as resolve4 } from "node:path";
|
|
454
658
|
|
|
455
659
|
// ../cli-core/src/bundle.ts
|
|
660
|
+
init_define_APP_STARTER();
|
|
456
661
|
init_define_PKG();
|
|
457
662
|
import { createHash } from "node:crypto";
|
|
458
663
|
import {
|
|
459
664
|
createWriteStream,
|
|
460
|
-
existsSync,
|
|
461
|
-
mkdirSync,
|
|
665
|
+
existsSync as existsSync2,
|
|
666
|
+
mkdirSync as mkdirSync2,
|
|
462
667
|
mkdtempSync,
|
|
463
|
-
readdirSync,
|
|
464
|
-
readFileSync,
|
|
668
|
+
readdirSync as readdirSync2,
|
|
669
|
+
readFileSync as readFileSync2,
|
|
465
670
|
renameSync,
|
|
466
671
|
rmSync
|
|
467
672
|
} from "node:fs";
|
|
468
|
-
import { join as
|
|
673
|
+
import { join as join3 } from "node:path";
|
|
469
674
|
import { spawnSync } from "node:child_process";
|
|
470
675
|
import { Readable, Transform } from "node:stream";
|
|
471
676
|
import { pipeline } from "node:stream/promises";
|
|
472
677
|
|
|
473
678
|
// ../cli-core/src/paths.ts
|
|
679
|
+
init_define_APP_STARTER();
|
|
474
680
|
init_define_PKG();
|
|
475
681
|
import { homedir } from "node:os";
|
|
476
|
-
import { join, resolve } from "node:path";
|
|
477
|
-
var appCacheDir = () => process.env.SHOPNEX_APP_DIR ??
|
|
682
|
+
import { join as join2, resolve as resolve2 } from "node:path";
|
|
683
|
+
var appCacheDir = () => process.env.SHOPNEX_APP_DIR ?? join2(homedir(), ".shopnex", "app");
|
|
478
684
|
|
|
479
685
|
// ../cli-core/src/bundle.ts
|
|
480
686
|
var isEdge = (version) => /-edge\./.test(version);
|
|
481
687
|
var bundleName = (version) => `shopnex-v${version}-node.tgz`;
|
|
482
688
|
var bundleUrl = (version) => process.env.SHOPNEX_BUNDLE_URL ?? (isEdge(version) ? "https://github.com/shopnex-ai/shopnex/releases/download/edge/shopnex-edge-node.tgz" : `https://github.com/shopnex-ai/shopnex/releases/download/v${version}/${bundleName(version)}`);
|
|
483
|
-
var bundleDir = (key) =>
|
|
484
|
-
var isInstalled = (key) =>
|
|
485
|
-
var installedEdges = () =>
|
|
689
|
+
var bundleDir = (key) => join3(appCacheDir(), key);
|
|
690
|
+
var isInstalled = (key) => existsSync2(join3(bundleDir(key), "manifest.json"));
|
|
691
|
+
var installedEdges = () => existsSync2(appCacheDir()) ? readdirSync2(appCacheDir()).filter((name) => /^edge-[0-9a-f]{12}$/.test(name)) : [];
|
|
486
692
|
async function get(url, what, version, cli) {
|
|
487
693
|
let response;
|
|
488
694
|
try {
|
|
@@ -525,7 +731,7 @@ async function download(response, file, onProgress) {
|
|
|
525
731
|
async function resolveBundle({ version, cli = "create-shopnex" }) {
|
|
526
732
|
const edge = isEdge(version);
|
|
527
733
|
if (!edge && isInstalled(version)) return bundleDir(version);
|
|
528
|
-
|
|
734
|
+
mkdirSync2(appCacheDir(), { recursive: true });
|
|
529
735
|
const spinner = de();
|
|
530
736
|
const animate = Boolean(process.stdout.isTTY);
|
|
531
737
|
const say = (message) => animate ? spinner.message(message) : void 0;
|
|
@@ -545,8 +751,8 @@ async function resolveBundle({ version, cli = "create-shopnex" }) {
|
|
|
545
751
|
}
|
|
546
752
|
const label = edge ? "the latest edge build" : `ShopNex ${version}`;
|
|
547
753
|
say(`Downloading ${label}`);
|
|
548
|
-
work = mkdtempSync(
|
|
549
|
-
const file =
|
|
754
|
+
work = mkdtempSync(join3(appCacheDir(), `${key}.tmp-`));
|
|
755
|
+
const file = join3(work, "bundle.tgz");
|
|
550
756
|
const actual = await download(
|
|
551
757
|
await get(url, "ShopNex", version, cli),
|
|
552
758
|
file,
|
|
@@ -558,14 +764,14 @@ async function resolveBundle({ version, cli = "create-shopnex" }) {
|
|
|
558
764
|
);
|
|
559
765
|
}
|
|
560
766
|
say("Unpacking");
|
|
561
|
-
const unpacked =
|
|
562
|
-
|
|
767
|
+
const unpacked = join3(work, "app");
|
|
768
|
+
mkdirSync2(unpacked);
|
|
563
769
|
const tar = spawnSync("tar", ["-xzf", file, "-C", unpacked], { encoding: "utf8" });
|
|
564
770
|
if (tar.error || tar.status !== 0) {
|
|
565
771
|
throw new UnavailableError(`Could not unpack the download with tar: ${tar.error?.message ?? tar.stderr.trim()}`);
|
|
566
772
|
}
|
|
567
|
-
const manifestFile =
|
|
568
|
-
const manifest =
|
|
773
|
+
const manifestFile = join3(unpacked, "manifest.json");
|
|
774
|
+
const manifest = existsSync2(manifestFile) ? JSON.parse(readFileSync2(manifestFile, "utf8")) : void 0;
|
|
569
775
|
if (edge ? !manifest : manifest?.version !== version) {
|
|
570
776
|
throw new UnavailableError(
|
|
571
777
|
`The download is not ShopNex ${version} (its manifest says ${manifest?.version ?? "nothing"}).`
|
|
@@ -586,10 +792,11 @@ async function resolveBundle({ version, cli = "create-shopnex" }) {
|
|
|
586
792
|
}
|
|
587
793
|
|
|
588
794
|
// ../cli-core/src/env.ts
|
|
795
|
+
init_define_APP_STARTER();
|
|
589
796
|
init_define_PKG();
|
|
590
797
|
import { randomBytes } from "node:crypto";
|
|
591
|
-
import { existsSync as
|
|
592
|
-
import { isAbsolute, join as
|
|
798
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, appendFileSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
799
|
+
import { isAbsolute, join as join4, resolve as resolve3 } from "node:path";
|
|
593
800
|
import { parseEnv } from "node:util";
|
|
594
801
|
var DEFAULT_DATABASE_URL = "pglite:./.pglite";
|
|
595
802
|
var template = (secret) => `# ShopNex: the settings of this shop. Edit, then start it again.
|
|
@@ -607,26 +814,26 @@ SHOPNEX_SECRET=${secret}
|
|
|
607
814
|
var resolveDatabaseUrl = (url, shopDir) => {
|
|
608
815
|
if (!url.startsWith("pglite:")) return url;
|
|
609
816
|
const path = url.slice("pglite:".length);
|
|
610
|
-
return isAbsolute(path) ? url : `pglite:${
|
|
817
|
+
return isAbsolute(path) ? url : `pglite:${resolve3(shopDir, path)}`;
|
|
611
818
|
};
|
|
612
819
|
var redactUrl = (url) => url.replace(/\/\/([^:@/]+):[^@/]*@/, "//$1:***@");
|
|
613
820
|
function loadShopEnv(shopDir, { write }) {
|
|
614
|
-
const file =
|
|
615
|
-
const exists =
|
|
616
|
-
const { DATABASE_URL, SHOPNEX_SECRET, ...rest } = exists ? parseEnv(
|
|
821
|
+
const file = join4(shopDir, ".env");
|
|
822
|
+
const exists = existsSync3(file);
|
|
823
|
+
const { DATABASE_URL, SHOPNEX_SECRET, ...rest } = exists ? parseEnv(readFileSync3(file, "utf8")) : {};
|
|
617
824
|
const secret = SHOPNEX_SECRET?.trim() || (write ? randomBytes(32).toString("hex") : "");
|
|
618
825
|
const databaseUrl = DATABASE_URL?.trim() || DEFAULT_DATABASE_URL;
|
|
619
826
|
if (write) {
|
|
620
827
|
if (!exists) {
|
|
621
|
-
|
|
622
|
-
|
|
828
|
+
mkdirSync3(shopDir, { recursive: true });
|
|
829
|
+
writeFileSync2(file, template(secret), { mode: 384 });
|
|
623
830
|
} else {
|
|
624
831
|
const missing = [
|
|
625
832
|
DATABASE_URL?.trim() ? "" : `DATABASE_URL=${DEFAULT_DATABASE_URL}`,
|
|
626
833
|
SHOPNEX_SECRET?.trim() ? "" : `SHOPNEX_SECRET=${secret}`
|
|
627
834
|
].filter(Boolean);
|
|
628
835
|
if (missing.length)
|
|
629
|
-
appendFileSync(file, `${
|
|
836
|
+
appendFileSync(file, `${readFileSync3(file, "utf8").endsWith("\n") ? "" : "\n"}${missing.join("\n")}
|
|
630
837
|
`);
|
|
631
838
|
}
|
|
632
839
|
}
|
|
@@ -638,13 +845,13 @@ function switchDatabaseUrl(file, url, now = /* @__PURE__ */ new Date()) {
|
|
|
638
845
|
"The database address has a space, #, quote or backtick in it: percent-encode those characters."
|
|
639
846
|
);
|
|
640
847
|
}
|
|
641
|
-
const text =
|
|
848
|
+
const text = readFileSync3(file, "utf8");
|
|
642
849
|
const line = /^[ \t]*DATABASE_URL[ \t]*=.*$/m;
|
|
643
850
|
const old = line.exec(text)?.[0].trim();
|
|
644
851
|
const stamp2 = now.toISOString().slice(0, 10);
|
|
645
852
|
const replacement = `${old ? `# ${redactUrl(old)} (before shopnex migrate-db, ${stamp2})
|
|
646
853
|
` : ""}DATABASE_URL=${url}`;
|
|
647
|
-
|
|
854
|
+
writeFileSync2(
|
|
648
855
|
file,
|
|
649
856
|
old ? text.replace(line, () => replacement) : `${text}${text.endsWith("\n") ? "" : "\n"}${replacement}
|
|
650
857
|
`
|
|
@@ -652,30 +859,32 @@ function switchDatabaseUrl(file, url, now = /* @__PURE__ */ new Date()) {
|
|
|
652
859
|
}
|
|
653
860
|
|
|
654
861
|
// ../cli-core/src/ports.ts
|
|
862
|
+
init_define_APP_STARTER();
|
|
655
863
|
init_define_PKG();
|
|
656
864
|
import { connect } from "node:net";
|
|
657
865
|
function portInUse(port) {
|
|
658
|
-
const tryHost = (host) => new Promise((
|
|
866
|
+
const tryHost = (host) => new Promise((resolve6) => {
|
|
659
867
|
const socket = connect({ port, host });
|
|
660
868
|
socket.setTimeout(500);
|
|
661
|
-
socket.once("connect", () => (socket.destroy(),
|
|
662
|
-
socket.once("timeout", () => (socket.destroy(),
|
|
663
|
-
socket.once("error", () =>
|
|
869
|
+
socket.once("connect", () => (socket.destroy(), resolve6(true)));
|
|
870
|
+
socket.once("timeout", () => (socket.destroy(), resolve6(false)));
|
|
871
|
+
socket.once("error", () => resolve6(false));
|
|
664
872
|
});
|
|
665
873
|
return Promise.all([tryHost("127.0.0.1"), tryHost("::1")]).then((used) => used.some(Boolean));
|
|
666
874
|
}
|
|
667
875
|
|
|
668
876
|
// src/run-once.ts
|
|
877
|
+
init_define_APP_STARTER();
|
|
669
878
|
init_define_PKG();
|
|
670
879
|
import { spawn } from "node:child_process";
|
|
671
880
|
function runOnce({ script, cwd, env }) {
|
|
672
|
-
return new Promise((
|
|
881
|
+
return new Promise((resolve6) => {
|
|
673
882
|
const child = spawn(process.execPath, [script], { cwd, env: { ...process.env, ...env }, stdio: "inherit" });
|
|
674
883
|
child.on("error", (error) => {
|
|
675
884
|
console.error(`Could not start ${script}: ${error.message}`);
|
|
676
|
-
|
|
885
|
+
resolve6(1);
|
|
677
886
|
});
|
|
678
|
-
child.on("exit", (code, signal) =>
|
|
887
|
+
child.on("exit", (code, signal) => resolve6(code ?? (signal ? 1 : 0)));
|
|
679
888
|
});
|
|
680
889
|
}
|
|
681
890
|
|
|
@@ -693,14 +902,14 @@ function targetUrl({ to, toEnv }) {
|
|
|
693
902
|
}
|
|
694
903
|
var stamp = (now) => now.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
|
|
695
904
|
var appsWithData = (shopDir) => {
|
|
696
|
-
const apps =
|
|
697
|
-
if (!
|
|
698
|
-
return
|
|
905
|
+
const apps = join5(shopDir, "apps");
|
|
906
|
+
if (!existsSync4(apps)) return [];
|
|
907
|
+
return readdirSync3(apps).filter((name) => existsSync4(join5(apps, name, ".pglite")));
|
|
699
908
|
};
|
|
700
909
|
async function migrateDb(options2) {
|
|
701
910
|
const target = targetUrl(options2);
|
|
702
|
-
const shopDir =
|
|
703
|
-
if (!
|
|
911
|
+
const shopDir = resolve4(process.cwd(), options2.dir);
|
|
912
|
+
if (!existsSync4(join5(shopDir, ".env"))) {
|
|
704
913
|
throw new UsageError(
|
|
705
914
|
`${shopDir} is not a ShopNex shop (there is no .env in it). Go into the shop's folder, or give it with --dir.`
|
|
706
915
|
);
|
|
@@ -710,7 +919,7 @@ async function migrateDb(options2) {
|
|
|
710
919
|
throw new UsageError(`This shop already uses PostgreSQL (${redactUrl(env.databaseUrl)}): nothing to move.`);
|
|
711
920
|
}
|
|
712
921
|
const data = env.databaseUrl.slice("pglite:".length);
|
|
713
|
-
if (data === "memory" || !
|
|
922
|
+
if (data === "memory" || !existsSync4(data)) {
|
|
714
923
|
throw new UsageError(`There is no data to move: ${data} does not exist. Start the shop once first.`);
|
|
715
924
|
}
|
|
716
925
|
if (await portInUse(options2.port)) {
|
|
@@ -719,8 +928,8 @@ async function migrateDb(options2) {
|
|
|
719
928
|
);
|
|
720
929
|
}
|
|
721
930
|
const root = await resolveBundle({ version: options2.version, cli: "shopnex" });
|
|
722
|
-
const script =
|
|
723
|
-
if (!
|
|
931
|
+
const script = join5(root, "admin", "migrate-db.mjs");
|
|
932
|
+
if (!existsSync4(script)) {
|
|
724
933
|
throw new UnavailableError(`ShopNex ${options2.version} cannot move a database yet (its build has no migrate-db).`);
|
|
725
934
|
}
|
|
726
935
|
const backup = `${data}.bak-${stamp(/* @__PURE__ */ new Date())}`;
|
|
@@ -728,11 +937,11 @@ async function migrateDb(options2) {
|
|
|
728
937
|
f2.info(`A copy of the current data is kept in ${backup} until the move has worked`);
|
|
729
938
|
const code = await runOnce({
|
|
730
939
|
script,
|
|
731
|
-
cwd:
|
|
940
|
+
cwd: join5(root, "admin"),
|
|
732
941
|
env: {
|
|
733
942
|
SOURCE_DATABASE_URL: env.databaseUrl,
|
|
734
943
|
TARGET_DATABASE_URL: target,
|
|
735
|
-
SHOPNEX_MIGRATIONS_DIR:
|
|
944
|
+
SHOPNEX_MIGRATIONS_DIR: join5(root, "migrations")
|
|
736
945
|
}
|
|
737
946
|
});
|
|
738
947
|
if (code !== 0) {
|
|
@@ -752,7 +961,7 @@ async function migrateDb(options2) {
|
|
|
752
961
|
}
|
|
753
962
|
|
|
754
963
|
// src/cli.ts
|
|
755
|
-
var pkg = typeof define_PKG_default !== "undefined" ? define_PKG_default : JSON.parse(
|
|
964
|
+
var pkg = typeof define_PKG_default !== "undefined" ? define_PKG_default : JSON.parse(readFileSync4(new URL("../package.json", import.meta.url), "utf8"));
|
|
756
965
|
var HELP = `shopnex ${pkg.version}: look after a ShopNex shop made with create-shopnex.
|
|
757
966
|
|
|
758
967
|
Usage
|
|
@@ -760,6 +969,8 @@ Usage
|
|
|
760
969
|
|
|
761
970
|
Commands
|
|
762
971
|
migrate-db move the shop's data from the embedded database to PostgreSQL
|
|
972
|
+
generate app <name>
|
|
973
|
+
make a new ShopNex app in apps/<name> of the shop folder (or ./<name> outside one)
|
|
763
974
|
|
|
764
975
|
Options
|
|
765
976
|
--to <url> migrate-db: the PostgreSQL address, an empty database (postgres://user:password@host:5432/shopnex)
|
|
@@ -781,6 +992,17 @@ async function run(argv) {
|
|
|
781
992
|
}
|
|
782
993
|
assertNode(process.versions.node, pkg.engines.node);
|
|
783
994
|
oe(brandBadge(` shopnex ${options2.command} ${pkg.version} `));
|
|
995
|
+
if (options2.command === "generate") {
|
|
996
|
+
const [kind, name, ...extra] = options2.rest;
|
|
997
|
+
if (!KINDS.includes(kind) || extra.length > 0) {
|
|
998
|
+
throw new UsageError(`Usage: shopnex generate app <name> (kinds: ${KINDS.join(", ")}).`);
|
|
999
|
+
}
|
|
1000
|
+
const folder = generateApp({ name, dir: resolve5(options2.dir), version: pkg.version });
|
|
1001
|
+
return void $e(
|
|
1002
|
+
`Made ${folder}
|
|
1003
|
+
Next: cd ${relative(process.cwd(), folder) || "."}, copy .env.example to .env, then pnpm install and pnpm dev.`
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
784
1006
|
await migrateDb({ ...options2, version: pkg.version });
|
|
785
1007
|
}
|
|
786
1008
|
async function main(argv) {
|
package/package.json
CHANGED