@sssb/create 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/bin/create.js +135 -0
- package/package.json +22 -3
- package/src/args.js +270 -0
- package/src/files.js +660 -0
- package/src/generate.js +517 -0
- package/src/json.js +60 -0
- package/src/signals.js +72 -0
- package/src/template.js +496 -0
- package/src/yaml.js +17 -0
- package/template/app/DEMO-SIZE.md +55 -0
- package/template/app/config/app.ts +17 -0
- package/template/app/config/params.ts +70 -0
- package/template/app/infra/README.md +78 -0
- package/template/app/infra/app.ts +45 -0
- package/template/app/infra/cdk.json +9 -0
- package/template/app/infra/lib/tags.ts +35 -0
- package/template/app/infra/package.json +20 -0
- package/template/app/infra/tsconfig.json +13 -0
- package/template/app/messages/en.json +20 -0
- package/template/app/messages/es.json +20 -0
- package/template/app/next.config.ts +9 -0
- package/template/app/package.json +40 -0
- package/template/app/playwright.config.ts +50 -0
- package/template/app/playwright.demo.config.ts +10 -0
- package/template/app/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx +37 -0
- package/template/app/src/app/[locale]/(protected)/dashboard/page.tsx +21 -0
- package/template/app/src/app/[locale]/(protected)/header-glue.tsx +59 -0
- package/template/app/src/app/[locale]/(protected)/layout.tsx +43 -0
- package/template/app/src/app/[locale]/layout.tsx +55 -0
- package/template/app/src/app/[locale]/page.tsx +9 -0
- package/template/app/src/app/[locale]/signin/page.tsx +55 -0
- package/template/app/src/app/[locale]/signin/picker-glue.tsx +21 -0
- package/template/app/src/app/api/auth/dev-signin/route.ts +12 -0
- package/template/app/src/app/api/auth/org/route.ts +10 -0
- package/template/app/src/app/api/auth/signout/route.ts +9 -0
- package/template/app/src/app/api/items/route.ts +52 -0
- package/template/app/src/app/api/respond.ts +13 -0
- package/template/app/src/app/api/webhooks/cron/route.test.ts +59 -0
- package/template/app/src/app/api/webhooks/cron/route.ts +15 -0
- package/template/app/src/app/layout.tsx +7 -0
- package/template/app/src/app-config/abilities.ts +93 -0
- package/template/app/src/app-config/actors.ts +13 -0
- package/template/app/src/app-config/audit.ts +9 -0
- package/template/app/src/app-config/db/migrations/1001_items.ts +37 -0
- package/template/app/src/app-config/db/migrations/index.ts +11 -0
- package/template/app/src/app-config/db/rls-proofs.ts +81 -0
- package/template/app/src/app-config/db/schema.ts +23 -0
- package/template/app/src/app-config/digest.ts +10 -0
- package/template/app/src/app-config/identity.ts +8 -0
- package/template/app/src/app-config/inbound-email.ts +10 -0
- package/template/app/src/app-config/jobs.ts +28 -0
- package/template/app/src/app-config/messages.ts +18 -0
- package/template/app/src/app-config/notifications.ts +31 -0
- package/template/app/src/app-config/preset-operations.ts +9 -0
- package/template/app/src/app-config/presets.ts +18 -0
- package/template/app/src/app-config/seed.ts +7 -0
- package/template/app/src/app-config/simulator.ts +17 -0
- package/template/app/src/app-config/tours.ts +14 -0
- package/template/app/src/app-config/webhooks.ts +13 -0
- package/template/app/src/components/dashboard-screen.tsx +26 -0
- package/template/app/src/components/items-card.tsx +84 -0
- package/template/app/src/components/welcome-screen.tsx +20 -0
- package/template/app/src/demo-static/app.tsx +77 -0
- package/template/app/src/demo-static/index.html +12 -0
- package/template/app/src/demo-static/main.tsx +40 -0
- package/template/app/src/proxy.ts +9 -0
- package/template/app/src/seed/index.ts +93 -0
- package/template/app/src/sssb.conformance.test.ts +7 -0
- package/template/app/src/styles/index.css +1 -0
- package/template/app/tests/catalog.ts +15 -0
- package/template/app/tests/contract/rls-contract.test.ts +14 -0
- package/template/app/tests/demo-static/static-shell.spec.ts +32 -0
- package/template/app/tests/e2e/items.spec.ts +58 -0
- package/template/app/tsconfig.json +29 -0
- package/template/app/vite.demo.config.ts +8 -0
- package/template/guide.md +118 -0
- package/template/meta.json +633 -0
- package/template/root/_dot_editorconfig +12 -0
- package/template/root/_dot_husky/commit-msg +1 -0
- package/template/root/_dot_husky/pre-commit +1 -0
- package/template/root/_dot_nvmrc +1 -0
- package/template/root/_dot_prettierrc.json +5 -0
- package/template/root/commitlint.config.mjs +1 -0
- package/README.md +0 -3
package/src/generate.js
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// GENERATION: a new app workspace from a built template (template.js), into a directory that does not exist or is
|
|
3
|
+
// empty. The app is the template's (SSSB's starter) under apps/<slug>/, renamed where its identity lives; the
|
|
4
|
+
// workspace around it is written by files.js. Nothing in the output names SSSB's repository, its other app, its
|
|
5
|
+
// framework package's path or its maintainers, which tests/tooling/create-generate.test.ts greps for.
|
|
6
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
7
|
+
import {
|
|
8
|
+
cpSync,
|
|
9
|
+
existsSync,
|
|
10
|
+
lstatSync,
|
|
11
|
+
mkdirSync,
|
|
12
|
+
readdirSync,
|
|
13
|
+
readFileSync,
|
|
14
|
+
renameSync,
|
|
15
|
+
rmdirSync,
|
|
16
|
+
rmSync,
|
|
17
|
+
statSync,
|
|
18
|
+
writeFileSync,
|
|
19
|
+
} from 'node:fs'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import { columns, CreateError, displayName } from './args.js'
|
|
22
|
+
import * as files from './files.js'
|
|
23
|
+
import { formatJson, packageJson } from './json.js'
|
|
24
|
+
import { holdSignals, releaseSignals } from './signals.js'
|
|
25
|
+
import { filesUnder, fromStored, GUIDE_FILE, readTemplate } from './template.js'
|
|
26
|
+
|
|
27
|
+
/** The @sssb packages the workspace installs (the seam, @sssb/app-config, is the app's own and never installed). */
|
|
28
|
+
const SSSB_PACKAGES = ['kit', 'tools', 'eslint-plugin', 'cdk']
|
|
29
|
+
|
|
30
|
+
const SEAM = '@sssb/app-config'
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The seam's own package name: unique in the workspace, as the app's is (`<slug>`, its infra `<slug>-infra`).
|
|
34
|
+
* @param {string} slug
|
|
35
|
+
*/
|
|
36
|
+
const seamPackage = (slug) => `${slug}-app-config`
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A TypeScript string literal quoted the way Prettier would quote it (single quotes unless the value has more of
|
|
40
|
+
* them than of double quotes), so a display name with an apostrophe does not fail the first `pnpm lint`.
|
|
41
|
+
* @param {string} value
|
|
42
|
+
*/
|
|
43
|
+
function tsString(value) {
|
|
44
|
+
const singles = (value.match(/'/g) ?? []).length
|
|
45
|
+
const doubles = (value.match(/"/g) ?? []).length
|
|
46
|
+
return singles > doubles
|
|
47
|
+
? `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
|
|
48
|
+
: `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @param {string} value */
|
|
52
|
+
const htmlText = (value) => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* `--sssb`: a directory of packed tarballs, or a version (range) for every @sssb package.
|
|
56
|
+
* @param {string | null} sssb
|
|
57
|
+
* @param {string} version the generator's own, the fixed group's
|
|
58
|
+
* @returns {{ spec: (pkg: string) => string, tarballs: Record<string, string> | null }}
|
|
59
|
+
*/
|
|
60
|
+
function resolveSssb(sssb, version) {
|
|
61
|
+
if (sssb === null) return { spec: () => `^${version}`, tarballs: null }
|
|
62
|
+
const dir = path.resolve(sssb)
|
|
63
|
+
if (existsSync(dir) && statSync(dir).isDirectory()) {
|
|
64
|
+
const names = readdirSync(dir)
|
|
65
|
+
/** @type {Record<string, string>} */
|
|
66
|
+
const tarballs = {}
|
|
67
|
+
/** @type {Map<string, string[]>} */
|
|
68
|
+
const versions = new Map()
|
|
69
|
+
for (const pkg of SSSB_PACKAGES) {
|
|
70
|
+
const found = names.filter((name) => new RegExp(`^sssb-${pkg}-\\d[^/]*\\.tgz$`).test(name))
|
|
71
|
+
if (found.length !== 1) {
|
|
72
|
+
throw new CreateError(
|
|
73
|
+
`--sssb ${sssb}: expected one sssb-${pkg}-<version>.tgz there, found ${found.join(', ') || 'none'}`,
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
const file = /** @type {string} */ (found[0])
|
|
77
|
+
tarballs[pkg] = path.join(dir, file)
|
|
78
|
+
const version = file.slice(`sssb-${pkg}-`.length, -'.tgz'.length)
|
|
79
|
+
versions.set(version, [...(versions.get(version) ?? []), `@sssb/${pkg}`])
|
|
80
|
+
}
|
|
81
|
+
// The @sssb packages are one fixed group, released together at one version (ADR-0014 part 7): tarballs of two
|
|
82
|
+
// versions are two releases mixed, which no published install could ever be.
|
|
83
|
+
if (versions.size > 1) {
|
|
84
|
+
throw new CreateError(
|
|
85
|
+
`--sssb ${sssb}: the tarballs are of different versions (${[...versions]
|
|
86
|
+
.map(([version, pkgs]) => `${pkgs.join(', ')} ${version}`)
|
|
87
|
+
.join('; ')}); the @sssb packages are released together at one version`,
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
checkVersion(sssb, /** @type {string} */ ([...versions.keys()][0]), version)
|
|
91
|
+
return { spec: (pkg) => `file:${tarballs[pkg]}`, tarballs }
|
|
92
|
+
}
|
|
93
|
+
if (!/^[\^~]?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(sssb))
|
|
94
|
+
throw new CreateError(`--sssb ${sssb} is neither a directory of tarballs nor a version`)
|
|
95
|
+
checkVersion(sssb, sssb.replace(/^[\^~]/, ''), version)
|
|
96
|
+
return { spec: () => sssb, tarballs: null }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The @sssb packages a workspace installs must be the generator's own version: the workspace's copy of the app guide
|
|
101
|
+
* (.claude/sssb-guide.md) is stamped with the hash of the guide packed into the generator, and `sssb doctor` fails on
|
|
102
|
+
* the first `pnpm verify` when the installed @sssb/kit's guide differs.
|
|
103
|
+
* @param {string} sssb the flag's value
|
|
104
|
+
* @param {string} given the version it names
|
|
105
|
+
* @param {string} version the generator's
|
|
106
|
+
*/
|
|
107
|
+
function checkVersion(sssb, given, version) {
|
|
108
|
+
if (given !== version) {
|
|
109
|
+
throw new CreateError(
|
|
110
|
+
`--sssb ${sssb} is @sssb ${given}, and this generator writes workspaces of @sssb ${version} (its copy of ` +
|
|
111
|
+
`the app guide is ${version}'s): run @sssb/create@${given} instead`,
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @param {string} file
|
|
118
|
+
* @param {string} from
|
|
119
|
+
* @param {string} to
|
|
120
|
+
*/
|
|
121
|
+
function replaceOnce(file, from, to) {
|
|
122
|
+
const text = readFileSync(file, 'utf8')
|
|
123
|
+
const count = text.split(from).length - 1
|
|
124
|
+
if (count !== 1)
|
|
125
|
+
throw new CreateError(
|
|
126
|
+
`the template's ${path.basename(file)}: expected ${JSON.stringify(from)} once, found ${count}`,
|
|
127
|
+
)
|
|
128
|
+
writeFileSync(
|
|
129
|
+
file,
|
|
130
|
+
text.replace(from, () => to),
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** @param {string} file */
|
|
135
|
+
const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'))
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Every @sssb dependency of a manifest, rewritten to what this workspace installs.
|
|
139
|
+
* @param {Record<string, Record<string, string>>} manifest
|
|
140
|
+
* @param {(pkg: string) => string} spec
|
|
141
|
+
*/
|
|
142
|
+
function pinSssb(manifest, spec) {
|
|
143
|
+
for (const field of ['dependencies', 'devDependencies']) {
|
|
144
|
+
const deps = manifest[field]
|
|
145
|
+
if (!deps) continue
|
|
146
|
+
for (const name of Object.keys(deps)) {
|
|
147
|
+
if (!name.startsWith('@sssb/') || name === SEAM) continue
|
|
148
|
+
const pkg = name.slice('@sssb/'.length)
|
|
149
|
+
if (!SSSB_PACKAGES.includes(pkg))
|
|
150
|
+
throw new CreateError(`the template depends on ${name}, an unknown package`)
|
|
151
|
+
deps[name] = spec(pkg)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* @param {Record<string, string>} deps
|
|
158
|
+
* @returns {Record<string, string>}
|
|
159
|
+
*/
|
|
160
|
+
const sorted = (deps) => Object.fromEntries(Object.entries(deps).sort(([a], [b]) => a.localeCompare(b)))
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The seam package's exports: every specifier the framework imports from `@sssb/app-config` resolves to a module of
|
|
164
|
+
* the app's. The flat modules by one pattern (`./*` to `./*.ts`), so a seam module the framework adds later is
|
|
165
|
+
* covered when the app writes it; a directory module (`db/migrations`) by name.
|
|
166
|
+
* @param {string} seamDir
|
|
167
|
+
* @param {string[]} specifiers
|
|
168
|
+
*/
|
|
169
|
+
function seamExports(seamDir, specifiers) {
|
|
170
|
+
/** @type {Record<string, string>} */
|
|
171
|
+
const exportsMap = {}
|
|
172
|
+
let flat = false
|
|
173
|
+
for (const specifier of specifiers) {
|
|
174
|
+
if (!specifier.startsWith(`${SEAM}/`)) throw new CreateError(`${specifier} is not a seam specifier`)
|
|
175
|
+
const sub = specifier.slice(SEAM.length + 1)
|
|
176
|
+
if (existsSync(path.join(seamDir, `${sub}.ts`))) flat = true
|
|
177
|
+
else if (existsSync(path.join(seamDir, sub, 'index.ts'))) exportsMap[`./${sub}`] = `./${sub}/index.ts`
|
|
178
|
+
else throw new CreateError(`the template's seam has no module for ${specifier}`)
|
|
179
|
+
}
|
|
180
|
+
if (flat) exportsMap['./*'] = './*.ts'
|
|
181
|
+
return exportsMap
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* @typedef {{
|
|
186
|
+
* templateDir: string,
|
|
187
|
+
* target: string,
|
|
188
|
+
* slug: string,
|
|
189
|
+
* name: string,
|
|
190
|
+
* repo?: string | null,
|
|
191
|
+
* owners?: string[],
|
|
192
|
+
* sssb?: string | null,
|
|
193
|
+
* workflowRef?: string | null,
|
|
194
|
+
* }} GenerateOptions
|
|
195
|
+
*/
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A filesystem failure (no permission, no space, a name that cannot be made) as a CreateError, for the person at the
|
|
199
|
+
* terminal; anything else, a bug, as it is.
|
|
200
|
+
* @param {unknown} error
|
|
201
|
+
*/
|
|
202
|
+
function asCreateError(error) {
|
|
203
|
+
if (error instanceof CreateError) return error
|
|
204
|
+
const err = /** @type {NodeJS.ErrnoException} */ (error)
|
|
205
|
+
if (typeof err?.code === 'string' && typeof err.syscall === 'string')
|
|
206
|
+
return new CreateError(`could not write the workspace: ${err.message}`)
|
|
207
|
+
return error
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The slug names the app's packages; refused when one of those names is a package the workspace installs (the
|
|
212
|
+
* template's `dependencyNames`, from pack and consume's lockfile seed), which pnpm would then mistake for the app (an
|
|
213
|
+
* app named `ws` was handed the `ws` package's optional peers).
|
|
214
|
+
* @param {string} slug
|
|
215
|
+
* @param {import('./template.js').TemplateMeta} meta
|
|
216
|
+
*/
|
|
217
|
+
function checkPackageNames(slug, meta) {
|
|
218
|
+
const names = new Set(meta.dependencyNames)
|
|
219
|
+
for (const pkg of [slug, `${slug}-infra`, `${slug}-workspace`]) {
|
|
220
|
+
if (names.has(pkg)) {
|
|
221
|
+
throw new CreateError(
|
|
222
|
+
`the slug "${slug}" would name a package "${pkg}", which is also a dependency the workspace installs ` +
|
|
223
|
+
`(npm's ${pkg}): pnpm mistakes one for the other. Pass another --slug`,
|
|
224
|
+
)
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* What a directory may hold and still count as empty, each left untouched: a repository's `.git` (`git init`, or
|
|
231
|
+
* `gh repo clone` of a new repository), the Finder's `.DS_Store` (which it may also write while the workspace is), and a
|
|
232
|
+
* filesystem root's `lost+found`. The workspace writes none of them.
|
|
233
|
+
*/
|
|
234
|
+
const LEFT_ALONE = new Set(['.git', '.DS_Store', 'lost+found'])
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* A directory's entries but those LEFT_ALONE and `also`.
|
|
238
|
+
* @param {string} dir
|
|
239
|
+
* @param {string} [also]
|
|
240
|
+
*/
|
|
241
|
+
const occupants = (dir, also) => readdirSync(dir).filter((entry) => !LEFT_ALONE.has(entry) && entry !== also)
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Writes a new workspace. Refuses a target that exists and is not an empty directory (LEFT_ALONE's entries aside), or
|
|
245
|
+
* is a symlink. An existing target is never removed or replaced (it may be the shell's working directory, a mount
|
|
246
|
+
* point, or in a directory this user cannot write; its mode, owner and ACLs are the user's): the workspace is written
|
|
247
|
+
* into a stage INSIDE it, `<target>/.sssb-create-<hex>/`, whose entries are moved up into the target at the end. A
|
|
248
|
+
* failure part-way, or a SIGINT, SIGTERM or SIGHUP (signals.js), leaves nothing behind: the stage and whatever was
|
|
249
|
+
* moved up are removed, and the target and its parents too when this run created them (and they are empty).
|
|
250
|
+
* @param {GenerateOptions} options
|
|
251
|
+
* @returns {{ root: string, appDir: string, files: string[], workflowRef: string, tarballs: Record<string, string> | null }}
|
|
252
|
+
*/
|
|
253
|
+
export function generate({
|
|
254
|
+
templateDir,
|
|
255
|
+
target,
|
|
256
|
+
slug,
|
|
257
|
+
name,
|
|
258
|
+
repo = null,
|
|
259
|
+
owners = [],
|
|
260
|
+
sssb = null,
|
|
261
|
+
workflowRef = null,
|
|
262
|
+
}) {
|
|
263
|
+
const meta = readTemplate(templateDir)
|
|
264
|
+
const root = path.resolve(target)
|
|
265
|
+
const ref = workflowRef ?? meta.workflow.ref
|
|
266
|
+
if (!/^[0-9a-f]{40}$/.test(ref)) throw new CreateError(`the workflow ref "${ref}" is not a full commit SHA`)
|
|
267
|
+
checkPackageNames(slug, meta)
|
|
268
|
+
const { spec, tarballs } = resolveSssb(sssb, meta.version)
|
|
269
|
+
/** @type {import('./files.js').Context} */
|
|
270
|
+
const c = { slug, name: displayName(name), repo, owners, meta, sssbSpec: spec, workflowRef: ref }
|
|
271
|
+
|
|
272
|
+
/** What this run made: the first directory it created on the way to the target (maybe the target), the stage. */
|
|
273
|
+
const made = {
|
|
274
|
+
created: /** @type {string | undefined} */ (undefined),
|
|
275
|
+
stage: '',
|
|
276
|
+
moved: /** @type {string[]} */ ([]),
|
|
277
|
+
}
|
|
278
|
+
// Only what this run made goes: the stage, the entries it moved up, then each directory it created, while empty.
|
|
279
|
+
const undo = () => {
|
|
280
|
+
if (made.stage) rmSync(made.stage, { recursive: true, force: true })
|
|
281
|
+
for (const entry of made.moved.splice(0)) rmSync(path.join(root, entry), { recursive: true, force: true })
|
|
282
|
+
for (let dir = root; made.created; dir = path.dirname(dir)) {
|
|
283
|
+
try {
|
|
284
|
+
rmdirSync(dir)
|
|
285
|
+
} catch {
|
|
286
|
+
break
|
|
287
|
+
}
|
|
288
|
+
if (dir === made.created) break
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
holdSignals(undo)
|
|
292
|
+
try {
|
|
293
|
+
const existing = lstatSync(root, { throwIfNoEntry: false })
|
|
294
|
+
if (existing?.isSymbolicLink())
|
|
295
|
+
throw new CreateError(`${root} is a symbolic link: name a new directory, or an empty one`)
|
|
296
|
+
if (existing && (!existing.isDirectory() || occupants(root).length > 0))
|
|
297
|
+
throw new CreateError(`${root} already exists and is not an empty directory: name a new one`)
|
|
298
|
+
if (!existing) {
|
|
299
|
+
made.created = mkdirSync(path.dirname(root), { recursive: true })
|
|
300
|
+
mkdirSync(root)
|
|
301
|
+
made.created ??= root
|
|
302
|
+
}
|
|
303
|
+
const stageName = `.sssb-create-${randomBytes(4).toString('hex')}`
|
|
304
|
+
made.stage = path.join(root, stageName)
|
|
305
|
+
mkdirSync(made.stage)
|
|
306
|
+
const files = writeWorkspace(made.stage, c, templateDir)
|
|
307
|
+
const arrived = occupants(root, stageName)
|
|
308
|
+
if (arrived.length > 0)
|
|
309
|
+
throw new CreateError(
|
|
310
|
+
`${root} gained ${arrived.join(', ')} while the workspace was written: name a new one`,
|
|
311
|
+
)
|
|
312
|
+
for (const entry of readdirSync(made.stage)) {
|
|
313
|
+
// Never over one of LEFT_ALONE's (a rename replaces a file), and so never undoing it.
|
|
314
|
+
if (lstatSync(path.join(root, entry), { throwIfNoEntry: false }))
|
|
315
|
+
throw new CreateError(`${root} already holds ${entry}, which the workspace would replace`)
|
|
316
|
+
renameSync(path.join(made.stage, entry), path.join(root, entry))
|
|
317
|
+
made.moved.push(entry)
|
|
318
|
+
}
|
|
319
|
+
rmdirSync(made.stage)
|
|
320
|
+
made.stage = ''
|
|
321
|
+
return { root, appDir: path.join(root, 'apps', slug), files, workflowRef: ref, tarballs }
|
|
322
|
+
} catch (error) {
|
|
323
|
+
undo()
|
|
324
|
+
throw asCreateError(error)
|
|
325
|
+
} finally {
|
|
326
|
+
releaseSignals(undo)
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* The workspace's files, written under `root`.
|
|
332
|
+
* @param {string} root
|
|
333
|
+
* @param {import('./files.js').Context} c
|
|
334
|
+
* @param {string} templateDir
|
|
335
|
+
* @returns {string[]} the files written, relative to `root`
|
|
336
|
+
*/
|
|
337
|
+
function writeWorkspace(root, c, templateDir) {
|
|
338
|
+
const { slug, name, meta, sssbSpec: spec } = c
|
|
339
|
+
const appDir = path.join(root, 'apps', slug)
|
|
340
|
+
const inApp = (/** @type {string} */ relative) => path.join(appDir, relative)
|
|
341
|
+
|
|
342
|
+
// The template, copied: the app, and the generic workspace files.
|
|
343
|
+
for (const [from, to] of /** @type {const} */ ([
|
|
344
|
+
['app', appDir],
|
|
345
|
+
['root', root],
|
|
346
|
+
])) {
|
|
347
|
+
for (const stored of filesUnder(path.join(templateDir, from))) {
|
|
348
|
+
const file = path.join(to, fromStored(stored))
|
|
349
|
+
mkdirSync(path.dirname(file), { recursive: true })
|
|
350
|
+
cpSync(path.join(templateDir, from, stored), file)
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// THE APP'S IDENTITY: its slug (config/app.ts, which everything mechanical derives from), its package names, and
|
|
355
|
+
// its display name in its catalogs and titles. Each edit must find what it replaces exactly once, so a template
|
|
356
|
+
// that moved its identity elsewhere fails here instead of shipping half-renamed.
|
|
357
|
+
const slugLine = /export const APP_SLUG = '([^']+)'/.exec(readFileSync(inApp('config/app.ts'), 'utf8'))
|
|
358
|
+
if (!slugLine?.[1]) throw new CreateError("the template's config/app.ts declares no APP_SLUG")
|
|
359
|
+
const oldSlug = slugLine[1]
|
|
360
|
+
const oldName = readJson(inApp('messages/en.json'))?.welcome?.appName
|
|
361
|
+
if (typeof oldName !== 'string') throw new CreateError("the template's messages/en.json has no welcome.appName")
|
|
362
|
+
replaceOnce(inApp('config/app.ts'), `export const APP_SLUG = '${oldSlug}'`, `export const APP_SLUG = '${slug}'`)
|
|
363
|
+
replaceOnce(inApp('config/app.ts'), `\`${oldSlug}_session\``, `\`${slug}_session\``)
|
|
364
|
+
for (const locale of ['en', 'es']) {
|
|
365
|
+
for (const key of ['appName', 'title'])
|
|
366
|
+
replaceOnce(
|
|
367
|
+
inApp(`messages/${locale}.json`),
|
|
368
|
+
`"${key}": ${JSON.stringify(oldName)}`,
|
|
369
|
+
`"${key}": ${JSON.stringify(name)}`,
|
|
370
|
+
)
|
|
371
|
+
}
|
|
372
|
+
replaceOnce(inApp('src/app/[locale]/layout.tsx'), `title: ${tsString(oldName)}`, `title: ${tsString(name)}`)
|
|
373
|
+
replaceOnce(inApp('src/demo-static/index.html'), `<title>${oldName} `, `<title>${htmlText(name)} `)
|
|
374
|
+
// Prettier wraps an HTML line past the print width, so the title line must fit (displayName caps the name; `&`
|
|
375
|
+
// grows as it is escaped).
|
|
376
|
+
const titleLine = readFileSync(inApp('src/demo-static/index.html'), 'utf8')
|
|
377
|
+
.split('\n')
|
|
378
|
+
.find((line) => line.includes('<title>'))
|
|
379
|
+
if (titleLine && columns(titleLine) > 120)
|
|
380
|
+
throw new CreateError(`--name "${name}" is too long for the static demo's <title> line: shorten it`)
|
|
381
|
+
|
|
382
|
+
// The app's manifest: its name, the @sssb packages it installs, the seam linked as a package of the app's own
|
|
383
|
+
// (ADR-0014 part 1), and the lint fences' plugin and ESLint beside it. No `license`: the packages are private, and
|
|
384
|
+
// which licence the workspace takes (a LICENSE at its root) is the adopter's to choose, not the starter's to claim.
|
|
385
|
+
const manifest = readJson(inApp('package.json'))
|
|
386
|
+
manifest.name = slug
|
|
387
|
+
delete manifest.license
|
|
388
|
+
manifest.description = `${name}: the app.`
|
|
389
|
+
pinSssb(manifest, spec)
|
|
390
|
+
manifest.dependencies = sorted({ ...manifest.dependencies, [SEAM]: `workspace:${seamPackage(slug)}@*` })
|
|
391
|
+
manifest.devDependencies = sorted({
|
|
392
|
+
...manifest.devDependencies,
|
|
393
|
+
'@sssb/eslint-plugin': spec('eslint-plugin'),
|
|
394
|
+
eslint: /** @type {string} */ (meta.ranges['eslint']),
|
|
395
|
+
})
|
|
396
|
+
writeFileSync(inApp('package.json'), packageJson(manifest))
|
|
397
|
+
const budget = /sssb check-demo-size (\d+)/.exec(manifest.scripts?.['check:demo-size'] ?? '')?.[1]
|
|
398
|
+
if (!budget) throw new CreateError("the template's package.json has no `sssb check-demo-size <bytes>` script")
|
|
399
|
+
|
|
400
|
+
const infra = readJson(inApp('infra/package.json'))
|
|
401
|
+
infra.name = `${slug}-infra`
|
|
402
|
+
delete infra.license
|
|
403
|
+
pinSssb(infra, spec)
|
|
404
|
+
writeFileSync(inApp('infra/package.json'), packageJson(infra))
|
|
405
|
+
|
|
406
|
+
// The seam package (ADR-0014 part 1, option C): the app's src/app-config, a workspace package of the app's own name
|
|
407
|
+
// that the app takes under the name the framework imports (`@sssb/app-config`: `workspace:<slug>-app-config@*`),
|
|
408
|
+
// with an export for every module the framework imports. A workspace package, not a `link:`, because pnpm's
|
|
409
|
+
// partial installs for the app (`add <pkg>`, `remove`, `update <pkg>`) drop a `link:` dependency as the provider of
|
|
410
|
+
// @sssb/kit's peer (the 2026-11-18 addendum to ADR-0014). It takes the app's module `type`, because a nested package.json resets it for everything
|
|
411
|
+
// below it.
|
|
412
|
+
const seamDir = inApp('src/app-config')
|
|
413
|
+
/** @type {Record<string, unknown>} */
|
|
414
|
+
const seam = { name: seamPackage(slug), private: true }
|
|
415
|
+
if (manifest.type) seam['type'] = manifest.type
|
|
416
|
+
seam['exports'] = seamExports(seamDir, meta.seamSpecifiers)
|
|
417
|
+
writeFileSync(path.join(seamDir, 'package.json'), packageJson(seam))
|
|
418
|
+
|
|
419
|
+
// The app's tsconfig, on @sssb/tools' base: in SSSB's repository the starter's also sends @sssb/kit and the seam to
|
|
420
|
+
// source and compiles the framework's own tree (it is the framework's falsifier there). Here resolution goes
|
|
421
|
+
// through the installed packages and the seam link, so only the app's own `@/` alias stays.
|
|
422
|
+
const tsconfig = readJson(inApp('tsconfig.json'))
|
|
423
|
+
if (tsconfig.extends !== '@sssb/tools/tsconfig.base.json')
|
|
424
|
+
throw new CreateError(`the template's tsconfig.json extends ${tsconfig.extends}, not @sssb/tools' base`)
|
|
425
|
+
const own = (/** @type {string} */ entry) => !entry.startsWith('../')
|
|
426
|
+
tsconfig.compilerOptions.paths = { '@/*': tsconfig.compilerOptions.paths['@/*'] }
|
|
427
|
+
tsconfig.include = tsconfig.include.filter(own)
|
|
428
|
+
tsconfig.exclude = tsconfig.exclude.filter(own)
|
|
429
|
+
writeFileSync(inApp('tsconfig.json'), formatJson(tsconfig))
|
|
430
|
+
|
|
431
|
+
writeFileSync(inApp('eslint.config.mjs'), files.APP_ESLINT)
|
|
432
|
+
writeFileSync(inApp('DEMO-SIZE.md'), files.demoSizeMd(Number(budget)))
|
|
433
|
+
|
|
434
|
+
// The workspace around it.
|
|
435
|
+
/** @type {Record<string, string>} */
|
|
436
|
+
const written = {
|
|
437
|
+
'package.json': files.rootPackageJson(c),
|
|
438
|
+
'pnpm-workspace.yaml': files.pnpmWorkspace(c),
|
|
439
|
+
'.gitignore': files.GITIGNORE,
|
|
440
|
+
'.prettierignore': files.PRETTIERIGNORE,
|
|
441
|
+
'lint-staged.config.mjs': files.LINT_STAGED,
|
|
442
|
+
'eslint.config.mjs': files.ROOT_ESLINT,
|
|
443
|
+
'tsconfig.json': files.ROOT_TSCONFIG,
|
|
444
|
+
'vitest.config.ts': files.vitestConfig(c),
|
|
445
|
+
'vitest.contract.config.ts': files.vitestContractConfig(c),
|
|
446
|
+
'knip.json': files.knipJson(c),
|
|
447
|
+
'.jscpd.json': files.JSCPD,
|
|
448
|
+
'.gitleaks.toml': files.GITLEAKS,
|
|
449
|
+
CODEOWNERS: files.codeowners(c),
|
|
450
|
+
'SECURITY.md': files.securityMd(c),
|
|
451
|
+
'CODE_OF_CONDUCT.md': files.codeOfConduct(c),
|
|
452
|
+
'README.md': files.readme(c),
|
|
453
|
+
'CLAUDE.md': files.CLAUDE_MD,
|
|
454
|
+
'.claude/settings.json': files.claudeSettings(c),
|
|
455
|
+
'docs/cutover-checklist.md': files.cutoverChecklist(c),
|
|
456
|
+
'.github/workflows/checks.yml': files.workflow(c),
|
|
457
|
+
'.github/ISSUE_TEMPLATE/config.yml': files.issueConfig(c),
|
|
458
|
+
'.github/ISSUE_TEMPLATE/bug_report.yml': files.BUG_REPORT,
|
|
459
|
+
}
|
|
460
|
+
// The app guide's stamped copy, as `sssb guide` writes it (@sssb/tools' guide.js; the generator depends on no SSSB
|
|
461
|
+
// package): `sssb doctor` fails a workspace without it, and fails it again once an upgrade's guide differs.
|
|
462
|
+
const guide = readFileSync(path.join(templateDir, GUIDE_FILE))
|
|
463
|
+
written['.claude/sssb-guide.md'] =
|
|
464
|
+
`<!-- sssb-guide sha256:${createHash('sha256').update(guide).digest('hex')} (copied from @sssb/kit ` +
|
|
465
|
+
`${meta.version} by \`sssb guide\`: edit nothing here; rerun it after an upgrade and review the diff) -->\n\n` +
|
|
466
|
+
guide.toString('utf8')
|
|
467
|
+
for (const [relative, text] of Object.entries(written)) {
|
|
468
|
+
const file = path.join(root, relative)
|
|
469
|
+
mkdirSync(path.dirname(file), { recursive: true })
|
|
470
|
+
writeFileSync(file, text)
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const all = filesUnder(root)
|
|
474
|
+
// Nothing may still point at a workspace package this workspace does not have (the seam is one it has): a package
|
|
475
|
+
// is the workspace's when pnpm-workspace.yaml's `packages` globs (a `*` is one path segment) cover its directory.
|
|
476
|
+
const globs = readFileSync(path.join(root, 'pnpm-workspace.yaml'), 'utf8')
|
|
477
|
+
.split('\n\n')[0]
|
|
478
|
+
.split('\n')
|
|
479
|
+
.flatMap((line) => /^\s*-\s+(\S+)\s*$/.exec(line)?.[1] ?? [])
|
|
480
|
+
.map(
|
|
481
|
+
(glob) =>
|
|
482
|
+
new RegExp(
|
|
483
|
+
`^${glob
|
|
484
|
+
.split('*')
|
|
485
|
+
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
|
|
486
|
+
.join('[^/]+')}$`,
|
|
487
|
+
),
|
|
488
|
+
)
|
|
489
|
+
const manifests = all
|
|
490
|
+
.filter((f) => path.basename(f) === 'package.json')
|
|
491
|
+
.map((file) => {
|
|
492
|
+
try {
|
|
493
|
+
return { file, json: readJson(path.join(root, file)) }
|
|
494
|
+
} catch (err) {
|
|
495
|
+
throw new CreateError(`${file} is not valid JSON: ${/** @type {Error} */ (err).message}`)
|
|
496
|
+
}
|
|
497
|
+
})
|
|
498
|
+
const member = (/** @type {string} */ file) => {
|
|
499
|
+
const dir = path.dirname(file).split(path.sep).join('/')
|
|
500
|
+
return dir === '.' || globs.some((glob) => glob.test(dir))
|
|
501
|
+
}
|
|
502
|
+
const names = new Set(manifests.filter(({ file }) => member(file)).map(({ json }) => json.name))
|
|
503
|
+
for (const { file, json } of manifests) {
|
|
504
|
+
for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
|
|
505
|
+
for (const [dep, spec] of Object.entries(json[field] ?? {})) {
|
|
506
|
+
if (typeof spec !== 'string' || !spec.startsWith('workspace:')) continue
|
|
507
|
+
// `workspace:<name>@<range>` takes the package <name> under the alias `dep`; any other form, `dep`.
|
|
508
|
+
const target = /^(@?[^@]+)@/.exec(spec.slice('workspace:'.length))?.[1] ?? dep
|
|
509
|
+
if (!names.has(target))
|
|
510
|
+
throw new CreateError(
|
|
511
|
+
`${file} still depends on ${target} by workspace: protocol, a package it lacks`,
|
|
512
|
+
)
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return all
|
|
517
|
+
}
|
package/src/json.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// JSON written the way the generated workspace's own Prettier would write it, so its first `pnpm lint` (which runs
|
|
3
|
+
// `prettier --check .`) is green with no formatting pass: the generator has no dependencies, Prettier included.
|
|
4
|
+
//
|
|
5
|
+
// Prettier formats `package.json` with its `json-stringify` parser, which is JSON.stringify's layout (`packageJson`).
|
|
6
|
+
// Every other `.json` file gets its `json` parser (`formatJson`): an object that was written across lines stays across
|
|
7
|
+
// lines, and an array of plain values goes on one line when that line fits the print width (the workspace's
|
|
8
|
+
// `.editorconfig` sets 120 columns and an indent of 4). tests/tooling/create-generate.test.ts runs Prettier over the
|
|
9
|
+
// output to hold both to it.
|
|
10
|
+
|
|
11
|
+
const INDENT = ' '
|
|
12
|
+
const WIDTH = 120
|
|
13
|
+
|
|
14
|
+
/** @param {unknown} value */
|
|
15
|
+
const isPlain = (value) => value === null || typeof value !== 'object'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {unknown} value
|
|
19
|
+
* @param {number} depth
|
|
20
|
+
* @param {number} prefix the columns already taken on the line this value starts on
|
|
21
|
+
* @returns {string}
|
|
22
|
+
*/
|
|
23
|
+
function format(value, depth, prefix) {
|
|
24
|
+
if (isPlain(value)) return JSON.stringify(value)
|
|
25
|
+
const inner = INDENT.repeat(depth + 1)
|
|
26
|
+
const outer = INDENT.repeat(depth)
|
|
27
|
+
if (Array.isArray(value)) {
|
|
28
|
+
if (value.length === 0) return '[]'
|
|
29
|
+
if (value.every(isPlain)) {
|
|
30
|
+
const line = `[${value.map((item) => JSON.stringify(item)).join(', ')}]`
|
|
31
|
+
// The trailing comma Prettier may add after it counts against the width.
|
|
32
|
+
if (prefix + line.length + 1 <= WIDTH) return line
|
|
33
|
+
}
|
|
34
|
+
return `[\n${value.map((item) => `${inner}${format(item, depth + 1, inner.length)}`).join(',\n')}\n${outer}]`
|
|
35
|
+
}
|
|
36
|
+
const entries = Object.entries(/** @type {Record<string, unknown>} */ (value))
|
|
37
|
+
if (entries.length === 0) return '{}'
|
|
38
|
+
return `{\n${entries
|
|
39
|
+
.map(([key, item]) => {
|
|
40
|
+
const head = `${inner}${JSON.stringify(key)}: `
|
|
41
|
+
return `${head}${format(item, depth + 1, head.length)}`
|
|
42
|
+
})
|
|
43
|
+
.join(',\n')}\n${outer}}`
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A `.json` file's text, as Prettier's `json` parser lays it out.
|
|
48
|
+
* @param {unknown} value
|
|
49
|
+
*/
|
|
50
|
+
export function formatJson(value) {
|
|
51
|
+
return `${format(value, 0, 0)}\n`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A `package.json`'s text, as Prettier's `json-stringify` parser (and npm) lay it out.
|
|
56
|
+
* @param {unknown} value
|
|
57
|
+
*/
|
|
58
|
+
export function packageJson(value) {
|
|
59
|
+
return `${JSON.stringify(value, null, 4)}\n`
|
|
60
|
+
}
|
package/src/signals.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// SIGNALS while the generator writes. Its work is synchronous (a template built into a temporary directory, a workspace
|
|
3
|
+
// written), so a signal's default action would end the process part-way and leave that work behind. While work is under
|
|
4
|
+
// way a listener defers the signal instead: Node runs it on a later turn of the event loop, where it undoes everything
|
|
5
|
+
// still under way and raises the signal again, for the process to end as it was asked.
|
|
6
|
+
import { setImmediate } from 'node:timers'
|
|
7
|
+
|
|
8
|
+
/** What ends the process part-way: Ctrl-C, a kill, the terminal closing. */
|
|
9
|
+
const SIGNALS = /** @type {const} */ (['SIGINT', 'SIGTERM', 'SIGHUP'])
|
|
10
|
+
|
|
11
|
+
/** How to undo each piece of work under way. @type {Set<() => void>} */
|
|
12
|
+
const underWay = new Set()
|
|
13
|
+
|
|
14
|
+
/** @param {boolean} on */
|
|
15
|
+
function listen(on) {
|
|
16
|
+
for (const signal of SIGNALS) {
|
|
17
|
+
if (on) process.on(signal, onSignal)
|
|
18
|
+
else process.off(signal, onSignal)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {NodeJS.Signals} signal */
|
|
23
|
+
function onSignal(signal) {
|
|
24
|
+
// Every undo runs, one failing or not (what it could not remove stays), and the signal is raised again regardless.
|
|
25
|
+
for (const undo of underWay) {
|
|
26
|
+
try {
|
|
27
|
+
undo()
|
|
28
|
+
} catch {
|
|
29
|
+
// nothing more to do for it
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
underWay.clear()
|
|
33
|
+
listen(false)
|
|
34
|
+
process.kill(process.pid, signal)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Defers SIGINT, SIGTERM and SIGHUP until `undo`'s work is released; a signal that comes meanwhile runs `undo` (and
|
|
39
|
+
* every other undo still held). Call it before the work makes anything.
|
|
40
|
+
* @param {() => void} undo
|
|
41
|
+
*/
|
|
42
|
+
export function holdSignals(undo) {
|
|
43
|
+
if (underWay.size === 0) listen(true)
|
|
44
|
+
underWay.add(undo)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Resolves two turns of the event loop from now. A signal that arrived before the call is dispatched by then: libuv
|
|
49
|
+
* reads a pending signal only in the event loop's poll phase, and the first turn's check phase can come straight after
|
|
50
|
+
* the poll phase the caller is running in (`main()` resumes from the confirmation prompt's stdin callback, a poll
|
|
51
|
+
* callback), so only the second turn is sure to pass through a poll phase first.
|
|
52
|
+
* @returns {Promise<void>}
|
|
53
|
+
*/
|
|
54
|
+
export function signalsSettled() {
|
|
55
|
+
return new Promise((resolve) => setImmediate(() => setImmediate(resolve)))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Lets the signals go again for `undo`'s work, two turns from now (signalsSettled): a signal that arrived while the
|
|
60
|
+
* work ran is dispatched before then and still finds `undo` to run, even when the work finished. One that arrives
|
|
61
|
+
* after the work returned is not promised either way: it may undo the work, or (in the last turn, as the listener
|
|
62
|
+
* goes) be dropped, or end the process by its default action; the work it finds then is finished.
|
|
63
|
+
* @param {() => void} undo
|
|
64
|
+
*/
|
|
65
|
+
export function releaseSignals(undo) {
|
|
66
|
+
setImmediate(() =>
|
|
67
|
+
setImmediate(() => {
|
|
68
|
+
underWay.delete(undo)
|
|
69
|
+
if (underWay.size === 0) listen(false)
|
|
70
|
+
}),
|
|
71
|
+
)
|
|
72
|
+
}
|