You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

44 lines
2.0 KiB

import { readFileSync, writeFileSync, existsSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve } from 'node:path'
const root = fileURLToPath(new URL('../', import.meta.url))
const [name] = process.argv.slice(2)
if (!name || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) || name.length > 48) {
console.error('Usage: pnpm module:new <lowercase-module-name>')
process.exitCode = 1
} else {
const identifier = name.replace(/-([a-z0-9])/g, (_match, char) => char.toUpperCase()) + 'Module'
const moduleFile = resolve(root, `src/main/modules/${name}.ts`)
const contractFile = resolve(root, 'packages/contracts/src/index.ts')
const indexFile = resolve(root, 'src/main/modules/index.ts')
const contract = readFileSync(contractFile, 'utf8')
const index = readFileSync(indexFile, 'utf8')
const pattern = /export const modules: AppModule\[\] = \[([\s\S]*?)\]/
if (
existsSync(moduleFile) ||
contract.includes(`'${name}.echo'`) ||
!contract.includes('export const routes = {') ||
!pattern.test(index)
) {
throw new Error('Module exists or composition anchors changed; no files written')
}
const source = `import type { AppModule } from '../context'\n\nexport const ${identifier}: AppModule = {\n id: '${name}',\n setup({ ipc }, scope) {\n scope.add(ipc.register('${name}.echo', (message) => message))\n }\n}\n`
const nextContract = contract.replace(
'export const routes = {',
`export const routes = {\n '${name}.echo': route(z.string().max(1000), z.string()),`
)
const nextIndex =
`import { ${identifier} } from './${name}'\n` +
index.replace(
pattern,
(_match, items) =>
`export const modules: AppModule[] = [${items.trimEnd().replace(/,$/, '')},\n ${identifier}\n]`
)
writeFileSync(moduleFile, source, { flag: 'wx' })
writeFileSync(contractFile, nextContract)
writeFileSync(indexFile, nextIndex)
console.log(
`Created ${name}.echo. Main windows can call it; grant other roles explicitly in windowPermissions if needed. Run pnpm format && pnpm check.`
)
}