@otwdesign/cli 0.0.0-stage → 1.0.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/LICENSE +202 -0
- package/NOTICE +2 -0
- package/README.md +13 -2
- package/bin/cms.js +7 -0
- package/package.json +52 -3
- package/src/generate.ts +375 -0
- package/src/index.ts +30 -0
- package/src/main.ts +219 -0
- package/src/migrate.ts +89 -0
- package/src/serve/control.ts +67 -0
- package/src/serve/index.ts +168 -0
- package/src/serve/processes.ts +99 -0
- package/src/serve/proxy.ts +80 -0
- package/src/serve/releases.ts +195 -0
- package/src/serve/state.ts +43 -0
- package/src/serve/supervisor.ts +439 -0
- package/src/site.ts +29 -0
- package/src/update.ts +485 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @otwdesign/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `cms` command for OTW CMS sites:
|
|
4
|
+
|
|
5
|
+
- `cms generate` writes the site module and the CMS's route files from `cms.config.json`.
|
|
6
|
+
- `cms migrate` backs up the database, then runs pending migrations.
|
|
7
|
+
- `cms update` updates the CMS and its plugins to the newest compatible versions.
|
|
8
|
+
- `cms serve` runs the site from built releases, with updates from the admin.
|
|
9
|
+
|
|
10
|
+
A site made with `npm create otw-cms` has it as a development dependency. Run `cms --help` for the
|
|
11
|
+
options.
|
|
12
|
+
|
|
13
|
+
Part of [OTW CMS](https://github.com/OTWSRL/otw-cms), a WordPress-style CMS for Next.js and
|
|
14
|
+
PostgreSQL. Licensed under the Apache License 2.0.
|
package/bin/cms.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Plain JavaScript, so it runs from node_modules: it registers tsx, which then loads the CLI, the
|
|
3
|
+
// CMS packages and the site's plugins from their TypeScript source.
|
|
4
|
+
import { register } from 'tsx/esm/api'
|
|
5
|
+
|
|
6
|
+
register()
|
|
7
|
+
await import('../src/main.ts')
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@otwdesign/cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "The cms command for OTW CMS sites: generate, migrate, update and serve.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "OTW SRL",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/OTWSRL/otw-cms.git",
|
|
10
|
+
"directory": "packages/cli"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/OTWSRL/otw-cms/tree/main/packages/cli#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/OTWSRL/otw-cms/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"otw-cms",
|
|
18
|
+
"cms",
|
|
19
|
+
"cli"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"bin": {
|
|
23
|
+
"cms": "./bin/cms.js"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./src/index.ts"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"bin",
|
|
30
|
+
"src",
|
|
31
|
+
"NOTICE"
|
|
32
|
+
],
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22.18"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@next/env": "^16.4.3",
|
|
41
|
+
"@types/semver": "^7.7.0",
|
|
42
|
+
"semver": "^7.8.0",
|
|
43
|
+
"tsx": "^4.23.15",
|
|
44
|
+
"@otwdesign/core": "1.0.1",
|
|
45
|
+
"@otwdesign/next": "1.0.1",
|
|
46
|
+
"@otwdesign/sdk": "1.0.1"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@opentelemetry/api": "~1.9.0",
|
|
50
|
+
"drizzle-orm": "^0.45.4"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"typecheck": "tsc --noEmit -p ."
|
|
54
|
+
}
|
|
6
55
|
}
|
package/src/generate.ts
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
import { access, mkdir, readFile, rmdir, unlink, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, join, posix, relative, resolve, sep } from 'node:path'
|
|
3
|
+
import type { Brand } from '@otwdesign/core'
|
|
4
|
+
|
|
5
|
+
export interface CmsConfig {
|
|
6
|
+
/** npm package names of installed plugins. Installing a plugin adds it here and rebuilds. */
|
|
7
|
+
plugins: string[]
|
|
8
|
+
/** New paths for plugin pages, by qualified name: `{ "commerce.product": "/p/:slug" }`. */
|
|
9
|
+
routes?: Record<string, string>
|
|
10
|
+
/** The name the admin shows for the CMS, when it isn't the CMS's own. */
|
|
11
|
+
brand?: Brand
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// npm's rules for new package names. Names end up in generated source, so nothing else is allowed.
|
|
15
|
+
const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
|
|
16
|
+
const MAX_PACKAGE_NAME = 214
|
|
17
|
+
|
|
18
|
+
/** First line of every file `cms generate` owns. Delete it and the file is yours to keep. */
|
|
19
|
+
export const MARKER =
|
|
20
|
+
'// @generated by `cms generate`. Edits are overwritten; delete this line to keep yours.'
|
|
21
|
+
|
|
22
|
+
const MAX_BRAND_NAME = 60
|
|
23
|
+
const MAX_URL = 2048
|
|
24
|
+
const BRAND_FIELDS = new Set(['name', 'url', 'logo'])
|
|
25
|
+
// Nothing the admin shows should hold control characters.
|
|
26
|
+
const CONTROL = /\p{Cc}/u
|
|
27
|
+
|
|
28
|
+
function isWebUrl(value: unknown, protocols: readonly string[]): value is string {
|
|
29
|
+
if (typeof value !== 'string' || value.length > MAX_URL || CONTROL.test(value)) return false
|
|
30
|
+
return URL.canParse(value) && protocols.includes(new URL(value).protocol)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Root-relative only: browsers read `//host/...` as another site.
|
|
34
|
+
function isSitePath(value: unknown): value is string {
|
|
35
|
+
return typeof value === 'string' && value.length <= MAX_URL && /^\/(?![/\\])[^\s\\]*$/.test(value)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function parseBrand(raw: unknown): Brand {
|
|
39
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
40
|
+
throw new Error('cms.config.json: "brand" must be an object, such as { "name": "Acme Sites" }')
|
|
41
|
+
}
|
|
42
|
+
const fields = raw as Record<string, unknown>
|
|
43
|
+
const unknown = Object.keys(fields).find((key) => !BRAND_FIELDS.has(key))
|
|
44
|
+
if (unknown)
|
|
45
|
+
throw new Error(
|
|
46
|
+
`cms.config.json: "brand" has no field "${unknown}"; it takes name, url and logo`,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
const name = typeof fields.name === 'string' ? fields.name.trim() : ''
|
|
50
|
+
if (!name || name.length > MAX_BRAND_NAME || CONTROL.test(name)) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`cms.config.json: "brand.name" must be text of 1 to ${MAX_BRAND_NAME} characters`,
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
const brand: Brand = { name }
|
|
56
|
+
if (fields.url !== undefined) {
|
|
57
|
+
if (!isWebUrl(fields.url, ['http:', 'https:'])) {
|
|
58
|
+
throw new Error('cms.config.json: "brand.url" must be an http or https URL')
|
|
59
|
+
}
|
|
60
|
+
brand.url = fields.url
|
|
61
|
+
}
|
|
62
|
+
if (fields.logo !== undefined) {
|
|
63
|
+
if (!isSitePath(fields.logo) && !isWebUrl(fields.logo, ['https:'])) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
'cms.config.json: "brand.logo" must be a path on the site, such as /brand/logo.svg, or an https URL',
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
brand.logo = fields.logo
|
|
69
|
+
}
|
|
70
|
+
return brand
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// `{pluginId}.{page name}`, as plugins name their pages.
|
|
74
|
+
const ROUTE_KEY = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.[a-z][a-z0-9-]*$/
|
|
75
|
+
// The kernel checks the segments and parameters against the plugin's page when the site boots.
|
|
76
|
+
const ROUTE_PATH = /^\/[A-Za-z0-9._~:/-]*$/
|
|
77
|
+
const MAX_ROUTE_PATH = 200
|
|
78
|
+
|
|
79
|
+
function parseRoutes(raw: unknown): Record<string, string> {
|
|
80
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
'cms.config.json: "routes" must be an object, such as { "commerce.product": "/p/:slug" }',
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
const routes: Record<string, string> = {}
|
|
86
|
+
for (const [key, path] of Object.entries(raw)) {
|
|
87
|
+
if (!ROUTE_KEY.test(key)) {
|
|
88
|
+
throw new Error(
|
|
89
|
+
`cms.config.json: routes: "${key}" must name a plugin's page, such as "commerce.product"`,
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
if (typeof path !== 'string' || path.length > MAX_ROUTE_PATH || !ROUTE_PATH.test(path)) {
|
|
93
|
+
throw new Error(`cms.config.json: routes: "${key}" must be a path such as /shop/:slug`)
|
|
94
|
+
}
|
|
95
|
+
routes[key] = path
|
|
96
|
+
}
|
|
97
|
+
return routes
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function parseConfig(raw: unknown): CmsConfig {
|
|
101
|
+
const plugins = (raw as { plugins?: unknown } | null)?.plugins
|
|
102
|
+
if (!Array.isArray(plugins)) throw new Error('cms.config.json must contain a "plugins" array')
|
|
103
|
+
|
|
104
|
+
const seen = new Set<string>()
|
|
105
|
+
for (const name of plugins) {
|
|
106
|
+
if (typeof name !== 'string' || name.length > MAX_PACKAGE_NAME || !PACKAGE_NAME.test(name)) {
|
|
107
|
+
throw new Error(`Invalid plugin package name: ${JSON.stringify(name)}`)
|
|
108
|
+
}
|
|
109
|
+
if (seen.has(name)) throw new Error(`Plugin "${name}" is listed twice`)
|
|
110
|
+
seen.add(name)
|
|
111
|
+
}
|
|
112
|
+
const { routes, brand } = raw as { routes?: unknown; brand?: unknown }
|
|
113
|
+
return {
|
|
114
|
+
plugins: [...seen],
|
|
115
|
+
...(routes === undefined ? {} : { routes: parseRoutes(routes) }),
|
|
116
|
+
...(brand === undefined ? {} : { brand: parseBrand(brand) }),
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export async function readConfig(path: string): Promise<CmsConfig> {
|
|
121
|
+
return parseConfig(JSON.parse(await readFile(path, 'utf8')))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface ManagedFile {
|
|
125
|
+
/** Relative to the site's root, with forward slashes. */
|
|
126
|
+
path: string
|
|
127
|
+
content: string
|
|
128
|
+
/** The site may put its own file here, as with its other pages, so having one isn't a warning. */
|
|
129
|
+
replaceable?: true
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** `src/app` when the site uses a src directory, as Next.js allows either. */
|
|
133
|
+
export interface SiteLayout {
|
|
134
|
+
srcDir: '' | 'src'
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const SITE_MODULE = 'cms/site.generated.ts'
|
|
138
|
+
const ADMIN_MODULE = 'cms/admin.generated.ts'
|
|
139
|
+
|
|
140
|
+
/** Where the generated site module lives, relative to the site's root. */
|
|
141
|
+
export function siteModulePath({ srcDir }: SiteLayout): string {
|
|
142
|
+
return srcDir ? `${srcDir}/${SITE_MODULE}` : SITE_MODULE
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function file(path: string, lines: readonly string[], replaceable = false): ManagedFile {
|
|
146
|
+
const content = [MARKER, ...lines, ''].join('\n')
|
|
147
|
+
return replaceable ? { path, content, replaceable } : { path, content }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The import specifier from one site file to another, as Next.js resolves it. */
|
|
151
|
+
function importPath(from: string, to: string): string {
|
|
152
|
+
const path = posix.relative(posix.dirname(from), to).replace(/\.tsx?$/, '')
|
|
153
|
+
return path.startsWith('.') ? path : `./${path}`
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The lines of a site module: the plugins, with their admin entries when `admin` lists them, and
|
|
158
|
+
* the site's own templates (`cms/templates.tsx`) when it has them, imported when a page first
|
|
159
|
+
* needs them: they render with the kernel, which scripts and tests that boot the site from this
|
|
160
|
+
* module can't load outside Next.js.
|
|
161
|
+
*/
|
|
162
|
+
function siteModule(config: CmsConfig, admin?: ReadonlySet<string>, templates = false): string[] {
|
|
163
|
+
const withAdmin = config.plugins.flatMap((name, i) => (admin?.has(name) ? [i] : []))
|
|
164
|
+
return [
|
|
165
|
+
"import { defineSite } from '@otwdesign/next'",
|
|
166
|
+
...config.plugins.map((name, i) => `import plugin${i} from ${JSON.stringify(name)}`),
|
|
167
|
+
...withAdmin.map(
|
|
168
|
+
(i) => `import admin${i} from ${JSON.stringify(`${config.plugins[i]}/admin`)}`,
|
|
169
|
+
),
|
|
170
|
+
'',
|
|
171
|
+
'export const site = defineSite({',
|
|
172
|
+
` plugins: [${config.plugins.map((_, i) => `plugin${i}`).join(', ')}],`,
|
|
173
|
+
...(admin ? [` admin: [${withAdmin.map((i) => `admin${i}`).join(', ')}],`] : []),
|
|
174
|
+
` packages: [${config.plugins.map((name) => JSON.stringify(name)).join(', ')}],`,
|
|
175
|
+
...(config.routes ? [` routes: ${JSON.stringify(config.routes)},`] : []),
|
|
176
|
+
...(config.brand ? [` brand: ${JSON.stringify(config.brand)},`] : []),
|
|
177
|
+
...(templates ? [" templates: () => import('./templates'),"] : []),
|
|
178
|
+
'})',
|
|
179
|
+
]
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Everything the CMS needs in the site's app directory. The admin is one catch-all route, so new
|
|
184
|
+
* core screens need no new files; these only change when the routing itself does. `admin` names
|
|
185
|
+
* the plugins whose packages have an admin entry (`./admin`).
|
|
186
|
+
*/
|
|
187
|
+
export function managedFiles(
|
|
188
|
+
config: CmsConfig,
|
|
189
|
+
{ srcDir }: SiteLayout,
|
|
190
|
+
admin: readonly string[] = [],
|
|
191
|
+
/** Whether the site has its own templates, `cms/templates.tsx`, which only its pages need. */
|
|
192
|
+
templates = false,
|
|
193
|
+
): ManagedFile[] {
|
|
194
|
+
const at = (path: string) => (srcDir ? `${srcDir}/${path}` : path)
|
|
195
|
+
const site = siteModulePath({ srcDir })
|
|
196
|
+
const adminSite = srcDir ? `${srcDir}/${ADMIN_MODULE}` : ADMIN_MODULE
|
|
197
|
+
// Every route imports a site module, which registers the installed plugins for its bundle. The
|
|
198
|
+
// admin's adds their admin entries, which the storefront's routes must never import: Next.js
|
|
199
|
+
// sends every client component a route imports to its visitors.
|
|
200
|
+
const route = (path: string, lines: readonly string[], replaceable = false, module = site) =>
|
|
201
|
+
file(at(path), [`import '${importPath(at(path), module)}'`, ...lines], replaceable)
|
|
202
|
+
const adminRoute = (path: string, lines: readonly string[]) =>
|
|
203
|
+
route(path, lines, false, adminSite)
|
|
204
|
+
const dynamic = "export const dynamic = 'force-dynamic'"
|
|
205
|
+
const storefront = [
|
|
206
|
+
"export { SitePage as default, generateSiteMetadata as generateMetadata } from '@otwdesign/next/site'",
|
|
207
|
+
dynamic,
|
|
208
|
+
]
|
|
209
|
+
|
|
210
|
+
return [
|
|
211
|
+
file(site, siteModule(config, undefined, templates)),
|
|
212
|
+
file(adminSite, [
|
|
213
|
+
"// The admin's site module: the plugins and their admin entries. Only the admin and the API import it.",
|
|
214
|
+
...siteModule(config, new Set(admin)),
|
|
215
|
+
]),
|
|
216
|
+
adminRoute('app/(cms)/layout.tsx', [
|
|
217
|
+
"export { AdminRootLayout as default } from '@otwdesign/next/admin'",
|
|
218
|
+
dynamic,
|
|
219
|
+
]),
|
|
220
|
+
// Wrapped as Prettier would, so a site's format check passes on the files written here.
|
|
221
|
+
adminRoute('app/(cms)/admin/[[...segments]]/page.tsx', [
|
|
222
|
+
'export {',
|
|
223
|
+
' AdminPage as default,',
|
|
224
|
+
' generateAdminMetadata as generateMetadata,',
|
|
225
|
+
"} from '@otwdesign/next/admin'",
|
|
226
|
+
dynamic,
|
|
227
|
+
]),
|
|
228
|
+
file(at('app/(cms)/admin/forbidden.tsx'), [
|
|
229
|
+
"export { AdminForbidden as default } from '@otwdesign/next/admin'",
|
|
230
|
+
]),
|
|
231
|
+
file(at('app/(cms)/admin/not-found.tsx'), [
|
|
232
|
+
"export { AdminNotFound as default } from '@otwdesign/next/admin'",
|
|
233
|
+
]),
|
|
234
|
+
adminRoute('app/(cms)/api/p/[...path]/route.ts', [
|
|
235
|
+
"export { DELETE, GET, PATCH, POST, PUT } from '@otwdesign/next/api'",
|
|
236
|
+
dynamic,
|
|
237
|
+
]),
|
|
238
|
+
// The media library's files, as wp-content/uploads. A plugin may keep them elsewhere, so
|
|
239
|
+
// they come from the site's module, where plugins set up, never the admin's.
|
|
240
|
+
route('app/(cms)/uploads/[...path]/route.ts', [
|
|
241
|
+
"export { GET, HEAD } from '@otwdesign/next/uploads'",
|
|
242
|
+
dynamic,
|
|
243
|
+
]),
|
|
244
|
+
// Next.js loads it when the server starts. A site with its own (Sentry, say) keeps it and
|
|
245
|
+
// calls this register() from its own.
|
|
246
|
+
file(
|
|
247
|
+
at('instrumentation.ts'),
|
|
248
|
+
["export { register } from '@otwdesign/next/instrumentation'"],
|
|
249
|
+
true,
|
|
250
|
+
),
|
|
251
|
+
// The home page has a file of its own so the site can write its own home page; an optional
|
|
252
|
+
// catch-all would claim / as well, and Next.js allows only one.
|
|
253
|
+
route('app/(site)/page.tsx', storefront, true),
|
|
254
|
+
route('app/(site)/[...slug]/page.tsx', storefront),
|
|
255
|
+
]
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Files earlier versions managed, and the files that took their place. One still carrying the
|
|
260
|
+
* marker is removed. One the site made its own stays, and its replacements aren't written,
|
|
261
|
+
* since they would clash with it.
|
|
262
|
+
*/
|
|
263
|
+
export function retiredFiles({ srcDir }: SiteLayout): { path: string; replacedBy: string[] }[] {
|
|
264
|
+
const at = (path: string) => (srcDir ? `${srcDir}/${path}` : path)
|
|
265
|
+
return [
|
|
266
|
+
{
|
|
267
|
+
path: at('app/(site)/[[...slug]]/page.tsx'),
|
|
268
|
+
replacedBy: [at('app/(site)/page.tsx'), at('app/(site)/[...slug]/page.tsx')],
|
|
269
|
+
},
|
|
270
|
+
]
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** `own` is the site's file where a replaceable one would go; `removed`, a retired file. */
|
|
274
|
+
export type FileStatus = 'written' | 'unchanged' | 'kept' | 'own' | 'removed'
|
|
275
|
+
|
|
276
|
+
export interface GenerateResult {
|
|
277
|
+
files: { path: string; status: FileStatus }[]
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function exists(path: string): Promise<boolean> {
|
|
281
|
+
return access(path).then(
|
|
282
|
+
() => true,
|
|
283
|
+
() => false,
|
|
284
|
+
)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async function readIfExists(path: string): Promise<string | null> {
|
|
288
|
+
return readFile(path, 'utf8').catch((error: NodeJS.ErrnoException) => {
|
|
289
|
+
if (error.code === 'ENOENT') return null
|
|
290
|
+
throw error
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Writes the managed files under `root`. A file is rewritten only when its content changes, so
|
|
296
|
+
* the dev server doesn't reload for nothing, and never once its marker line is gone.
|
|
297
|
+
*/
|
|
298
|
+
export async function generate({
|
|
299
|
+
root,
|
|
300
|
+
config: configPath = join(root, 'cms.config.json'),
|
|
301
|
+
}: {
|
|
302
|
+
root: string
|
|
303
|
+
config?: string
|
|
304
|
+
}): Promise<GenerateResult> {
|
|
305
|
+
const config = await readConfig(configPath)
|
|
306
|
+
const layout: SiteLayout = { srcDir: (await exists(join(root, 'src', 'app'))) ? 'src' : '' }
|
|
307
|
+
const admin = await pluginsWithAdmin(root, config.plugins)
|
|
308
|
+
const cmsDir = join(root, layout.srcDir, 'cms')
|
|
309
|
+
const templates =
|
|
310
|
+
(await exists(join(cmsDir, 'templates.tsx'))) || (await exists(join(cmsDir, 'templates.ts')))
|
|
311
|
+
const files: GenerateResult['files'] = []
|
|
312
|
+
const clashing = new Set<string>()
|
|
313
|
+
for (const retired of retiredFiles(layout)) {
|
|
314
|
+
const target = join(root, ...retired.path.split('/'))
|
|
315
|
+
const existing = await readIfExists(target)
|
|
316
|
+
if (existing === null) continue
|
|
317
|
+
if (existing.startsWith(MARKER)) {
|
|
318
|
+
await removeRoute(target)
|
|
319
|
+
files.push({ path: retired.path, status: 'removed' })
|
|
320
|
+
} else {
|
|
321
|
+
files.push({ path: retired.path, status: 'kept' })
|
|
322
|
+
for (const path of retired.replacedBy) clashing.add(path)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
for (const managed of managedFiles(config, layout, admin, templates)) {
|
|
326
|
+
if (clashing.has(managed.path)) continue
|
|
327
|
+
const target = join(root, ...managed.path.split('/'))
|
|
328
|
+
const existing = await readIfExists(target)
|
|
329
|
+
if (existing !== null && !existing.startsWith(MARKER)) {
|
|
330
|
+
files.push({ path: managed.path, status: managed.replaceable ? 'own' : 'kept' })
|
|
331
|
+
} else if (existing === managed.content) {
|
|
332
|
+
files.push({ path: managed.path, status: 'unchanged' })
|
|
333
|
+
} else {
|
|
334
|
+
await mkdir(dirname(target), { recursive: true })
|
|
335
|
+
await writeFile(target, managed.content)
|
|
336
|
+
files.push({ path: managed.path, status: 'written' })
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return { files }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* The plugins whose package exports an admin entry (`./admin`), found as Node resolves packages:
|
|
344
|
+
* in `node_modules` here or in a folder above, where workspaces install them.
|
|
345
|
+
*/
|
|
346
|
+
async function pluginsWithAdmin(root: string, plugins: readonly string[]): Promise<string[]> {
|
|
347
|
+
const found: string[] = []
|
|
348
|
+
for (const name of plugins) {
|
|
349
|
+
const manifest = await packageManifest(root, name)
|
|
350
|
+
const exports = manifest?.exports
|
|
351
|
+
if (exports && typeof exports === 'object' && './admin' in exports) found.push(name)
|
|
352
|
+
}
|
|
353
|
+
return found
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function packageManifest(root: string, name: string): Promise<{ exports?: unknown } | null> {
|
|
357
|
+
for (let dir = resolve(root); ; dir = dirname(dir)) {
|
|
358
|
+
const text = await readIfExists(join(dir, 'node_modules', ...name.split('/'), 'package.json'))
|
|
359
|
+
if (text !== null) return JSON.parse(text) as { exports?: unknown }
|
|
360
|
+
if (dirname(dir) === dir) return null
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Deletes a route file, and its folder unless the site put something else there. */
|
|
365
|
+
export async function removeRoute(path: string): Promise<void> {
|
|
366
|
+
await unlink(path)
|
|
367
|
+
await rmdir(dirname(path)).catch((error: NodeJS.ErrnoException) => {
|
|
368
|
+
if (error.code !== 'ENOTEMPTY' && error.code !== 'EEXIST') throw error
|
|
369
|
+
})
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** For messages: a path relative to where the command ran. */
|
|
373
|
+
export function displayPath(root: string, path: string): string {
|
|
374
|
+
return relative(process.cwd(), join(root, path)).split(sep).join('/') || '.'
|
|
375
|
+
}
|