orionplace-react 0.1.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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +242 -0
  3. package/bin/orionplace-react.mjs +101 -0
  4. package/package.json +56 -0
  5. package/runtime/marketplace.d.mts +22 -0
  6. package/runtime/marketplace.mjs +211 -0
  7. package/src/project-readme.mjs +341 -0
  8. package/src/setup.mjs +250 -0
  9. package/src/update.mjs +36 -0
  10. package/src/validation.mjs +27 -0
  11. package/templates/app/api/[...orionplace]/route.ts +14 -0
  12. package/templates/app/globals.css +10 -0
  13. package/templates/app/layout.tsx +25 -0
  14. package/templates/app/page.module.css +133 -0
  15. package/templates/app/page.tsx +80 -0
  16. package/templates/hooks/useOrionplaceAppLoad.ts +34 -0
  17. package/templates/interfaces/orionplace/apiBase/TMethod.ts +1 -0
  18. package/templates/interfaces/orionplace/appBase/IAppLoad.ts +15 -0
  19. package/templates/interfaces/orionplace/appBase/IAppLoadCommon.ts +54 -0
  20. package/templates/interfaces/orionplace/appBase/IApploadUserProfile.ts +13 -0
  21. package/templates/interfaces/orionplace/appBase/IForm.ts +21 -0
  22. package/templates/interfaces/orionplace/appBase/ISEO.ts +21 -0
  23. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonBanner.ts +11 -0
  24. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonContact.ts +8 -0
  25. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonCurrency.ts +15 -0
  26. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonEvents.ts +18 -0
  27. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonLocale.ts +14 -0
  28. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonLogos.ts +6 -0
  29. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonPath.ts +22 -0
  30. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonSEO.ts +13 -0
  31. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonSocial.ts +15 -0
  32. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonTariff.ts +7 -0
  33. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonUnit.ts +12 -0
  34. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonVariables.ts +7 -0
  35. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonVisualSettings.ts +11 -0
  36. package/templates/interfaces/orionplace/appBase/appLoadCommon/IAppLoadCommonWalletValue.ts +3 -0
  37. package/templates/interfaces/orionplace/category/ICategory.ts +40 -0
  38. package/templates/interfaces/orionplace/domains/IDomain.ts +13 -0
  39. package/templates/interfaces/orionplace/index.ts +30 -0
  40. package/templates/interfaces/orionplace/products/IProduct.ts +235 -0
  41. package/templates/interfaces/orionplace/shared/IGeoCoordinates.ts +4 -0
  42. package/templates/interfaces/orionplace/shared/ITransformValue.ts +3 -0
  43. package/templates/interfaces/orionplace/state.ts +4 -0
  44. package/templates/interfaces/orionplace/subscribeOptions/ISubscribeOption.ts +9 -0
  45. package/templates/interfaces/orionplace/subscribeTariff/ISubscribeTariff.ts +46 -0
  46. package/templates/interfaces/orionplace/subscribes/ISubscribe.ts +28 -0
  47. package/templates/interfaces/orionplace/transport.ts +30 -0
  48. package/templates/lib/orionplace/appLoadClient.ts +33 -0
  49. package/templates/lib/orionplace/appLoadResult.ts +56 -0
  50. package/templates/lib/orionplace/appLoadServer.ts +72 -0
  51. package/templates/lib/orionplace/domain.ts +16 -0
  52. package/templates/providers/OrionplaceProvider.tsx +39 -0
  53. package/templates/proxy.ts +17 -0
  54. package/templates/stores/orionplace.ts +119 -0
@@ -0,0 +1,341 @@
1
+ export function projectReadme(settings, base = '') {
2
+ const frontend = settings.frontend || 'shop.example.com';
3
+ const backend = settings.backend || 'https://your-project.orionplace.app/api';
4
+ return `# Your Orionplace React integration
5
+
6
+ This folder contains the integration source for your Next.js storefront.
7
+ Your personal backend API is provided in your account at https://orionmarket.place.
8
+ You can change that backend domain in your account, then update this project.
9
+
10
+ ## Quick start from zero
11
+
12
+ Install Node.js 20.9 or newer (including npm). Run these commands from the folder
13
+ where you want to create a new project; no existing Next.js project is needed:
14
+
15
+ \`\`\`bash
16
+ npx --yes orionplace-react init my-marketplace
17
+ cd my-marketplace
18
+ npm install
19
+ npx orionplace-react set backend your-project.orionplace.app
20
+ npx orionplace-react add frontend shop.example.com
21
+ npm run dev
22
+ \`\`\`
23
+
24
+ Replace \`your-project.orionplace.app\` with the personal backend domain shown in
25
+ your profile at [orionmarket.place](https://orionmarket.place), and
26
+ \`shop.example.com\` with your storefront domain. The first frontend also becomes
27
+ the local MIMIC domain.
28
+
29
+ Open the local URL printed by Next.js (normally http://localhost:3000). The starter
30
+ should show \`Loaded\` in its AppLoad state section. If it shows \`Failed\`, check
31
+ the domain mapping and backend response before building pages.
32
+
33
+ This project is already generated. To configure or run it, use the following
34
+ sections from its root directory; do not create another project inside it.
35
+
36
+ ## Current setup
37
+
38
+ - Frontend domains: ${settings.frontends?.length ? settings.frontends.map(domain => '\`' + domain + '\`').join(', ') : 'not configured yet'}
39
+ - Local MIMIC domain: \`${settings.frontend || 'empty'}\`
40
+ - Personal API: \`${settings.backend || 'not configured yet'}\`
41
+
42
+ Set or change these values from the project root:
43
+
44
+ \`\`\`bash
45
+ npx orionplace-react set backend ${backend}
46
+ npx orionplace-react add frontend ${frontend}
47
+ npx orionplace-react add frontend www.${frontend}
48
+ npx orionplace-react remove frontend www.${frontend}
49
+ \`\`\`
50
+
51
+ Set the backend or add a frontend first; either order works. Each frontend has its
52
+ own \`sitemaps/<domain>.cfg\` mapping to your personal API. Adding a domain again
53
+ is safe. Changing the backend updates every CLI-managed frontend mapping.
54
+
55
+ MIMIC is empty in a new project: \`MIMIC_FRONT_DOMAIN=""\`. Setting the backend
56
+ alone leaves it empty. The first added frontend sets MIMIC; adding more domains
57
+ preserves that choice.
58
+
59
+ Use \`npx orionplace-react set mimic <domain>\` to select an already-added frontend
60
+ for localhost. It changes MIMIC without editing domain mappings. Add an unknown
61
+ domain with \`add frontend\` first. The legacy \`set frontend\` shortcut still
62
+ adds and selects a frontend.
63
+
64
+ \`\`\`bash
65
+ npx orionplace-react help
66
+ npx orionplace-react set mimic ${frontend}
67
+ \`\`\`
68
+
69
+ Removing a frontend deletes only its unchanged generated \`.cfg\` file. If it was
70
+ the selected MIMIC domain, the first remaining domain takes its place. Removing
71
+ the last frontend clears MIMIC; add a frontend again before making API requests.
72
+ Unknown or manually edited mappings are not removed automatically.
73
+
74
+ Restart a running development server after changing domains so Next.js reloads
75
+ \`.env\`. Production reads domain files on each request; restart or reload the
76
+ process environment when changing MIMIC. DNS, TLS and hosting-proxy settings must
77
+ also cover each public frontend domain. Existing unrelated environment variables
78
+ and Next.js configuration are preserved.
79
+
80
+ ## Files you can read and customize
81
+
82
+ | File | Purpose |
83
+ | --- | --- |
84
+ | \`runtime/marketplace.mjs\` | Domain lookup, configuration validation, API transport and cookies. |
85
+ | \`runtime/marketplace.d.mts\` | Types for the gateway functions used by your TypeScript source. |
86
+ | \`settings.json\` | The CLI's frontend list, local MIMIC domain and personal backend; not a secret store. |
87
+ | \`../${base}app/api/[...orionplace]/route.ts\` | The route handler serving \`/api/...\` from your project. |
88
+ | \`../${base}proxy.ts\` | Marks personalized pages private and varies them by storefront domain. |
89
+ | \`../sitemaps/${frontend}.cfg\` | The backend URL used for this frontend domain. |
90
+ | \`../.env\` | Local MIMIC setting; keep secrets out of version control. |
91
+
92
+ You can edit these files; subsequent setup runs preserve customized source and
93
+ this README. The CLI refuses to overwrite an unknown or manually changed domain
94
+ mapping, and never replaces your own layout, page or middleware.
95
+
96
+ ## How requests reach your personal API
97
+
98
+ The trusted hosting proxy supplies the public domain through \`X-Front-Domain\`,
99
+ \`X-Forwarded-Host\`, or \`Host\`, in that order. On localhost,
100
+ \`MIMIC_FRONT_DOMAIN\` supplies the domain instead. A known public domain takes
101
+ priority over MIMIC; an unconfigured public domain returns \`503\`.
102
+
103
+ The domain file is read for each request. The gateway preserves the request method,
104
+ query, body, authorization and cookies. Backend HTTP status codes are preserved.
105
+ Backend cookie domains are removed so cookies belong to the active frontend.
106
+ Responses are not cached by this gateway. Network failures return \`502\`.
107
+
108
+ The configuration directory defaults to \`sitemaps\` under the process working
109
+ directory. Set \`SITEMAPS_DIR\` only if you store it elsewhere. Nothing here sets
110
+ a fixed public site URL. Use \`getStorefrontDomain()\` from
111
+ \`${base}lib/orionplace/domain.ts\` when you build canonical URLs or page metadata.
112
+
113
+ ## Start and verify
114
+
115
+ Use Node.js 20.9 or newer. After scaffolding a new project, install dependencies:
116
+
117
+ \`\`\`bash
118
+ npm install
119
+ npm run dev
120
+ \`\`\`
121
+
122
+ In another terminal:
123
+
124
+ \`\`\`bash
125
+ curl -i http://localhost:3000/api/appload \\
126
+ -H 'Content-Type: application/json' \\
127
+ --data '{"ignore_cache":true,"detalize_mode":"light"}'
128
+ \`\`\`
129
+
130
+ Check both the HTTP status and \`form_errors\`. Successful initialization returns
131
+ \`page_data\`; HTTP 200 by itself is insufficient. Documentation and public requests
132
+ do not require a login prompt. Protected actions still require backend permission.
133
+
134
+ ## AppLoad architecture
135
+
136
+ The root layout initializes the marketplace before your page renders. The request
137
+ uses \`POST /api/appload\` with \`detalize_mode: "light"\` and \`ignore_cache: true\`.
138
+ Tenant settings may override these options.
139
+
140
+ | Project file | Responsibility |
141
+ | --- | --- |
142
+ | \`${base}app/layout.tsx\` | Awaits initialization, then passes the snapshot to the provider. |
143
+ | \`${base}lib/orionplace/appLoadServer.ts\` | Server transport: one request per render through \`cache()\`. |
144
+ | \`${base}lib/orionplace/appLoadClient.ts\` | Browser transport for explicit initialize and refresh. |
145
+ | \`${base}lib/orionplace/appLoadResult.ts\` | HTTP, form-error and bootstrap-envelope checks. |
146
+ | \`${base}lib/orionplace/domain.ts\` | The storefront domain selected for the current request. |
147
+ | \`${base}stores/orionplace.ts\` | The typed snapshot, status, errors, merged discovery and selectors. |
148
+ | \`${base}providers/OrionplaceProvider.tsx\` | One store per browser session, hydrated from the server snapshot. |
149
+ | \`${base}hooks/useOrionplaceAppLoad.ts\` | Explicit initialize, refresh and reset actions. |
150
+ | \`${base}interfaces/orionplace/index.ts\` | Response envelope and all nested models. |
151
+
152
+ The server render owns initialization. Rendering a component or calling the hook
153
+ never starts another request, and initialization never opens an authentication
154
+ prompt.
155
+
156
+ ### Read data in a client component
157
+
158
+ \`\`\`tsx
159
+ 'use client';
160
+
161
+ import { useOrionplace } from '../providers/OrionplaceProvider';
162
+ import { selectCurrencies, selectFailure, selectIsReady, selectProducts, selectStatus } from '../stores/orionplace';
163
+
164
+ export function MarketplaceSummary() {
165
+ const isReady = useOrionplace(selectIsReady);
166
+ const status = useOrionplace(selectStatus);
167
+ const failure = useOrionplace(selectFailure);
168
+ const products = useOrionplace(selectProducts);
169
+ const currencies = useOrionplace(selectCurrencies);
170
+
171
+ if (failure) return <p role="alert">Marketplace initialization failed.</p>;
172
+ if (!isReady) return <p role="status">AppLoad: {status}</p>;
173
+ return <p>{products.length} products; {Object.keys(currencies).length} currencies.</p>;
174
+ }
175
+ \`\`\`
176
+
177
+ Select one value at a time. Each selector returns a stable reference, so a
178
+ component re-renders only when its own data changes. This example lives one
179
+ directory below the project root, such as \`${base}components\`; adjust relative
180
+ imports for deeper directories.
181
+
182
+ | Selector | Available data |
183
+ | --- | --- |
184
+ | \`selectResult\` | Response envelope, HTTP status and load time. |
185
+ | \`selectData\` | Complete \`page_data\`, including optional sections. |
186
+ | \`selectInit\` | All initialization settings, banners, events, contacts, SEO, units and other sections. |
187
+ | \`selectProfile\`, \`selectIsAuthenticated\` | Current profile and session state. |
188
+ | \`selectLocales\`, \`selectCurrencies\`, \`selectCatalog\`, \`selectProducts\`, \`selectTariffs\` | Common initial collections. |
189
+ | \`selectPublicEndpoints\`, \`selectAuthenticatedEndpoints\`, \`selectEndpoints\` | Current discovery groups and their combined view. |
190
+ | \`selectIsReady\`, \`selectStatus\`, \`selectFailure\` | Readiness, loading/success/error state and sanitized failure details. |
191
+
192
+ Use \`selectEndpoint(section, name)\` with section and endpoint keys from the
193
+ current response. It returns the endpoint's target, methods and forms, or
194
+ \`undefined\` when unavailable. Full descriptions may be omitted in light mode.
195
+ Discovery describes availability; the backend checks permissions on every call.
196
+
197
+ ### Read data in a server component
198
+
199
+ \`\`\`tsx
200
+ import { getOrionplaceAppLoad } from '../lib/orionplace/appLoadServer';
201
+
202
+ export default async function CatalogPage() {
203
+ const { result, failure } = await getOrionplaceAppLoad();
204
+ if (failure || !result) return <p role="alert">Marketplace initialization failed.</p>;
205
+ const categories = result.response.page_data.init.catalog ?? [];
206
+ return <p>{categories.length} catalog roots.</p>;
207
+ }
208
+ \`\`\`
209
+
210
+ \`getOrionplaceAppLoad()\` is cached per render, so the layout and your page share
211
+ one request. Do not import it from a client component.
212
+
213
+ ### Refresh after a session change
214
+
215
+ \`\`\`tsx
216
+ 'use client';
217
+
218
+ import { useOrionplaceAppLoad } from '../hooks/useOrionplaceAppLoad';
219
+
220
+ export function SessionActions() {
221
+ const { reset, refresh } = useOrionplaceAppLoad();
222
+ async function afterSessionChanged() {
223
+ reset();
224
+ await refresh();
225
+ }
226
+ return <button type="button" onClick={() => void afterSessionChanged()}>Reload marketplace</button>;
227
+ }
228
+ \`\`\`
229
+
230
+ Call this after the session-changing API request has completed. Reset clears the
231
+ profile, initialization and discovery, aborts pending initialization and prevents
232
+ late responses restoring the old session. Refresh replaces the whole snapshot.
233
+ On failure, stale data and permissions remain cleared; the store exposes the error.
234
+
235
+ ### Session and CSRF cookies
236
+
237
+ Session and CSRF cookies travel in HTTP headers, not in the initialization JSON.
238
+ Keep the signed HttpOnly \`sessionid\` opaque: the browser sends it automatically.
239
+ Never log, decode, rewrite or put cookie values in the store or localStorage.
240
+ Read the current \`csrftoken\` for each protected browser action and send it as
241
+ \`X-CSRFToken\` through the same-origin \`/api/\` gateway with credentials enabled.
242
+ Login can rotate the token. The AppLoad loaders handle initialization; they are
243
+ not a general CSRF-aware client for other endpoints.
244
+
245
+ The server render forwards the incoming request's cookies and domain to the same
246
+ gateway, in process. React Server Components cannot write response cookies, so a
247
+ new backend cookie from that render is not relayed to the browser: the browser
248
+ establishes and updates its own session through \`/api/...\` requests. The raw
249
+ \`Set-Cookie\` headers are available as \`cookies\` from \`requestAppLoad()\` if you
250
+ relay them from your own route handler or server action. New response cookies
251
+ never update the current render's request. Never share a cookie jar across visitors.
252
+
253
+ Renew CSRF using \`POST /api/csrf_renew\` with \`{}\`, then re-read the cookie.
254
+ HTTP \`419\` with \`page_data.csrf: false\` means CSRF rejection; a general
255
+ \`403\` can mean permissions or origin rejection. Offer explicit retries for
256
+ mutations. After confirmed login/logout, reset and refresh AppLoad; these actions
257
+ change application data and do not log in/out or delete cookies.
258
+
259
+ [Cookie lifecycle and browser request example](https://orionmarket.place/sandbox/appload/react#session-cookies)
260
+
261
+ ### Rendering, navigation and failures
262
+
263
+ Each server render gets its own request-scoped snapshot; the provider creates one
264
+ store per browser session and hydrates it, so hydration and client navigation do
265
+ not repeat initialization. Concurrent \`load\` calls share one request per store.
266
+
267
+ Failures also survive hydration and navigation. They never open a login modal or
268
+ trigger an automatic retry on every route. Show the error and offer explicit
269
+ reload. Feature components should check \`selectIsReady\` before using required data.
270
+
271
+ Page responses use \`private, no-store\` through \`${base}proxy.ts\`. Do not put
272
+ personalized HTML in shared caches or persist the snapshot in localStorage. The
273
+ debug page displays summaries; account details, keys and backend exception stacks
274
+ are not rendered there.
275
+
276
+ Interfaces cover initialization, discovery/forms, profile and nested models.
277
+ Plugin-defined configuration uses JSON types; interfaces are not full runtime
278
+ validation of every nested field. Existing edited generated source is preserved;
279
+ review and merge newer templates manually where the CLI reports preserved files.
280
+
281
+ ## Update the package and components
282
+
283
+ Run this from your project root whenever you want the latest release:
284
+
285
+ \`\`\`bash
286
+ npx orionplace-react update
287
+ \`\`\`
288
+
289
+ The command fetches the latest CLI, adds new template files, refreshes unchanged
290
+ generated source, updates the package dependency, and runs \`npm install\`.
291
+ It preserves edited files and lists them for manual review. Find their incoming
292
+ versions under \`node_modules/orionplace-react/templates\` or \`runtime\`.
293
+ Domain mappings, domain settings and \`.env\` are preserved. Upstream file removals
294
+ do not delete local source. Restart development or rebuild and redeploy afterward.
295
+
296
+ Use \`npx orionplace-react update --dry-run\` to review changes without modifying
297
+ project files or installed dependencies; downloading the CLI may update npm's
298
+ cache. The alias \`npm run orionplace:update\` performs the same normal update.
299
+ If installation fails after source generation, run \`npm install\` and retry.
300
+
301
+ ## Deploy on your VPS
302
+
303
+ This integration needs a Node.js server and its domain configuration files.
304
+ It does not support static export or edge-only hosting. Deploy the build,
305
+ dependencies, \`sitemaps\`, and your environment configuration together; use an
306
+ absolute \`SITEMAPS_DIR\` when running from another working directory.
307
+
308
+ \`\`\`bash
309
+ npm run build
310
+ HOSTNAME=127.0.0.1 PORT=3000 node --env-file=.env node_modules/next/dist/bin/next start
311
+ \`\`\`
312
+
313
+ The production process explicitly reads \`MIMIC_FRONT_DOMAIN\`. A public domain
314
+ still takes precedence. The Node port must stay private behind your HTTPS proxy.
315
+
316
+ Inside the storefront's HTTPS Nginx server block:
317
+
318
+ \`\`\`nginx
319
+ location / {
320
+ proxy_pass http://127.0.0.1:3000;
321
+ proxy_http_version 1.1;
322
+ proxy_set_header Host $host;
323
+ proxy_set_header X-Forwarded-Host $host;
324
+ proxy_set_header X-Front-Domain $host;
325
+ proxy_set_header X-Forwarded-Proto $scheme;
326
+ proxy_set_header X-Init-Ip $remote_addr;
327
+ proxy_buffering off;
328
+ }
329
+ \`\`\`
330
+
331
+ Here localhost is your frontend process on your VPS. That process selects the
332
+ remote personal API from the domain file. The proxy must overwrite those headers.
333
+ An unknown domain never falls back to another tenant. This setup does not generate
334
+ sitemap XML or add analytics.
335
+
336
+ ## More documentation
337
+
338
+ - [React package installation and domain setup](https://orionmarket.place/sandbox/new-project/react)
339
+ - [AppLoad](https://orionmarket.place/sandbox)
340
+ `;
341
+ }
package/src/setup.mjs ADDED
@@ -0,0 +1,250 @@
1
+ import { readFile, readdir, lstat, mkdir, writeFile, rename, unlink } from 'node:fs/promises';
2
+ import { resolve, dirname, relative, sep, posix } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { backendUrl, frontendDomain } from './validation.mjs';
5
+ import { projectReadme } from './project-readme.mjs';
6
+
7
+ const metadata = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
8
+ const hash = text => createHash('sha256').update(text).digest('hex');
9
+ // Generated files a customer may already own: keep theirs untouched instead of failing.
10
+ const optional = ['app/layout.tsx', 'app/page.tsx', 'app/page.module.css', 'app/globals.css', 'proxy.ts'];
11
+
12
+ async function read(path) {
13
+ try { return await readFile(path, 'utf8'); }
14
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
15
+ }
16
+ async function safePath(root, name) {
17
+ const target = resolve(root, name);
18
+ if (relative(root, target).startsWith('..') || target === root) throw new Error('Invalid generated path');
19
+ let cursor = root;
20
+ for (const piece of relative(root, target).split(sep)) {
21
+ cursor = resolve(cursor, piece);
22
+ try { if ((await lstat(cursor)).isSymbolicLink()) throw new Error(`Refusing symbolic link: ${name}`); }
23
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
24
+ }
25
+ return target;
26
+ }
27
+ async function directoryExists(root, name) {
28
+ try { return (await lstat(resolve(root, name))).isDirectory(); }
29
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
30
+ }
31
+ /** Generated source imports the editable gateway by an explicit relative path. */
32
+ function runtimeImport(name) {
33
+ const from = posix.dirname(name);
34
+ const path = posix.relative(from, 'orionplace/runtime/marketplace.mjs');
35
+ return path.startsWith('.') ? path : `./${path}`;
36
+ }
37
+ const nextConfigTemplate = `import type { NextConfig } from 'next';
38
+
39
+ const nextConfig: NextConfig = {};
40
+
41
+ export default nextConfig;
42
+ `;
43
+ const tsconfigTemplate = {
44
+ compilerOptions: {
45
+ target: 'ES2022', lib: ['dom', 'dom.iterable', 'esnext'], allowJs: true, skipLibCheck: true,
46
+ strict: true, noEmit: true, esModuleInterop: true, module: 'esnext', moduleResolution: 'bundler',
47
+ resolveJsonModule: true, isolatedModules: true, jsx: 'react-jsx', incremental: true,
48
+ plugins: [{ name: 'next' }], paths: { '@/*': ['./*'] },
49
+ },
50
+ include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts', '.next/dev/types/**/*.ts'],
51
+ exclude: ['node_modules'],
52
+ };
53
+ /**
54
+ * Next.js needs no plugin registration: the gateway is a route handler in the
55
+ * project. Only a conflicting /api rewrite or redirect must be resolved first.
56
+ */
57
+ function inspectNextConfig(source) {
58
+ const cleaned = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
59
+ if (/\b(?:rewrites|redirects)\b/.test(cleaned) && /source\s*:\s*['"`]\/api(?:\/|['"`])/.test(cleaned)) {
60
+ throw new Error('Remove the conflicting /api rewrite or redirect from the Next.js configuration: Orionplace handles API routing. No files were changed.');
61
+ }
62
+ if (/\boutput\s*:\s*['"`]export['"`]/.test(cleaned)) {
63
+ throw new Error('Static export cannot read domain files. Use the default Node.js server output. No files were changed.');
64
+ }
65
+ }
66
+ function updateEnvironment(source, domain) {
67
+ const lines = (source || '').split(/\r?\n/);
68
+ let updated = false;
69
+ const result = lines.flatMap(line => {
70
+ if (!/^\s*(?:export\s+)?MIMIC_FRONT_DOMAIN\s*=/.test(line)) return [line];
71
+ if (updated) return [];
72
+ updated = true;
73
+ return [`MIMIC_FRONT_DOMAIN="${domain}"`];
74
+ });
75
+ if (!updated) result.push(`MIMIC_FRONT_DOMAIN="${domain}"`);
76
+ return result.join('\n').replace(/^\n/, '').replace(/\n*$/, '\n');
77
+ }
78
+
79
+ export async function setupProject({ cwd = process.cwd(), action = 'set', field, value, dryRun = false } = {}) {
80
+ if (!['set', 'add', 'remove', 'update'].includes(action) ||
81
+ (['add', 'remove'].includes(action) && field !== 'frontend') || (action === 'update' && field)) {
82
+ throw new Error('Use set backend, add frontend, remove frontend, set mimic, or set frontend.');
83
+ }
84
+ const root = resolve(cwd);
85
+ const setting = field === 'backend' ? backendUrl(value) : ['frontend', 'mimic'].includes(field) ? frontendDomain(value) : null;
86
+ if (field && !setting) throw new Error('Choose backend, frontend, or mimic.');
87
+ const names = ['package.json', 'next.config.ts', 'next.config.js', 'next.config.mjs', 'orionplace/settings.json', 'orionplace/.generated.json', '.env', '.gitignore'];
88
+ const current = {};
89
+ for (const name of names) current[name] = await read(await safePath(root, name));
90
+ const pkg = current['package.json'] ? JSON.parse(current['package.json']) : { name: 'orionplace-storefront', private: true, version: '0.1.0' };
91
+ const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
92
+ if (action === 'update' && (!dependencies.next || !current['orionplace/settings.json'] || !current['orionplace/.generated.json'])) {
93
+ throw new Error('Update requires an initialized Orionplace React project. Run init first.');
94
+ }
95
+ if (!dependencies.next && ['nuxt', '@sveltejs/kit'].some(name => dependencies[name])) throw new Error('This package sets up Next.js projects only.');
96
+ if (dependencies.next && !/^(?:[~^]|>=)?16(?:\.|$)/.test(dependencies.next)) {
97
+ throw new Error('This release supports Next.js 16. Upgrade your Next.js dependency before setup.');
98
+ }
99
+ const configs = ['next.config.ts', 'next.config.js', 'next.config.mjs'].filter(name => current[name] !== null);
100
+ if (configs.length > 1) throw new Error('Multiple Next.js configuration files found; keep one root config.');
101
+ const configName = configs[0] || 'next.config.ts';
102
+ if (configs.length) inspectNextConfig(current[configName]);
103
+ // The App Router lives in app/ or src/app/; generated source follows it.
104
+ const base = await directoryExists(root, 'src/app') || (!await directoryExists(root, 'app') && await directoryExists(root, 'src')) ? 'src/' : '';
105
+ if (await directoryExists(root, `${base}pages`)) {
106
+ throw new Error('This release generates App Router source. Remove or migrate the Pages Router directory first.');
107
+ }
108
+ for (const directory of [`${base}app/api`, `${base}pages/api`]) {
109
+ const path = await safePath(root, directory);
110
+ let entries = [];
111
+ try { entries = await readdir(path); }
112
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
113
+ if (entries.some(name => name.startsWith('[...') && name !== '[...orionplace]')) {
114
+ throw new Error(`Existing API catch-all in ${directory}. Resolve this route conflict first.`);
115
+ }
116
+ }
117
+ const settings = current['orionplace/settings.json'] ? JSON.parse(current['orionplace/settings.json']) : {};
118
+ const previous = current['orionplace/.generated.json'] ? JSON.parse(current['orionplace/.generated.json']) : {};
119
+ if (settings.backend) settings.backend = backendUrl(settings.backend);
120
+ if (settings.frontend) settings.frontend = frontendDomain(settings.frontend);
121
+ const oldFrontend = settings.frontend;
122
+ const frontends = settings.frontends ?? (settings.frontend ? [settings.frontend] : []);
123
+ if (!Array.isArray(frontends)) throw new Error('settings.frontends must be an array of domain names.');
124
+ settings.frontends = [...new Set(frontends.map(frontendDomain))];
125
+ if (settings.frontend && !settings.frontends.includes(settings.frontend)) settings.frontends.unshift(settings.frontend);
126
+ if (field === 'backend') settings.backend = setting;
127
+ if (field === 'mimic') {
128
+ if (!settings.frontends.includes(setting)) {
129
+ throw new Error(`Add this frontend before selecting it for MIMIC: ${setting}`);
130
+ }
131
+ settings.frontend = setting;
132
+ }
133
+ if (field === 'frontend') {
134
+ if (action === 'remove') {
135
+ if (!settings.frontends.includes(setting)) throw new Error(`Frontend is not managed by this project: ${setting}`);
136
+ settings.frontends = settings.frontends.filter(domain => domain !== setting);
137
+ if (settings.frontend === setting) settings.frontend = settings.frontends[0];
138
+ } else {
139
+ if (!settings.frontends.includes(setting)) settings.frontends.push(setting);
140
+ // Adding an alias preserves the local development domain. "set" selects it.
141
+ if (action === 'set' || !settings.frontend) settings.frontend = setting;
142
+ }
143
+ }
144
+ settings.frontend ||= settings.frontends[0];
145
+ if (!settings.frontend) delete settings.frontend;
146
+ const manifest = { ...previous };
147
+ const changes = new Map();
148
+ const preserved = [];
149
+ async function plan(name, content, { managed = false, preserve = false } = {}) {
150
+ const path = await safePath(root, name);
151
+ const existing = await read(path);
152
+ if (managed && existing !== null && existing !== content && previous[name] !== hash(existing)) {
153
+ if (preserve && previous[name]) { preserved.push(name); return; }
154
+ throw new Error(`Refusing to overwrite ${name}: it is not an unchanged generated file. No files were changed.`);
155
+ }
156
+ if (existing !== content) changes.set(name, content);
157
+ if (managed) manifest[name] = hash(content);
158
+ }
159
+ async function planRemoval(name) {
160
+ const existing = await read(await safePath(root, name));
161
+ if (existing !== null && previous[name] !== hash(existing)) {
162
+ throw new Error(`Refusing to remove ${name}: it is not an unchanged generated file. No files were changed.`);
163
+ }
164
+ if (existing !== null) changes.set(name, null);
165
+ delete manifest[name];
166
+ }
167
+ // All checks and content generation happen before the first write.
168
+ const isNewNext = !dependencies.next;
169
+ if (!configs.length) await plan(configName, nextConfigTemplate, { managed: true, preserve: true });
170
+ pkg.scripts ||= {};
171
+ pkg.scripts.dev ||= 'next dev';
172
+ pkg.scripts.build ||= 'next build';
173
+ pkg.scripts.start ||= 'next start';
174
+ pkg.scripts['orionplace:backend'] ||= 'orionplace-react set backend';
175
+ pkg.scripts['orionplace:frontend'] ||= 'orionplace-react set frontend';
176
+ pkg.scripts['orionplace:add-frontend'] ||= 'orionplace-react add frontend';
177
+ pkg.scripts['orionplace:remove-frontend'] ||= 'orionplace-react remove frontend';
178
+ pkg.scripts['orionplace:mimic'] ||= 'orionplace-react set mimic';
179
+ pkg.scripts['orionplace:help'] ||= 'orionplace-react help';
180
+ pkg.scripts['orionplace:update'] ||= 'orionplace-react update';
181
+ pkg.dependencies ||= {};
182
+ pkg.dependencies.zustand ||= dependencies.zustand || '^5.0.15';
183
+ pkg.dependencies['orionplace-react'] ||= dependencies['orionplace-react'] || `^${metadata.version}`;
184
+ if (action === 'update') {
185
+ pkg.dependencies['orionplace-react'] = metadata.version;
186
+ if (pkg.devDependencies) delete pkg.devDependencies['orionplace-react'];
187
+ }
188
+ if (isNewNext) {
189
+ pkg.dependencies.next = '^16.3.4';
190
+ pkg.dependencies.react ||= '^19.3.0';
191
+ pkg.dependencies['react-dom'] ||= '^19.3.0';
192
+ pkg.devDependencies ||= {};
193
+ pkg.devDependencies.typescript ||= '^5.9.3';
194
+ pkg.devDependencies['@types/node'] ||= '^22.18.0';
195
+ pkg.devDependencies['@types/react'] ||= '^19.3.0';
196
+ pkg.devDependencies['@types/react-dom'] ||= '^19.3.0';
197
+ }
198
+ const templateRoot = new URL('../templates/', import.meta.url);
199
+ async function planTemplates(directory = '') {
200
+ for (const entry of await readdir(new URL(directory, templateRoot), { withFileTypes: true })) {
201
+ const name = directory + entry.name;
202
+ if (entry.isDirectory()) { await planTemplates(name + '/'); continue; }
203
+ const target = base + name;
204
+ // Never replace a customer's own layout, page, styles or middleware.
205
+ if (optional.includes(name) && !previous[target] && await read(await safePath(root, target)) !== null) continue;
206
+ const source = (await readFile(new URL(name, templateRoot), 'utf8'))
207
+ .replaceAll('__ORIONPLACE_RUNTIME__', runtimeImport(target));
208
+ await plan(target, source, { managed: true, preserve: true });
209
+ }
210
+ }
211
+ await planTemplates();
212
+ if (!await read(await safePath(root, 'tsconfig.json'))) {
213
+ await plan('tsconfig.json', JSON.stringify(tsconfigTemplate, null, 2) + '\n', { managed: true });
214
+ }
215
+ await plan('package.json', JSON.stringify(pkg, null, 2) + '\n');
216
+ await plan('orionplace/runtime/marketplace.mjs', await readFile(new URL('../runtime/marketplace.mjs', import.meta.url), 'utf8'), { managed: true, preserve: true });
217
+ await plan('orionplace/runtime/marketplace.d.mts', await readFile(new URL('../runtime/marketplace.d.mts', import.meta.url), 'utf8'), { managed: true, preserve: true });
218
+ await plan('orionplace/README.md', projectReadme(settings, base), { managed: true, preserve: true });
219
+ // A new project starts explicitly empty; keep a pre-existing manual setting on init.
220
+ const hasMimicSetting = /^\s*(?:export\s+)?MIMIC_FRONT_DOMAIN\s*=/m.test(current['.env'] || '');
221
+ if (action !== 'update' && (settings.frontend || oldFrontend || !hasMimicSetting)) {
222
+ await plan('.env', updateEnvironment(current['.env'], settings.frontend || ''));
223
+ }
224
+ if (settings.backend && action !== 'update') {
225
+ const mappings = action === 'remove' || field === 'mimic' ? []
226
+ : field === 'frontend' ? [setting] : settings.frontends;
227
+ for (const domain of mappings) {
228
+ await plan(`sitemaps/${domain}.cfg`, settings.backend + '\n', { managed: true });
229
+ }
230
+ }
231
+ if (action === 'remove') await planRemoval(`sitemaps/${setting}.cfg`);
232
+ let ignore = current['.gitignore'] || '';
233
+ for (const entry of ['node_modules/', '.next/', 'out/', 'next-env.d.ts', '.env', '.env.*', '!.env.example']) {
234
+ if (!ignore.split(/\r?\n/).includes(entry)) ignore = ignore.replace(/\n*$/, '\n') + entry + '\n';
235
+ }
236
+ await plan('.gitignore', ignore);
237
+ if (action !== 'update') await plan('orionplace/settings.json', JSON.stringify(settings, null, 2) + '\n');
238
+ await plan('orionplace/.generated.json', JSON.stringify(manifest, null, 2) + '\n');
239
+ if (!dryRun) {
240
+ for (const [name, content] of changes) {
241
+ const target = await safePath(root, name);
242
+ if (content === null) { await unlink(target); continue; }
243
+ await mkdir(dirname(target), { recursive: true });
244
+ const temporary = `${target}.orionplace-${process.pid}.tmp`;
245
+ await writeFile(temporary, content, { mode: name === '.env' ? 0o600 : 0o644, flag: 'wx' });
246
+ await rename(temporary, target);
247
+ }
248
+ }
249
+ return { root, settings, changed: [...changes.keys()], removed: [...changes].filter(([, content]) => content === null).map(([name]) => name), preserved, dryRun, isNewNext, base };
250
+ }
package/src/update.mjs ADDED
@@ -0,0 +1,36 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { resolve } from 'node:path';
3
+ import { setupProject } from './setup.mjs';
4
+
5
+ export function runNpm(args, cwd) {
6
+ const npmCli = process.env.npm_execpath;
7
+ const command = npmCli ? process.execPath : 'npm';
8
+ const commandArgs = npmCli ? [npmCli, ...args] : args;
9
+ return new Promise((resolve, reject) => {
10
+ const child = spawn(command, commandArgs, { cwd, stdio: 'inherit', shell: false });
11
+ child.once('error', reject);
12
+ child.once('exit', (code, signal) => code === 0 ? resolve() : reject(new Error(
13
+ `npm ${args[0]} failed (${signal || code}).`,
14
+ )));
15
+ });
16
+ }
17
+
18
+ export async function updateProject({ cwd = process.cwd(), dryRun = false, local = false, npm = runNpm } = {}) {
19
+ cwd = resolve(cwd);
20
+ // Validate before downloading or writing; the latest CLI repeats preflight with its own templates.
21
+ const preview = await setupProject({ cwd, action: 'update', dryRun: true });
22
+ if (!local) {
23
+ console.log('Checking the latest Orionplace React release…');
24
+ await npm(['exec', '--yes', '--prefer-online', '--package=orionplace-react@latest', '--',
25
+ 'orionplace-react', 'update', '--local', '--cwd', cwd, ...(dryRun ? ['--dry-run'] : [])], cwd);
26
+ return null; // The latest CLI reports its own changes.
27
+ }
28
+ if (dryRun) return preview;
29
+ const result = await setupProject({ cwd, action: 'update' });
30
+ try {
31
+ await npm(['install', '--no-audit', '--no-fund'], cwd);
32
+ } catch (error) {
33
+ throw new Error(`Source files were updated, but dependency installation failed. Run npm install in the project, then retry update. ${error.message}`);
34
+ }
35
+ return result;
36
+ }
@@ -0,0 +1,27 @@
1
+ import { isIP } from 'node:net';
2
+ const dns = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
3
+
4
+ export function frontendDomain(value) {
5
+ let url;
6
+ try { url = new URL(value.includes('://') ? value : `https://${value}`); }
7
+ catch { throw new Error('Use a public frontend hostname, for example shop.example.com.'); }
8
+ const domain = url.hostname.toLowerCase().replace(/\.$/, '');
9
+ if (!dns.test(domain) || isIP(domain) || url.username || url.password || url.port ||
10
+ url.search || url.hash || url.pathname !== '/' || !['http:', 'https:'].includes(url.protocol)) {
11
+ throw new Error('Frontend must be a public hostname without a port, path, or credentials.');
12
+ }
13
+ return domain;
14
+ }
15
+
16
+ export function backendUrl(value) {
17
+ let url;
18
+ try { url = new URL(value.includes('://') ? value : `https://${value}`); }
19
+ catch { throw new Error('Use the personal backend domain shown in your Orionplace account.'); }
20
+ const path = url.pathname.replace(/\/+$/, '');
21
+ if (url.protocol !== 'https:' || !dns.test(url.hostname) ||
22
+ !url.hostname.endsWith('.orionplace.app') || url.username || url.password ||
23
+ url.port || url.search || url.hash || !['', '/api'].includes(path)) {
24
+ throw new Error('Backend must be https://<your-project>.orionplace.app or its /api URL.');
25
+ }
26
+ return `${url.origin}/api`;
27
+ }