create-typeser 2.0.0 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/project.mjs CHANGED
@@ -1,184 +1,211 @@
1
- import {execFileSync} from 'node:child_process';
2
- import {createHash, randomBytes} from 'node:crypto';
3
- import {cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync,
4
- readdirSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync} from 'node:fs';
5
- import {createServer} from 'node:net';
6
- import path from 'node:path';
7
- import {tmpdir} from 'node:os';
8
-
9
- export function readJson(file) { return JSON.parse(readFileSync(file, 'utf8')); }
10
- export function writeJson(file, value) { writeFileSync(file, JSON.stringify(value, null, 2) + '\n', {mode: 0o600}); }
11
-
12
- export function physicalPath(value) {
13
- const target = path.resolve(value);
14
- const root = path.parse(target).root;
15
- let cursor = root;
16
- for (const part of target.slice(root.length).split(path.sep).filter(Boolean)) {
17
- cursor = path.join(cursor, part);
18
- const info = lstatSync(cursor, {throwIfNoEntry: false});
19
- if (info && (info.isSymbolicLink() || path.relative(cursor, realpathSync(cursor)) !== ''))
20
- throw new Error('Choose a physical path without links or junctions: ' + cursor);
21
- }
22
- return target;
23
- }
24
-
25
- // npm uses the caller's configured registry and integrity-checked cache.
26
- export function registryPlatform(version) {
27
- if (!/^(?:latest|next|\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.test(version))
28
- throw new Error('Expected an exact TypeSer version, latest or next.');
29
- if (!process.env.npm_execpath) throw new Error('Start the initializer with npm create typeser.');
30
- const stage = mkdtempSync(path.join(realpathSync(tmpdir()), 'typeser-manifest-'));
31
- try {
32
- const info = JSON.parse(execFileSync(process.execPath, [process.env.npm_execpath, 'pack', 'typeser@' + version,
33
- '--ignore-scripts', '--json', '--pack-destination', stage], {encoding: 'utf8', windowsHide: true}))[0];
34
- if (!info || path.basename(info.filename) !== info.filename) throw new Error('Unexpected npm archive name');
35
- const release = inspectArchive(path.join(stage, info.filename));
36
- return {...release, tgz: null};
37
- } finally { rmSync(stage, {recursive: true, force: true}); }
38
- }
39
-
40
- export function inspectArchive(file) {
41
- const tgz = physicalPath(file);
42
- if (!tgz.endsWith('.tgz') || !statSync(tgz, {throwIfNoEntry: false})?.isFile()) throw new Error('Select a local typeser-<version>.tgz file');
43
- const manifest = member => JSON.parse(execFileSync('tar', ['-xOf', tgz, 'package/' + member], {encoding: 'utf8', windowsHide: true}));
44
- const platform = manifest('package.json');
45
- if (platform.name !== 'typeser' || !platform.bin?.typeser) throw new Error('The selected archive must contain the TypeSer platform');
46
- if (!platform.exports?.['./local-runtime']) throw new Error('This initializer needs the platform-managed launcher from TypeSer 2.0. Select a compatible platform archive.');
47
- const template = manifest('solutions.demo/empty_template/package.json');
48
- if (!template.dependencies?.typeser || !template.devDependencies?.vite) throw new Error('The archive is missing the standalone blank application');
49
- return {tgz, version: platform.version, template, optionalModules: platform.peerDependencies};
50
- }
51
-
52
- export async function freePort(port) {
53
- return await new Promise(resolve => {
54
- const server = createServer();
55
- server.once('error', () => resolve(false));
56
- server.listen(port, '127.0.0.1', () => server.close(() => resolve(true)));
57
- });
58
- }
59
-
60
- export function assignedOffsets(withDemo) {
61
- const offsets = [0, 1, 10, 11, 12, 20, 21, 22, 32, 39];
62
- if (withDemo) for (const base of [50, 60, 70, 80, 90, 100]) offsets.push(base, base + 1, base + 2);
63
- return offsets;
64
- }
65
-
66
- export async function portBase(root, withDemo = false) {
67
- const seed = createHash('sha256').update(root).digest().readUInt16BE();
68
- for (let attempt = 0; attempt < 220; attempt++) {
69
- const base = 18000 + ((seed + attempt) % 220) * 150;
70
- if ((await Promise.all([...assignedOffsets(withDemo), 40].map(n => freePort(base + n)))).every(Boolean)) return base;
71
- }
72
- throw new Error('Could not allocate local TypeSer ports');
73
- }
74
-
75
- export function makeRegistry(platform, plan) {
76
- const {schema, database, base} = plan;
77
- const defaults = readJson(path.join(platform, 'common-resources/typeser-demo-apps.json'));
78
- const applications = {};
79
- for (const [site, offset] of [['dba', 0], ['auth', 10], ['app', 20]]) {
80
- const original = defaults.applications['empty_template.' + site];
81
- const sourcePath = site === 'app' ? 'solutions/' + schema + '/app' : 'node_modules/typeser/' + original.sourcePath;
82
- const name = site === 'app' ? plan.name : plan.name + (site === 'dba' ? ' Configurator' : ' Authentication');
83
- applications[schema + '.' + site] = {...original, name, schema, sourcePath, groups: [schema],
84
- assets: {...original.assets, publicDir: sourcePath + '/public'},
85
- targets: {dev: {...original.targets.dev, entryPointId: base + offset}}};
86
- }
87
- const schemas = {[schema]: {...defaults.schemas.empty_template, name: plan.name, sourcePath: 'solutions/' + schema,
88
- targets: {dev: {authOrigin: 'http://localhost:' + (base + 11)}}}};
89
- if (plan.withDemo) {
90
- const demo = defaults.schemas.demo_typeser;
91
- schemas.demo_typeser = {...demo, sourcePath: 'node_modules/typeser/' + demo.sourcePath,
92
- targets: {dev: {authOrigin: 'http://localhost:' + (base + 61)}}};
93
- const offsets = {dba: 50, auth: 60, app: 70, integration: 80, warehouse: 90, public: 100};
94
- for (const [site, offset] of Object.entries(offsets)) {
95
- const key = 'demo_typeser.' + site;
96
- const app = defaults.applications[key];
97
- applications[key] = {...app, sourcePath: 'node_modules/typeser/' + app.sourcePath,
98
- assets: {...app.assets, publicDir: 'node_modules/typeser/' + app.assets.publicDir},
99
- targets: {dev: {...app.targets.dev, entryPointId: base + offset}}};
100
- }
101
- }
102
- return {version: 1, environments: {dev: {...defaults.environments.dev, database, authoringPort: base + 32}},
103
- schemas, assets: {}, applications};
104
- }
105
-
106
- function protectSecrets(directory) {
107
- mkdirSync(directory, {mode: 0o700});
108
- if (process.platform !== 'win32') return;
109
- const system = path.join(process.env.SystemRoot, 'System32');
110
- const identity = execFileSync(path.join(system, 'whoami.exe'), ['/user', '/fo', 'csv', '/nh'], {windowsHide: true}).toString('latin1');
111
- const sid = identity.match(/"(S-1-[\d-]+)"\s*$/i)?.[1];
112
- if (!sid) throw new Error('Could not identify the current Windows account for the secrets directory');
113
- execFileSync(path.join(system, 'icacls.exe'), [directory, '/inheritance:r', '/grant:r', '*' + sid + ':(OI)(CI)F', '/q'], {windowsHide: true});
114
- }
115
-
116
- export function assertAvailable(root) {
117
- if (root === path.parse(root).root || path.basename(root).toLowerCase() === 'node_modules')
118
- throw new Error('Choose a new application directory');
119
- if (existsSync(root) && (!statSync(root).isDirectory() || readdirSync(root).length))
120
- throw new Error('Directory already contains files. Choose a new or empty application directory: ' + root);
121
- }
122
-
123
- export function scaffold(root, archive, plan, password) {
124
- const parent = path.dirname(root);
125
- mkdirSync(parent, {recursive: true});
126
- const stage = mkdtempSync(path.join(parent, '.typeser-create-'));
127
- try {
128
- const manifest = archive.template;
129
- manifest.name = plan.name;
130
- manifest.dependencies.typeser = archive.tgz ? 'file:' + path.relative(root, archive.tgz).split(path.sep).join('/') : archive.version;
131
- for (const id of [...((plan.withDemo || plan['with-qr']) ? ['qrcode'] : []),
132
- ...((plan.withDemo || plan['with-mcp']) ? ['@modelcontextprotocol/client', '@modelcontextprotocol/core', '@modelcontextprotocol/ext-apps'] : [])]) {
133
- const version = archive.optionalModules?.[id];
134
- if (!version) throw new Error('This platform archive does not declare the optional module ' + id);
135
- manifest.dependencies[id] = version;
136
- }
137
- delete manifest.imports; // These package-local aliases belong to the bundled configurator.
138
- manifest.scripts.dev = 'typeser dev';
139
- manifest.scripts.build = 'typeser build ' + plan.schema + '.app';
140
- manifest.scripts['save:ts'] = 'typeser save-to-ts dev ' + plan.schema;
141
- manifest.scripts['save:sites'] = 'typeser save-sites dev ' + plan.schema;
142
- manifest.scripts['save:pg'] = 'typeser save-to-pg dev ' + plan.schema;
143
- writeJson(path.join(stage, 'package.json'), manifest);
144
- if (!process.env.npm_execpath) throw new Error('Start this installer with npm create typeser');
145
- console.log('Installing typeser ' + archive.version + ' and the application dependencies...');
146
- execFileSync(process.execPath, [process.env.npm_execpath, 'install', '--include=dev', '--workspaces=false', '--no-fund', '--no-audit'],
147
- {cwd: stage, windowsHide: true, stdio: 'inherit'});
148
- const platform = path.join(stage, 'node_modules/typeser');
149
- const source = path.join(platform, 'solutions.demo/empty_template');
150
- const configuration = path.join(stage, 'solutions', plan.schema);
151
- mkdirSync(configuration, {recursive: true});
152
- for (const name of ['app', 'forms', 'triggers', 'md.tsx', 'md-forms.tsx']) {
153
- cpSync(path.join(source, name), path.join(configuration, name), {recursive: true,
154
- filter: entry => physicalPath(entry) !== path.join(source, 'app', 'launcher.tsx')});
155
- }
156
- const tsconfig = readJson(path.join(source, 'tsconfig.json'));
157
- tsconfig.include = tsconfig.include.filter(directory => directory !== 'dba').map(directory => 'solutions/' + plan.schema + '/' + directory);
158
- writeJson(path.join(stage, 'tsconfig.json'), tsconfig);
159
- for (const [name, placeholder] of [['md.tsx', 'Blank application'], ['forms/empty_home.tsx', 'Blank application'], ['app/index.html', 'TypeSer blank app']]) {
160
- const file = path.join(configuration, name);
161
- writeFileSync(file, readFileSync(file, 'utf8').replaceAll(placeholder, plan.name));
162
- }
163
- writeFileSync(path.join(stage, 'AGENTS.md'), '# Application development\n\nRead the [TypeSer guide](node_modules/typeser/docs/README.md). Edit this application in `solutions/' + plan.schema + '/`. Use `npm run typecheck` and the configuration save scripts in package.json.\n');
164
- mkdirSync(path.join(stage, 'java'));
165
- const pom = readFileSync(path.join(platform, 'src/maven/application-pom.xml'), 'utf8');
166
- writeFileSync(path.join(stage, 'java/pom.xml'), pom.replace('<groupId>example</groupId>', '<groupId>local</groupId>')
167
- .replace('<artifactId>application-module</artifactId>', '<artifactId>' + plan.name + '-module</artifactId>'));
168
- writeJson(path.join(stage, 'typeser-apps.json'), makeRegistry(platform, plan));
169
- writeFileSync(path.join(stage, '.gitignore'), 'node_modules/\n/secrets/\n/.local/\ndist/\ntarget/\n*.log\n');
170
- mkdirSync(path.join(stage, '.local'), {mode: 0o700});
171
- writeJson(path.join(stage, '.local/create-typeser.json'), plan);
172
- protectSecrets(path.join(stage, 'secrets'));
173
- const host = plan.host === '::1' ? '[::1]' : plan.host;
174
- writeJson(path.join(stage, 'secrets/dev-secrets.json'), {
175
- TYPESER_DATABASE_URL: 'jdbc:postgresql://' + host + ':' + plan.port + '/' + plan.database,
176
- TYPESER_DATABASE_USER: plan.user, TYPESER_DATABASE_PASSWORD: password, TYPESER_DEPLOY_TOKEN: randomBytes(32).toString('hex'),
177
- });
178
- assertAvailable(root);
179
- if (existsSync(root)) rmdirSync(root); // Only an empty directory can be replaced.
180
- renameSync(stage, root);
181
- } finally {
182
- if (existsSync(stage) && path.dirname(realpathSync(stage)) === realpathSync(parent)) rmSync(stage, {recursive: true, force: true});
183
- }
184
- }
1
+ import {execFileSync} from 'node:child_process';
2
+ import {createHash, randomBytes} from 'node:crypto';
3
+ import {chmodSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync,
4
+ readdirSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync} from 'node:fs';
5
+ import {createServer} from 'node:net';
6
+ import path from 'node:path';
7
+ import {tmpdir} from 'node:os';
8
+
9
+ export function readJson(file) { return JSON.parse(readFileSync(file, 'utf8')); }
10
+ export function writeJson(file, value) { writeFileSync(file, JSON.stringify(value, null, 2) + '\n', {mode: 0o600}); }
11
+
12
+ export function physicalPath(value) {
13
+ const target = path.resolve(value);
14
+ const root = path.parse(target).root;
15
+ let cursor = root;
16
+ for (const part of target.slice(root.length).split(path.sep).filter(Boolean)) {
17
+ cursor = path.join(cursor, part);
18
+ const info = lstatSync(cursor, {throwIfNoEntry: false});
19
+ if (info && (info.isSymbolicLink() || path.relative(cursor, realpathSync(cursor)) !== ''))
20
+ throw new Error('Choose a physical path without links or junctions: ' + cursor);
21
+ }
22
+ return target;
23
+ }
24
+
25
+ // npm uses the caller's configured registry and integrity-checked cache.
26
+ export function registryPlatform(version) {
27
+ if (!/^(?:latest|next|\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.test(version))
28
+ throw new Error('Expected an exact TypeSer version, latest or next.');
29
+ if (!process.env.npm_execpath) throw new Error('Start the initializer with npm create typeser.');
30
+ const stage = mkdtempSync(path.join(realpathSync(tmpdir()), 'typeser-manifest-'));
31
+ try {
32
+ const info = JSON.parse(execFileSync(process.execPath, [process.env.npm_execpath, 'pack', 'typeser@' + version,
33
+ '--ignore-scripts', '--json', '--pack-destination', stage], {encoding: 'utf8', windowsHide: true}))[0];
34
+ if (!info || path.basename(info.filename) !== info.filename) throw new Error('Unexpected npm archive name');
35
+ const release = inspectArchive(path.join(stage, info.filename));
36
+ return {...release, tgz: null};
37
+ } finally { rmSync(stage, {recursive: true, force: true}); }
38
+ }
39
+
40
+ export function inspectArchive(file) {
41
+ const tgz = physicalPath(file);
42
+ if (!tgz.endsWith('.tgz') || !statSync(tgz, {throwIfNoEntry: false})?.isFile()) throw new Error('Select a local typeser-<version>.tgz file');
43
+ const manifest = member => JSON.parse(execFileSync('tar', ['-xOf', tgz, 'package/' + member], {encoding: 'utf8', windowsHide: true}));
44
+ const platform = manifest('package.json');
45
+ if (platform.name !== 'typeser' || !platform.bin?.typeser) throw new Error('The selected archive must contain the TypeSer platform');
46
+ if (!platform.exports?.['./local-runtime']) throw new Error('This initializer needs the platform-managed launcher from TypeSer 2.0. Select a compatible platform archive.');
47
+ const template = manifest('solutions.demo/empty_template/package.json');
48
+ if (!template.dependencies?.typeser || !template.devDependencies?.vite) throw new Error('The archive is missing the standalone blank application');
49
+ if (platform.typeserHost !== undefined && !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(platform.typeserHost))
50
+ throw new Error('Expected an exact typeserHost version in the platform manifest');
51
+ return {tgz, version: platform.version, typeserHost: platform.typeserHost, template, optionalModules: platform.peerDependencies};
52
+ }
53
+
54
+ export async function freePort(port) {
55
+ return await new Promise(resolve => {
56
+ const server = createServer();
57
+ server.once('error', () => resolve(false));
58
+ server.listen(port, '127.0.0.1', () => server.close(() => resolve(true)));
59
+ });
60
+ }
61
+
62
+ export function assignedOffsets(withDemo) {
63
+ const offsets = [0, 1, 10, 11, 12, 20, 21, 22, 32, 39];
64
+ if (withDemo) for (const base of [50, 60, 70, 80, 90, 100]) offsets.push(base, base + 1, base + 2);
65
+ return offsets;
66
+ }
67
+
68
+ export async function portBase(root, withDemo = false) {
69
+ const seed = createHash('sha256').update(root).digest().readUInt16BE();
70
+ for (let attempt = 0; attempt < 220; attempt++) {
71
+ const base = 18000 + ((seed + attempt) % 220) * 150;
72
+ if ((await Promise.all([...assignedOffsets(withDemo), 40].map(n => freePort(base + n)))).every(Boolean)) return base;
73
+ }
74
+ throw new Error('Could not allocate local TypeSer ports');
75
+ }
76
+
77
+ export function makeRegistry(platform, plan) {
78
+ const {schema, database, base} = plan;
79
+ const defaults = readJson(path.join(platform, 'common-resources/typeser-demo-apps.json'));
80
+ const applications = {};
81
+ for (const [site, offset] of [['dba', 0], ['auth', 10], ['app', 20]]) {
82
+ const original = defaults.applications['empty_template.' + site];
83
+ const sourcePath = site === 'app' ? 'solutions/' + schema + '/app' : 'node_modules/typeser/' + original.sourcePath;
84
+ const name = site === 'app' ? plan.name : plan.name + (site === 'dba' ? ' Configurator' : ' Authentication');
85
+ applications[schema + '.' + site] = {...original, name, schema, sourcePath, groups: [schema],
86
+ assets: {...original.assets, publicDir: sourcePath + '/public'},
87
+ targets: {dev: {...original.targets.dev, entryPointId: base + offset}}};
88
+ }
89
+ const schemas = {[schema]: {...defaults.schemas.empty_template, name: plan.name, sourcePath: 'solutions/' + schema,
90
+ targets: {dev: {authOrigin: 'http://localhost:' + (base + 11)}}}};
91
+ if (plan.withDemo) {
92
+ const demo = defaults.schemas.demo_typeser;
93
+ schemas.demo_typeser = {...demo, sourcePath: 'node_modules/typeser/' + demo.sourcePath,
94
+ targets: {dev: {authOrigin: 'http://localhost:' + (base + 61)}}};
95
+ const offsets = {dba: 50, auth: 60, app: 70, integration: 80, warehouse: 90, public: 100};
96
+ for (const [site, offset] of Object.entries(offsets)) {
97
+ const key = 'demo_typeser.' + site;
98
+ const app = defaults.applications[key];
99
+ applications[key] = {...app, sourcePath: 'node_modules/typeser/' + app.sourcePath,
100
+ assets: {...app.assets, publicDir: 'node_modules/typeser/' + app.assets.publicDir},
101
+ targets: {dev: {...app.targets.dev, entryPointId: base + offset}}};
102
+ }
103
+ }
104
+ return {version: 1, environments: {dev: {...defaults.environments.dev, database, authoringPort: base + 32}},
105
+ schemas, assets: {}, applications};
106
+ }
107
+
108
+ function protectSecrets(directory) {
109
+ mkdirSync(directory, {mode: 0o700});
110
+ if (process.platform !== 'win32') return;
111
+ const system = path.join(process.env.SystemRoot, 'System32');
112
+ const identity = execFileSync(path.join(system, 'whoami.exe'), ['/user', '/fo', 'csv', '/nh'], {windowsHide: true}).toString('latin1');
113
+ const sid = identity.match(/"(S-1-[\d-]+)"\s*$/i)?.[1];
114
+ if (!sid) throw new Error('Could not identify the current Windows account for the secrets directory');
115
+ execFileSync(path.join(system, 'icacls.exe'), [directory, '/inheritance:r', '/grant:r', '*' + sid + ':(OI)(CI)F', '/q'], {windowsHide: true});
116
+ }
117
+
118
+ export function assertAvailable(root) {
119
+ if (root === path.parse(root).root || path.basename(root).toLowerCase() === 'node_modules')
120
+ throw new Error('Choose a new application directory');
121
+ if (existsSync(root) && (!statSync(root).isDirectory() || readdirSync(root).length))
122
+ throw new Error('Directory already contains files. Choose a new or empty application directory: ' + root);
123
+ }
124
+
125
+ export function scaffold(root, archive, plan, password) {
126
+ const parent = path.dirname(root);
127
+ mkdirSync(parent, {recursive: true});
128
+ const stage = mkdtempSync(path.join(parent, '.typeser-create-'));
129
+ try {
130
+ const manifest = archive.template;
131
+ manifest.name = plan.name;
132
+ manifest.dependencies.typeser = archive.tgz ? 'file:' + path.relative(root, archive.tgz).split(path.sep).join('/') : archive.version;
133
+ if (archive.typeserHost) {
134
+ manifest.typeser = {...manifest.typeser, javaHost: plan.javaHost};
135
+ if (plan.javaHost === 'binary') {
136
+ const version = archive.typeserHost;
137
+ if (archive.tgz) {
138
+ const file = physicalPath(path.join(path.dirname(archive.tgz), 'typeser-java-host-' + version + '.tgz'));
139
+ if (!statSync(file, {throwIfNoEntry: false})?.isFile()) throw new Error('Place the matching host archive beside the platform archive: ' + file);
140
+ const host = JSON.parse(execFileSync('tar', ['-xOf', file, 'package/package.json'], {encoding: 'utf8', windowsHide: true}));
141
+ execFileSync('tar', ['-tf', file, 'package/typeser-host.jar'], {windowsHide: true, stdio: 'ignore'});
142
+ if (host.name !== '@typeser/java-host' || host.version !== version) throw new Error('Incorrect Java host archive: ' + file);
143
+ manifest.dependencies['@typeser/java-host'] = 'file:' + path.relative(root, file).split(path.sep).join('/');
144
+ } else manifest.dependencies['@typeser/java-host'] = version;
145
+ }
146
+ }
147
+ for (const id of [...((plan.withDemo || plan['with-qr']) ? ['qrcode'] : []),
148
+ ...((plan.withDemo || plan['with-mcp']) ? ['@modelcontextprotocol/client', '@modelcontextprotocol/core', '@modelcontextprotocol/ext-apps'] : [])]) {
149
+ const version = archive.optionalModules?.[id];
150
+ if (!version) throw new Error('This platform archive does not declare the optional module ' + id);
151
+ manifest.dependencies[id] = version;
152
+ }
153
+ delete manifest.imports; // These package-local aliases belong to the bundled configurator.
154
+ manifest.scripts.dev = 'typeser dev';
155
+ manifest.scripts.build = 'typeser build ' + plan.schema + '.app';
156
+ manifest.scripts['save:ts'] = 'typeser save-to-ts dev ' + plan.schema;
157
+ manifest.scripts['save:sites'] = 'typeser save-sites dev ' + plan.schema;
158
+ manifest.scripts['save:pg'] = 'typeser save-to-pg dev ' + plan.schema;
159
+ writeJson(path.join(stage, 'package.json'), manifest);
160
+ if (!process.env.npm_execpath) throw new Error('Start this installer with npm create typeser');
161
+ console.log('Installing typeser ' + archive.version + ' and the application dependencies...');
162
+ execFileSync(process.execPath, [process.env.npm_execpath, 'install', '--include=dev', '--workspaces=false', '--no-fund', '--no-audit'],
163
+ {cwd: stage, windowsHide: true, stdio: 'inherit'});
164
+ const platform = path.join(stage, 'node_modules/typeser');
165
+ const source = path.join(platform, 'solutions.demo/empty_template');
166
+ const configuration = path.join(stage, 'solutions', plan.schema);
167
+ mkdirSync(configuration, {recursive: true});
168
+ for (const name of ['app', 'forms', 'triggers', 'md.tsx', 'md-forms.tsx']) {
169
+ cpSync(path.join(source, name), path.join(configuration, name), {recursive: true,
170
+ filter: entry => physicalPath(entry) !== path.join(source, 'app', 'launcher.tsx')});
171
+ }
172
+ const tsconfig = readJson(path.join(source, 'tsconfig.json'));
173
+ tsconfig.include = tsconfig.include.filter(directory => directory !== 'dba').map(directory => 'solutions/' + plan.schema + '/' + directory);
174
+ writeJson(path.join(stage, 'tsconfig.json'), tsconfig);
175
+ for (const [name, placeholder] of [['md.tsx', 'Blank application'], ['forms/empty_home.tsx', 'Blank application'], ['app/index.html', 'TypeSer blank app']]) {
176
+ const file = path.join(configuration, name);
177
+ writeFileSync(file, readFileSync(file, 'utf8').replaceAll(placeholder, plan.name));
178
+ }
179
+ writeFileSync(path.join(stage, 'AGENTS.md'), '# Application development\n\nRead the [TypeSer guide](node_modules/typeser/docs/README.md). Edit this application in `solutions/' + plan.schema + '/`. Use `npm run typecheck` and the configuration save scripts in package.json.\n');
180
+ mkdirSync(path.join(stage, 'java'));
181
+ const maven = path.join(platform, 'src/maven');
182
+ const pom = readFileSync(path.join(maven, plan.javaHost === 'source' ? 'source-pom.xml' : 'application-pom.xml'), 'utf8');
183
+ if (plan.javaHost === 'source') {
184
+ const java = path.join(stage, 'java');
185
+ mkdirSync(path.join(java, '.mvn/wrapper'), {recursive: true});
186
+ for (const file of ['mvnw', 'mvnw.cmd']) cpSync(path.join(maven, 'wrapper', file), path.join(java, file));
187
+ chmodSync(path.join(java, 'mvnw'), 0o755);
188
+ cpSync(path.join(maven, 'wrapper/maven-wrapper.properties'), path.join(java, '.mvn/wrapper/maven-wrapper.properties'));
189
+ cpSync(path.join(maven, 'wrapper/NOTICE'), path.join(java, '.mvn/wrapper/NOTICE'));
190
+ cpSync(path.join(platform, 'LICENSE'), path.join(java, '.mvn/wrapper/LICENSE'));
191
+ }
192
+ writeFileSync(path.join(stage, 'java/pom.xml'), pom.replace('<groupId>example</groupId>', '<groupId>local</groupId>')
193
+ .replace('<artifactId>application-module</artifactId>', '<artifactId>' + plan.name + '-module</artifactId>')
194
+ .replace('>HOST_VERSION<', '>' + archive.typeserHost + '<'));
195
+ writeJson(path.join(stage, 'typeser-apps.json'), makeRegistry(platform, plan));
196
+ writeFileSync(path.join(stage, '.gitignore'), 'node_modules/\n/secrets/\n/.local/\ndist/\ntarget/\n*.log\n');
197
+ mkdirSync(path.join(stage, '.local'), {mode: 0o700});
198
+ writeJson(path.join(stage, '.local/create-typeser.json'), plan);
199
+ protectSecrets(path.join(stage, 'secrets'));
200
+ const host = plan.host === '::1' ? '[::1]' : plan.host;
201
+ writeJson(path.join(stage, 'secrets/dev-secrets.json'), {
202
+ TYPESER_DATABASE_URL: 'jdbc:postgresql://' + host + ':' + plan.port + '/' + plan.database,
203
+ TYPESER_DATABASE_USER: plan.user, TYPESER_DATABASE_PASSWORD: password, TYPESER_DEPLOY_TOKEN: randomBytes(32).toString('hex'),
204
+ });
205
+ assertAvailable(root);
206
+ if (existsSync(root)) rmdirSync(root); // Only an empty directory can be replaced.
207
+ renameSync(stage, root);
208
+ } finally {
209
+ if (existsSync(stage) && path.dirname(realpathSync(stage)) === realpathSync(parent)) rmSync(stage, {recursive: true, force: true});
210
+ }
211
+ }
@@ -0,0 +1,68 @@
1
+ -- Run with psql as the selected PostgreSQL administrator in the local server's maintenance database.
2
+ SET search_path = pg_catalog;
3
+ SET lock_timeout = '15s';
4
+ SELECT pg_advisory_lock(hashtextextended('create-typeser:provision-server', 0));
5
+ SELECT set_config('typeser.setup_database', :'database', false),
6
+ set_config('typeser.setup_owner', :'owner', false),
7
+ set_config('typeser.setup_id', :'setup_id', false);
8
+
9
+ BEGIN ISOLATION LEVEL REPEATABLE READ;
10
+ SELECT NOT EXISTS (SELECT FROM pg_database WHERE datname = :'database') AS create_database,
11
+ NOT EXISTS (SELECT FROM pg_roles WHERE rolname = :'owner') AS create_owner,
12
+ NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'r1_runtime') AS create_runtime \gset
13
+ DO $check$
14
+ DECLARE
15
+ app_owner pg_roles;
16
+ runtime pg_roles;
17
+ db pg_database;
18
+ BEGIN
19
+ IF current_setting('server_version_num')::int < 180000 OR pg_is_in_recovery() OR current_setting('transaction_read_only')::boolean THEN
20
+ RAISE EXCEPTION 'Select a writable PostgreSQL 18+ server';
21
+ END IF;
22
+ SELECT * INTO app_owner FROM pg_roles WHERE rolname = current_setting('typeser.setup_owner');
23
+ IF FOUND AND (shobj_description(app_owner.oid, 'pg_authid') IS DISTINCT FROM current_setting('typeser.setup_id')
24
+ OR NOT app_owner.rolcanlogin OR app_owner.rolsuper OR app_owner.rolcreaterole OR app_owner.rolcreatedb
25
+ OR app_owner.rolinherit OR app_owner.rolreplication OR app_owner.rolbypassrls) THEN
26
+ RAISE EXCEPTION 'The application login already exists and cannot be reused for this installation';
27
+ END IF;
28
+ SELECT * INTO db FROM pg_database WHERE datname = current_setting('typeser.setup_database');
29
+ IF FOUND AND db.datdba IS DISTINCT FROM app_owner.oid THEN
30
+ RAISE EXCEPTION 'Database "%" already exists. Start in a fresh project directory and choose an unused database name.', db.datname;
31
+ END IF;
32
+ SELECT * INTO runtime FROM pg_roles WHERE rolname = 'r1_runtime';
33
+ IF FOUND AND (runtime.rolcanlogin OR runtime.rolsuper OR runtime.rolcreaterole OR runtime.rolcreatedb
34
+ OR runtime.rolinherit OR runtime.rolreplication OR runtime.rolbypassrls
35
+ OR EXISTS (SELECT FROM pg_auth_members WHERE member = runtime.oid)) THEN
36
+ RAISE EXCEPTION 'Existing r1_runtime role has incompatible privileges';
37
+ END IF;
38
+ IF app_owner.oid IS NOT NULL AND (NOT EXISTS (
39
+ SELECT FROM pg_auth_members WHERE member = app_owner.oid AND roleid = runtime.oid
40
+ AND set_option AND NOT inherit_option AND NOT admin_option)
41
+ OR EXISTS (SELECT FROM pg_auth_members WHERE member = app_owner.oid
42
+ AND (roleid <> runtime.oid OR inherit_option OR admin_option))) THEN
43
+ RAISE EXCEPTION 'Application login membership has changed; verify its r1_runtime grant before retrying';
44
+ END IF;
45
+ END;
46
+ $check$;
47
+
48
+ \if :create_runtime
49
+ CREATE ROLE r1_runtime NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
50
+ \endif
51
+ \if :create_owner
52
+ \getenv verifier TYPESER_SETUP_VERIFIER
53
+ CREATE ROLE :"owner" LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD :'verifier';
54
+ COMMENT ON ROLE :"owner" IS :'setup_id';
55
+ GRANT r1_runtime TO :"owner" WITH INHERIT FALSE, SET TRUE;
56
+ \endif
57
+ COMMIT;
58
+
59
+ -- CREATE DATABASE runs outside a transaction. Ownership identifies our database on retry.
60
+ \if :create_database
61
+ CREATE DATABASE :"database" OWNER :"owner" TEMPLATE template0 ENCODING 'UTF8'
62
+ LOCALE_PROVIDER builtin LOCALE 'C' BUILTIN_LOCALE 'C.UTF-8' ALLOW_CONNECTIONS false;
63
+ \endif
64
+ BEGIN;
65
+ REVOKE ALL ON DATABASE :"database" FROM PUBLIC;
66
+ ALTER ROLE :"owner" IN DATABASE :"database" SET lc_messages = 'C';
67
+ ALTER DATABASE :"database" ALLOW_CONNECTIONS true;
68
+ COMMIT;
package/lib/questions.mjs CHANGED
@@ -13,7 +13,7 @@ export function questions() {
13
13
  rl.once('SIGINT', () => rl.close());
14
14
  const lines = rl[Symbol.asyncIterator]();
15
15
  return {
16
- async ask(label, fallback = '', {secret = false, check = value => value} = {}) {
16
+ async ask(label, fallback = '', {secret = false, allowEmpty = false, check = value => value} = {}) {
17
17
  for (;;) {
18
18
  hidden = secret;
19
19
  display.write(label + (fallback ? ' [' + fallback + ']' : '') + ': ');
@@ -23,7 +23,7 @@ export function questions() {
23
23
  if (answer.done) throw new Error('Setup cancelled before all answers were entered.');
24
24
  const value = secret ? answer.value : answer.value.trim() || fallback;
25
25
  try {
26
- if (!value) throw new Error('Enter a value.');
26
+ if (!value && !allowEmpty) throw new Error('Enter a value.');
27
27
  return check(value);
28
28
  } catch (error) {
29
29
  if (!terminal) throw error;