diff --git a/.github/actions/fresh-app/action.yml b/.github/actions/fresh-app/action.yml index 191c736..a2d830f 100644 --- a/.github/actions/fresh-app/action.yml +++ b/.github/actions/fresh-app/action.yml @@ -129,6 +129,11 @@ runs: patch -p1 < "modules/$MODULE/$f" done + # A template also replaces app files (home page, dashboard), as in a customer's app. + if [ "$(jq -r .type "modules/$MODULE/composer.json")" = "saucebase-template" ]; then + php artisan saucebase:template-install "$(jq -r .name "modules/$MODULE/composer.json")" --no-interaction + fi + - name: Configure the environment shell: bash working-directory: app diff --git a/.sonarcloud.properties b/.sonarcloud.properties index aae3022..290300c 100644 --- a/.sonarcloud.properties +++ b/.sonarcloud.properties @@ -8,4 +8,4 @@ sonar.test.inclusions=tests/**,**/*.test.ts,**/*.test.tsx # analysed; a newly added shadcn-vue component needs its folder listed here. # # A recipe is a template: its class and file names are placeholders the command fills in. -sonar.exclusions=stubs/recipes/**,stubs/stack/react/js/components/ui/*.tsx,stubs/stack/vue/js/components/ui/alert/**,stubs/stack/vue/js/components/ui/alert-dialog/**,stubs/stack/vue/js/components/ui/avatar/**,stubs/stack/vue/js/components/ui/badge/**,stubs/stack/vue/js/components/ui/breadcrumb/**,stubs/stack/vue/js/components/ui/button/**,stubs/stack/vue/js/components/ui/button-group/**,stubs/stack/vue/js/components/ui/card/**,stubs/stack/vue/js/components/ui/checkbox/**,stubs/stack/vue/js/components/ui/collapsible/**,stubs/stack/vue/js/components/ui/dialog/**,stubs/stack/vue/js/components/ui/dropdown-menu/**,stubs/stack/vue/js/components/ui/field/**,stubs/stack/vue/js/components/ui/input/**,stubs/stack/vue/js/components/ui/input-group/**,stubs/stack/vue/js/components/ui/label/**,stubs/stack/vue/js/components/ui/number-field/**,stubs/stack/vue/js/components/ui/popover/**,stubs/stack/vue/js/components/ui/scroll-area/**,stubs/stack/vue/js/components/ui/separator/**,stubs/stack/vue/js/components/ui/sheet/**,stubs/stack/vue/js/components/ui/sidebar/**,stubs/stack/vue/js/components/ui/skeleton/**,stubs/stack/vue/js/components/ui/slider/**,stubs/stack/vue/js/components/ui/textarea/**,stubs/stack/vue/js/components/ui/tooltip/** +sonar.exclusions=stubs/recipes/**,stubs/stack/react/js/components/ui/*.tsx,stubs/stack/vue/js/components/ui/alert/**,stubs/stack/vue/js/components/ui/alert-dialog/**,stubs/stack/vue/js/components/ui/avatar/**,stubs/stack/vue/js/components/ui/badge/**,stubs/stack/vue/js/components/ui/breadcrumb/**,stubs/stack/vue/js/components/ui/button/**,stubs/stack/vue/js/components/ui/button-group/**,stubs/stack/vue/js/components/ui/card/**,stubs/stack/vue/js/components/ui/checkbox/**,stubs/stack/vue/js/components/ui/collapsible/**,stubs/stack/vue/js/components/ui/combobox/**,stubs/stack/vue/js/components/ui/dialog/**,stubs/stack/vue/js/components/ui/dropdown-menu/**,stubs/stack/vue/js/components/ui/field/**,stubs/stack/vue/js/components/ui/input/**,stubs/stack/vue/js/components/ui/input-group/**,stubs/stack/vue/js/components/ui/label/**,stubs/stack/vue/js/components/ui/number-field/**,stubs/stack/vue/js/components/ui/popover/**,stubs/stack/vue/js/components/ui/scroll-area/**,stubs/stack/vue/js/components/ui/select/**,stubs/stack/vue/js/components/ui/separator/**,stubs/stack/vue/js/components/ui/sheet/**,stubs/stack/vue/js/components/ui/sidebar/**,stubs/stack/vue/js/components/ui/skeleton/**,stubs/stack/vue/js/components/ui/slider/**,stubs/stack/vue/js/components/ui/table/**,stubs/stack/vue/js/components/ui/textarea/**,stubs/stack/vue/js/components/ui/tooltip/** diff --git a/composer.json b/composer.json index 019667e..4c853a5 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "laravel/boost": "^2.10.3", "laravel/framework": "^13.38", "saucebase/breadcrumbs": "^1.1", - "saucebase/module-installer": "^3.0.1", + "saucebase/module-installer": "^3.3", "spatie/laravel-data": "^4.23", "spatie/laravel-navigation": "^1.3", "spatie/laravel-permission": "^8.3.2", @@ -61,6 +61,9 @@ } }, "extra": { + "branch-alias": { + "dev-dev": "3.0.x-dev" + }, "laravel": { "providers": [ "Saucebase\\Core\\CoreServiceProvider" diff --git a/config/saucebase.php b/config/saucebase.php index 415a771..0a48f6a 100644 --- a/config/saucebase.php +++ b/config/saucebase.php @@ -13,7 +13,7 @@ 'ignore_files' => ['module.json'], /* - * The password of every account the demo seeders create. There is no default: + * The password of every account a state's seeders create. There is no default: * a known password on a reachable admin account is the risk this avoids. */ 'demo_password' => env('DEMO_PASSWORD'), diff --git a/resources/boost/guidelines/core.md b/resources/boost/guidelines/core.md index 095a515..bed94ca 100644 --- a/resources/boost/guidelines/core.md +++ b/resources/boost/guidelines/core.md @@ -25,8 +25,8 @@ module plugin. `canAccess()` and created by the module's `DatabaseSeeder`, and site-wide settings pages are `manage settings`. The `admin` role passes every check through core's `Gate::before`. Roles are defined in core's `RolesDatabaseSeeder`; `admin` and `user` (the role - every sign-up gets) are fixed names modules may assign. The one exception is demo data: a module's - `Demo…DatabaseSeeder` may create a staff role for its own area (`blog admin`, `blog@saucebase.dev`). + every sign-up gets) are fixed names modules may assign. The one exception is showcase data: a module's + `Showcase…DatabaseSeeder` may create a staff role for its own area (`blog admin`, `blog@saucebase.dev`). - Where a signed-in user lands is the app's choice: `Home::using(fn (Request $request, string $reason) => …)` in a service provider (null means the site root). Modules redirect with `Home::url($request, Home::LOGIN)` or link to `route('home')`, never `route('dashboard')`, which is only the dashboard page. diff --git a/resources/boost/skills/saucebase-module-development/SKILL.md b/resources/boost/skills/saucebase-module-development/SKILL.md index c9be4b3..1b296a5 100644 --- a/resources/boost/skills/saucebase-module-development/SKILL.md +++ b/resources/boost/skills/saucebase-module-development/SKILL.md @@ -159,11 +159,13 @@ redirects such as OAuth callbacks. ## Seeders `php artisan modules:seed` runs `Modules\\Database\Seeders\DatabaseSeeder` for every installed module -that has one; `--module=` limits it to one. `--demo` then also runs `DemoDatabaseSeeder`, after -every module's required data exists. Each set runs in registry order, except that a seeder marked +that has one; `--module=` limits it to one. `--state=` then also runs `DatabaseSeeder`, after +every module's required data exists; `showcase` is the sample content (`ShowcaseBlogDatabaseSeeder`). A state +no module provides fails. In production it asks first; `--force` (also on `saucebase:module-setup` and +`saucebase:module-install`) skips the question. Each set runs in registry order, except that a seeder marked `#[SeedAfter('billing')]` (`Saucebase\Core\Attributes\SeedAfter`) runs after the named modules' seeder of the same kind; modules that aren't installed are ignored. A module with an admin area creates its `manage {module}` permission -there (see `saucebase-filament-development`); demo seeders never hold anything an install needs. +there (see `saucebase-filament-development`); state seeders never hold anything an install needs. ## Patches diff --git a/resources/boost/skills/saucebase-template-development/SKILL.md b/resources/boost/skills/saucebase-template-development/SKILL.md new file mode 100644 index 0000000..c36460e --- /dev/null +++ b/resources/boost/skills/saucebase-template-development/SKILL.md @@ -0,0 +1,85 @@ +--- +name: saucebase-template-development +description: Create and develop Saucebase templates — a saucebase-template package that installs a whole app (its modules, features, replaced app files and demo state) into a new application. Use when setting up a template workspace, running saucebase:template-capture or saucebase:template-install, writing a template's stubs/ or Default…DatabaseSeeder, or installing an app with --template. +--- + +# Saucebase Template Development + +A template is a module whose Composer type is `saucebase-template`, plus `stubs/`: app files it replaces on install. It installs once, into a new app, and the app owns the copied files. Everything the module skill says about code (`saucebase-module-development`) applies here too. + +## Where you work + +A template is built inside an app: the app runs it, the template is `modules/`, and `saucebase.json` names it (`"template": ""`). An app builds one template. + +| App | Created with | Frontend files | +|---|---|---| +| Normal app (anyone) | `saucebase new --modules=… --make-template=/` | App flat (`resources/js/pages`); template keeps `resources/js/{stack}/` | +| Contributor checkout (Saucebase team, also changing core or modules) | Contributor setup, `"template"` in `saucebase.json`, `tsconfig` `@/*` with `./resources/js/{stack}/*` first, then `saucebase:recipe template` | Both stacks, in their folders | + +In an existing app: `php artisan saucebase:recipe template --vendor=`, then `composer update /`. + +`template-install` refuses a contributor checkout and an app that already has a template. + +## The template's composer.json + +The recipe writes it: `type: saucebase-template`, `require` = core and every Saucebase module the app has, `extra.saucebase.frameworks` = the stacks it kept. + +- A module added later: `saucebase:module-install `, then add it to `require` by hand. +- `extra.saucebase.configure` (optional): module settings for the install, e.g. `{"auth": {"registration_enabled": true}}`. +- `extra.saucebase.demo_account` (optional): the email the demo signs in with; the installer prints it after `--demo`. +- Keep the template's frontend in `resources/js/{stack}/`. The installer flattens it into apps of that stack and refuses a module without the folder. + +## Stubs: replacing app files + +- Edit the app's file (`resources/js/pages/Index.vue`, `routes/web.php`; in a contributor checkout `resources/js/vue/pages/Index.vue`), then `php artisan saucebase:template-capture `. In a normal app, frontend files are filed under the stack folder for you. With no arguments it refreshes every existing stub; `--check` fails when one is stale. +- `stubs/` mirrors the app root. `resources/js/{vue,react}/…` and `resources/views/{vue,react}/…` lose the stack folder on install; the other stack's stubs are skipped. +- Refused: `composer.json`, `composer.lock`, `.env*`. `stubs/.env.example` is allowed: its missing keys are added to the app's `.env`. +- Import app code in stubs through `@/…`. +- Only replace what the template must. A stub is copied once; later template releases never reach existing apps. +- Most templates replace the starter kit's `routes/navigation.php` (its GitHub and Documentation links, "Welcome" for the dashboard) and `resources/js/{stack}/components/Footer.vue` (its credit), besides the home page and `routes/web.php`. + +## Data + +| Seeder | Runs | +|---|---| +| `DatabaseSeeder` | Every install: plans, permissions, anything the app needs to work | +| `DefaultDatabaseSeeder` | Only with `--demo` / `--state=default`: sample accounts and content | + +- `default` is the template's demo. Modules don't ship `Default…` seeders; the template recipe scaffolds an empty one. +- Seeders run twice without duplicating (`firstOrCreate`, `updateOrCreate`). Test that: run the state twice. +- Demo passwords come from `config('saucebase.demo_password')`. Never a literal. `modules:seed` makes a random one when it's unset. +- A clean install has no demo data, so every empty page needs an empty state and a first action. + +## Security + +- Per-user records: bind them among the signed-in user's own (`Route::bind('note', fn ($id) => Note::where('user_id', Auth::id())->findOrFail($id))`), and child records through their parent (`scopeBindings()`). Someone else's is then a 404. Never guard ownership with a gate or policy alone: core's `Gate::before` lets admins pass every check. +- Validate into arrays and set the owner with `associate()`; never `$request->all()`. +- Escape `LIKE` input with a portable character (`escape '!'`), not a backslash (MySQL). + +## Tests + +Write each behaviour's failing test first, in `modules//tests`: + +- Feature tests for routes and the state (`modules:seed --module= --state=default`, twice). +- E2E for the replaced pages (`npx playwright test --project="@*"`; first run needs `php artisan playwright:env`). + +## Check it as a user gets it + +In `sandboxes/`, never in the app that builds it: + +```bash +saucebase new my-app +cd my-app +composer config repositories. '{"type":"path","url":">","options":{"symlink":false}}' +php artisan saucebase:template-install / [--state=default] # no DEMO_PASSWORD? one is made and saved +npm install && npm run build +``` + +From a registry the installer knows: `saucebase new my-app --template=/ [--demo]`. + +## Gotchas + +- `template-install` takes the full package name; a bare name means `saucebase/`. +- A path repository must copy (`"symlink": false`); the module installer refuses a symlink. +- Iterating through a path repository: `composer update` changes nothing while `version` stays the same. Run `composer reinstall /`, then `template-install` again. +- An app takes one template, installed into a fresh app. A failed run prints the command to retry. diff --git a/resources/js/lib/modal.test.ts b/resources/js/lib/modal.test.ts new file mode 100644 index 0000000..0414ca4 --- /dev/null +++ b/resources/js/lib/modal.test.ts @@ -0,0 +1,65 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { initializeModals } from './modal'; + +/** Just enough of a page: a modal open, and a layer (a menu, a dialog) above it. */ +class FakeKeyboardEvent extends Event { + key: string; + + constructor(type: string, init: KeyboardEventInit = {}) { + super(type, init); + this.key = init.key ?? ''; + } +} + +const layerAbove = { closest: () => null }; + +beforeEach(() => { + const document = Object.assign(new EventTarget(), { + querySelector: (selector: string) => + selector === '.im-modal-wrapper' ? {} : null, + querySelectorAll: () => [layerAbove], + }); + + Object.assign(globalThis, { + document, + window: new EventTarget(), + KeyboardEvent: FakeKeyboardEvent, + }); + initializeModals(() => {}); +}); + +afterEach(() => { + for (const key of ['document', 'window', 'KeyboardEvent']) { + Reflect.deleteProperty(globalThis, key); + } +}); + +function pressEscape(): Event { + const event = new FakeKeyboardEvent('keydown', { + key: 'Escape', + bubbles: true, + cancelable: true, + }); + document.dispatchEvent(event); + + return event; +} + +describe('Escape over a modal', () => { + it('goes to the layer above, not the modal', () => { + let layerHeardIt = false; + window.addEventListener('keydown', () => (layerHeardIt = true)); + + pressEscape(); + + expect(layerHeardIt).toBe(true); + }); + + /** A layer may refuse Escape (mid-submit, say); the refusal must hold. */ + it('keeps a refusal from the layer above', () => { + window.addEventListener('keydown', (event) => event.preventDefault()); + + expect(pressEscape().defaultPrevented).toBe(true); + }); +}); diff --git a/resources/js/lib/modal.ts b/resources/js/lib/modal.ts index ceab37b..f15889a 100644 --- a/resources/js/lib/modal.ts +++ b/resources/js/lib/modal.ts @@ -23,6 +23,55 @@ export function initializeModals(putConfig: PutConfig): void { ); releaseCoveredModalFocus(); + escapeClosesTheTopLayerFirst(); +} + +/** + * Escape closes what is on top: a menu, select or dialog opened over a modal, not the + * modal under it. + * + * The modal listens for Escape on `document` and reka-ui's layers on `window`, so the + * modal hears it first and closes, taking the open menu and whatever was typed with + * it. Caught here on the way down instead: while a reka layer outside the modal is + * open, the key goes to `window` alone, where only reka is listening. + */ +function escapeClosesTheTopLayerFirst(): void { + if (typeof document === 'undefined') return; + + document.addEventListener( + 'keydown', + (event) => { + if ( + event.key !== 'Escape' || + !document.querySelector('.im-modal-wrapper') + ) { + return; + } + + // A closing layer stays in the page until its exit animation ends. + const layerAbove = [ + ...document.querySelectorAll( + '[data-dismissable-layer]:not([data-state="closed"])', + ), + ].some((layer) => !layer.closest('.im-modal-wrapper')); + + if (layerAbove) { + event.stopPropagation(); + // Cancelable, and its answer carried back: a layer that refuses Escape + // (mid-submit, say) stays open, and the browser's default stays off too. + const forwarded = new KeyboardEvent('keydown', { + key: 'Escape', + bubbles: true, + cancelable: true, + }); + + if (!window.dispatchEvent(forwarded)) { + event.preventDefault(); + } + } + }, + true, + ); } /** @@ -35,8 +84,10 @@ export function initializeModals(putConfig: PutConfig): void { * overflows. * * An overlay marks everything it covered with `data-aria-hidden` when it opens, - * so a covered modal has an overlay above it and no business holding focus. - * Swallowing the event in the capture phase keeps it from reaching either trap. + * so a covered modal has an overlay above it and no business holding focus. A + * non-modal layer (popover, combobox) marks nothing, so focus landing inside one + * counts too. Swallowing the event in the capture phase keeps it from reaching + * either trap. */ function releaseCoveredModalFocus(): void { // The server renders the same app but has no document to listen on. @@ -45,15 +96,27 @@ function releaseCoveredModalFocus(): void { document.addEventListener( 'focusin', (event) => { - const covered = document.querySelector( - '[data-aria-hidden] .im-modal-wrapper', - ); + const modal = document.querySelector('.im-modal-wrapper'); + const target = event.target; if ( - covered && - event.target instanceof Node && - !covered.contains(event.target) + !modal || + !(target instanceof Element) || + modal.contains(target) ) { + return; + } + + // Covered by a modal layer, or focus moving into a non-modal one (a popover + // or combobox opened from the modal): either way the trap must let go, or + // it pulls focus back and the layer closes as soon as it opens. + const covered = modal.closest('[data-aria-hidden]') !== null; + const intoLayer = + target.closest( + '[data-reka-popper-content-wrapper], [data-dismissable-layer]', + ) !== null; + + if (covered || intoLayer) { event.stopPropagation(); } }, diff --git a/resources/js/react/lib/pages.test.ts b/resources/js/react/lib/pages.test.ts index 7925575..702057c 100644 --- a/resources/js/react/lib/pages.test.ts +++ b/resources/js/react/lib/pages.test.ts @@ -3,7 +3,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; // Returns the path it was asked for and the pages it was given, so the tests read which // file a page name maps to and where it is looked up. vi.mock('laravel-vite-plugin/inertia-helpers', () => ({ - resolvePageComponent: (path: string, pages: object) => ({ path, pages }), + resolvePageComponent: (path: string | string[], pages: object) => ({ + path, + pages, + }), })); const appPages = {}; @@ -17,7 +20,7 @@ async function resolve(name: string, contributor: boolean) { registerAppPages(appPages); return resolveModularPageComponent(name) as unknown as { - path: string; + path: string | string[]; pages: object; }; } @@ -38,15 +41,25 @@ describe('resolveModularPageComponent', () => { it('finds module pages, turning the module name into its folder', async () => { const page = await resolve('Billing::Checkout', false); - expect(page.path).toBe( + expect(page.path).toContain( '/modules/billing/resources/js/pages/Checkout.tsx', ); expect(page.pages).not.toBe(appPages); - expect((await resolve('BillingPortal::Plans/Index', false)).path).toBe( + expect( + (await resolve('BillingPortal::Plans/Index', false)).path, + ).toContain( '/modules/billing-portal/resources/js/pages/Plans/Index.tsx', ); }); + /** The app's own template keeps its stack folder: it is published to apps of that stack. */ + it('finds the pages of a module that keeps its stack folder in an installed app', async () => { + expect((await resolve('Notes::Index', false)).path).toEqual([ + '/modules/notes/resources/js/pages/Index.tsx', + '/modules/notes/resources/js/react/pages/Index.tsx', + ]); + }); + it('finds module pages in a contributor checkout', async () => { expect((await resolve('Billing::Checkout', true)).path).toBe( '/modules/billing/resources/js/react/pages/Checkout.tsx', diff --git a/resources/js/react/lib/pages.ts b/resources/js/react/lib/pages.ts index f075f41..484bb80 100644 --- a/resources/js/react/lib/pages.ts +++ b/resources/js/react/lib/pages.ts @@ -3,8 +3,12 @@ import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'; declare const __SAUCEBASE_CONTRIBUTOR__: boolean; -/** A contributor checkout keeps each framework's module files in their own folder; an installed app is flat. */ -const tree = __SAUCEBASE_CONTRIBUTOR__ ? 'react/' : ''; +/** + * A contributor checkout keeps each framework's module files in their own folder; an + * installed app's modules are flat, except the template the app builds, which keeps its + * folder because it is published to other apps. + */ +const trees = __SAUCEBASE_CONTRIBUTOR__ ? ['react/'] : ['', 'react/']; let appPages: Record Promise> = {}; @@ -32,8 +36,13 @@ export function resolveModularPageComponent( .replace(/([a-z])([A-Z])/g, '$1-$2') .toLowerCase(); + const paths = trees.map( + (tree) => + `/modules/${moduleFolderName}/resources/js/${tree}pages/${componentPath}.tsx`, + ); + return resolvePageComponent( - `/modules/${moduleFolderName}/resources/js/${tree}pages/${componentPath}.tsx`, + paths.length === 1 ? paths[0] : paths, import.meta.glob( '/modules/*/resources/js/**/pages/**/*.tsx', ), diff --git a/resources/js/tests/vite.test.ts b/resources/js/tests/vite.test.ts index 563eeed..f640781 100644 --- a/resources/js/tests/vite.test.ts +++ b/resources/js/tests/vite.test.ts @@ -175,3 +175,223 @@ describe('saucebase()', () => { ).toBe('assets/auth/[name]-[hash][extname]'); }); }); + +/** The override layer of a template workspace: app files replace core's UI, per framework. */ +describe('saucebase() overrides', () => { + function overrides(): any { + return saucebase({ + framework: 'vue', + entry: 'resources/js/app.ts', + requires: {}, + }).find((p: any) => p?.name === 'saucebase:overrides') as any; + } + + function write(file: string, contents: string): string { + const full = path.join(root, file); + fs.mkdirSync(path.dirname(full), { recursive: true }); + fs.writeFileSync(full, contents); + + return full; + } + + const core = 'vendor/saucebase/core/stubs/stack/vue/js/pages/Index.vue'; + + it("serves the app's file in place of core's", () => { + write('saucebase.json', '{"contributor": true}'); + const corePage = write(core, 'core'); + write('resources/js/vue/pages/Index.vue', 'template'); + + expect(overrides().load.call({ addWatchFile() {} }, corePage)).toBe( + 'template', + ); + // Vite asks for the same file with a query for Vue's style and script parts. + expect( + overrides().load.call( + { addWatchFile() {} }, + `${corePage}?vue&type=style&index=0`, + ), + ).toBeNull(); + }); + + it("keeps core's file when the app has none", () => { + write('saucebase.json', '{"contributor": true}'); + const corePage = write(core, 'core'); + + expect( + overrides().load.call({ addWatchFile() {} }, corePage), + ).toBeNull(); + }); + + it("ignores the other framework's overrides", () => { + write('saucebase.json', '{"contributor": true}'); + const corePage = write(core, 'core'); + write('resources/js/react/pages/Index.vue', 'react'); + + expect( + overrides().load.call({ addWatchFile() {} }, corePage), + ).toBeNull(); + }); + + it('is off in an installed app, which owns its copy of the UI', () => { + write('saucebase.json', '{}'); + const corePage = write(core, 'core'); + write('resources/js/vue/pages/Index.vue', 'template'); + + expect(overrides()).toBeUndefined(); + }); +}); + +/** + * `@/` in a template workspace: the app's own UI first, then core's, else an error. + * Vite's alias has already turned `@/x` into core's path when this runs. + */ +describe('saucebase() app-first @/', () => { + const stack = 'vendor/saucebase/core/stubs/stack/vue/js'; + + function write(file: string, contents = ''): string { + const full = path.join(root, file); + fs.mkdirSync(path.dirname(full), { recursive: true }); + fs.writeFileSync(full, contents); + + return full; + } + + /** Vite's own resolution, reduced to what matters here: a file or a folder's index.ts. */ + const context = { + resolve: async (id: string) => + [id, `${id}/index.ts`] + .filter( + (file) => fs.existsSync(file) && fs.statSync(file).isFile(), + ) + .map((file) => ({ id: file }))[0] ?? null, + error: (message: string) => { + throw new Error(message); + }, + }; + + async function resolve(file: string, importer = 'resources/js/app.ts') { + const plugin = saucebase({ + framework: 'vue', + entry: 'resources/js/app.ts', + requires: {}, + }).find((p: any) => p?.name === 'saucebase:overrides') as any; + + const result = await plugin.resolveId.call( + context, + path.join(root, stack, file), + path.join(root, importer), + {}, + ); + + return result?.id ? path.relative(root, result.id) : result; + } + + beforeEach(() => { + write('saucebase.json', '{"contributor": true, "template": "uptime"}'); + }); + + it('finds a file only the app has', async () => { + write('resources/js/vue/components/ui/select/index.ts'); + + expect(await resolve('components/ui/select')).toBe( + 'resources/js/vue/components/ui/select/index.ts', + ); + }); + + it("leaves a file core has to core's path, which the override then fills", async () => { + write(`${stack}/components/ui/button/index.ts`); + write('resources/js/vue/components/ui/button/index.ts'); + + expect(await resolve('components/ui/button')).toBeNull(); + }); + + it("resolves an override's relative imports beside the override", async () => { + const core = write(`${stack}/components/ui/button/index.ts`); + write('resources/js/vue/components/ui/button/index.ts'); + write('resources/js/vue/components/ui/button/Fancy.vue'); + const plugin = saucebase({ + framework: 'vue', + entry: 'resources/js/app.ts', + requires: {}, + }).find((p: any) => p?.name === 'saucebase:overrides') as any; + + const result = await plugin.resolveId.call( + context, + './Fancy.vue', + core, + {}, + ); + + expect(path.relative(root, result.id)).toBe( + 'resources/js/vue/components/ui/button/Fancy.vue', + ); + }); + + it("leaves a relative import core's own file has to Vite", async () => { + const core = write(`${stack}/components/ui/button/index.ts`); + write(`${stack}/components/ui/button/Button.vue`); + const plugin = saucebase({ + framework: 'vue', + entry: 'resources/js/app.ts', + requires: {}, + }).find((p: any) => p?.name === 'saucebase:overrides') as any; + + expect( + await plugin.resolveId.call(context, './Button.vue', core, {}), + ).toBeNull(); + }); + + it('leaves a file neither has unresolved, so Vite reports it', async () => { + expect(await resolve('components/ui/nope')).toBeNull(); + }); + + it("lets the template's own module use the app's files", async () => { + write('resources/js/vue/components/ui/select/index.ts'); + + expect( + await resolve( + 'components/ui/select', + 'modules/uptime/resources/js/vue/pages/Monitors.vue', + ), + ).toBe('resources/js/vue/components/ui/select/index.ts'); + }); + + it("stops another module from using a file only this app has: customers' apps won't have it", async () => { + write('resources/js/vue/components/ui/select/index.ts'); + + await expect( + resolve( + 'components/ui/select', + 'modules/billing/resources/js/vue/pages/Settings.vue', + ), + ).rejects.toThrow(/billing.*components\/ui\/select/); + }); + + it('is off outside a template workspace: saucebase-dev builds core itself', async () => { + write('saucebase.json', '{"contributor": true}'); + write('resources/js/vue/components/ui/select/index.ts'); + + expect(await resolve('components/ui/select')).toBeNull(); + }); + + it('lists what the app replaces and adds, so nothing changes silently', () => { + write(`${stack}/pages/Index.vue`); + write('resources/js/vue/pages/Index.vue'); + write('resources/js/vue/components/ui/select/index.ts'); + const info = vi.fn(); + + const plugin = saucebase({ + framework: 'vue', + entry: 'resources/js/app.ts', + requires: {}, + }).find((p: any) => p?.name === 'saucebase:overrides') as any; + plugin.configResolved({ logger: { info } }); + + expect(info).toHaveBeenCalledWith( + expect.stringMatching(/replaces core: pages\/Index\.vue/), + ); + expect(info).toHaveBeenCalledWith( + expect.stringMatching(/adds: components\/ui\/select\/index\.ts/), + ); + }); +}); diff --git a/resources/js/vite.ts b/resources/js/vite.ts index 3bbcf61..ad7aa3d 100644 --- a/resources/js/vite.ts +++ b/resources/js/vite.ts @@ -42,6 +42,7 @@ export function saucebase({ : entry; return [ + contributor && overrides(framework, settings.template), { name: 'saucebase', config: (userConfig, env) => { @@ -160,8 +161,143 @@ export function saucebase({ ]; } +/** + * A contributor checkout reads core's UI from vendor/; a template workspace overrides + * parts of it from the app, one folder per framework, the way a template's stubs/ + * are laid out: resources/js/vue/pages/Index.vue replaces core's pages/Index.vue. + * + * In a template workspace `@/` also finds files only the app has, the way it does once + * a template is installed: the app's UI first, then core's, else Vite's usual error. + * Only the template's own module may use those files; any other module would break in + * apps without this template. + */ +function overrides( + framework: 'vue' | 'react', + template: string | undefined, +): PluginOption { + const root = process.cwd(); + const stack = path.join(root, SAUCEBASE_STACK, framework, 'js') + path.sep; + const appFiles = path.join(root, 'resources/js', framework); + const modules = path.join(root, 'modules') + path.sep; + const override = (id: string) => + id.startsWith(stack) && !id.includes('?') + ? path.join(appFiles, id.slice(stack.length)) + : null; + + return { + name: 'saucebase:overrides', + enforce: 'pre', + // Shown at start, so the app's files never take over core's without a trace. + configResolved(config) { + if (!template || !fs.existsSync(appFiles)) { + return; + } + const files = ( + fs.readdirSync(appFiles, { recursive: true }) as string[] + ) + .filter((file) => + fs.statSync(path.join(appFiles, file)).isFile(), + ) + .map((file) => file.split(path.sep).join('/')) + .sort((a, b) => a.localeCompare(b)); + const replaced = files.filter((file) => + fs.existsSync(stack + file), + ); + const added = files.filter((file) => !replaced.includes(file)); + + for (const [label, list] of [ + ['replaces core', replaced], + ['adds', added], + ] as const) { + if (list.length > 0) { + config.logger.info( + `[saucebase] ${template} ${label}: ${list.join(', ')}`, + ); + } + } + }, + // Vite's alias has already turned `@/x` into core's path. + async resolveId(id, importer, options) { + // load() serves an override under core's path, so its relative imports start + // beside core's file. One core has stays there; one only the app has is found + // beside the override. + const beside = + template && importer && id.startsWith('.') + ? override(importer) + : null; + + if (importer && beside !== null && fs.existsSync(beside)) { + const resolve = (target: string) => + this.resolve(target, importer, { + ...options, + skipSelf: true, + }); + + return (await resolve(path.resolve(path.dirname(importer), id))) + ? null + : resolve(path.resolve(path.dirname(beside), id)); + } + + const file = template ? override(id) : null; + + if (file === null) { + return null; + } + const resolve = (target: string) => + this.resolve(target, importer, { ...options, skipSelf: true }); + + // Core has it: keep core's path, and load() serves the app's copy if there is one. + if (await resolve(id)) { + return null; + } + const appOnly = await resolve(file); + const module = importer?.startsWith(modules) + ? importer.slice(modules.length).split(path.sep)[0] + : null; + + if (appOnly && module !== null && module !== template) { + this.error( + `modules/${module} imports @/${id.slice(stack.length)}, which only this app has. ` + + "Apps without the template won't have it: add it to core.", + ); + } + + return appOnly; + }, + load(id) { + const file = override(id); + + if (file === null || !fs.existsSync(file)) { + return null; + } + this.addWatchFile(file); + + return fs.readFileSync(file, 'utf-8'); + }, + // The page is known to Vite by core's path, so an edit to the override reloads it. + handleHotUpdate({ file, server }) { + if (!file.startsWith(appFiles + path.sep)) { + return; + } + const replaced = path.join(stack, path.relative(appFiles, file)); + for (const module of server.moduleGraph.getModulesByFile( + replaced, + ) ?? []) { + server.moduleGraph.invalidateModule(module); + } + server.ws.send({ type: 'full-reload' }); + + return []; + }, + }; +} + /** The app's `saucebase.json`: its framework, contributor mode and server rendering. */ -function readSettings(root: string): { contributor?: boolean; ssr?: boolean } { +function readSettings(root: string): { + contributor?: boolean; + ssr?: boolean; + template?: string; +} { const file = path.join(root, 'saucebase.json'); return fs.existsSync(file) diff --git a/resources/js/vue/lib/pages.test.ts b/resources/js/vue/lib/pages.test.ts index ee1106b..3b62f8e 100644 --- a/resources/js/vue/lib/pages.test.ts +++ b/resources/js/vue/lib/pages.test.ts @@ -3,7 +3,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; // Returns the path it was asked for and the pages it was given, so the tests read which // file a page name maps to and where it is looked up. vi.mock('laravel-vite-plugin/inertia-helpers', () => ({ - resolvePageComponent: (path: string, pages: object) => ({ path, pages }), + resolvePageComponent: (path: string | string[], pages: object) => ({ + path, + pages, + }), })); const appPages = {}; @@ -17,7 +20,7 @@ async function resolve(name: string, contributor: boolean) { registerAppPages(appPages); return resolveModularPageComponent(name) as unknown as { - path: string; + path: string | string[]; pages: object; }; } @@ -38,15 +41,25 @@ describe('resolveModularPageComponent', () => { it('finds module pages, turning the module name into its folder', async () => { const page = await resolve('Billing::Checkout', false); - expect(page.path).toBe( + expect(page.path).toContain( '/modules/billing/resources/js/pages/Checkout.vue', ); expect(page.pages).not.toBe(appPages); - expect((await resolve('BillingPortal::Plans/Index', false)).path).toBe( + expect( + (await resolve('BillingPortal::Plans/Index', false)).path, + ).toContain( '/modules/billing-portal/resources/js/pages/Plans/Index.vue', ); }); + /** The app's own template keeps its stack folder: it is published to apps of that stack. */ + it('finds the pages of a module that keeps its stack folder in an installed app', async () => { + expect((await resolve('Notes::Index', false)).path).toEqual([ + '/modules/notes/resources/js/pages/Index.vue', + '/modules/notes/resources/js/vue/pages/Index.vue', + ]); + }); + it('finds module pages in a contributor checkout', async () => { expect((await resolve('Billing::Checkout', true)).path).toBe( '/modules/billing/resources/js/vue/pages/Checkout.vue', diff --git a/resources/js/vue/lib/pages.ts b/resources/js/vue/lib/pages.ts index b003a28..522d783 100644 --- a/resources/js/vue/lib/pages.ts +++ b/resources/js/vue/lib/pages.ts @@ -3,8 +3,12 @@ import type { DefineComponent } from 'vue'; declare const __SAUCEBASE_CONTRIBUTOR__: boolean; -/** A contributor checkout keeps each framework's module files in their own folder; an installed app is flat. */ -const tree = __SAUCEBASE_CONTRIBUTOR__ ? 'vue/' : ''; +/** + * A contributor checkout keeps each framework's module files in their own folder; an + * installed app's modules are flat, except the template the app builds, which keeps its + * folder because it is published to other apps. + */ +const trees = __SAUCEBASE_CONTRIBUTOR__ ? ['vue/'] : ['', 'vue/']; let appPages: Record Promise> = {}; @@ -32,8 +36,13 @@ export function resolveModularPageComponent( .replace(/([a-z])([A-Z])/g, '$1-$2') .toLowerCase(); + const paths = trees.map( + (tree) => + `/modules/${moduleFolderName}/resources/js/${tree}pages/${componentPath}.vue`, + ); + return resolvePageComponent( - `/modules/${moduleFolderName}/resources/js/${tree}pages/${componentPath}.vue`, + paths.length === 1 ? paths[0] : paths, import.meta.glob( '/modules/*/resources/js/**/pages/**/*.vue', ), diff --git a/src/Attributes/SeedAfter.php b/src/Attributes/SeedAfter.php index c2d47de..e910950 100644 --- a/src/Attributes/SeedAfter.php +++ b/src/Attributes/SeedAfter.php @@ -6,7 +6,7 @@ /** * Runs a module's seeder after the named modules' seeders of the same kind - * (required or demo), for data that builds on theirs. Modules that aren't + * (required, or the same state), for data that builds on theirs. Modules that aren't * installed are ignored. */ #[Attribute(Attribute::TARGET_CLASS)] diff --git a/src/Console/Commands/ModuleInstallCommand.php b/src/Console/Commands/ModuleInstallCommand.php index 3da8b5f..80b2b9a 100644 --- a/src/Console/Commands/ModuleInstallCommand.php +++ b/src/Console/Commands/ModuleInstallCommand.php @@ -4,10 +4,9 @@ use Illuminate\Console\Command; use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Process; use Illuminate\Support\Str; +use Saucebase\Core\Console\Traits\InstallsSaucebasePackages; use Saucebase\Core\Support\DependencyOrder; -use Symfony\Component\Process\Process as SymfonyProcess; use function Laravel\Prompts\multiselect; @@ -17,20 +16,18 @@ */ class ModuleInstallCommand extends Command { + use InstallsSaucebasePackages; + protected $signature = 'saucebase:module-install {modules?* : Module names (billing). Omit to pick from a list} - {--demo : Also seed demo content}'; + {--state= : Also seed a state (showcase: sample content)} + {--force : Seed in production without asking} + {--set=* : Configure a module, module.key=value (tenancy.mode=subdomain, auth.registration_enabled=false)}'; protected $description = 'Install Saucebase modules into this application'; public function handle(): int { - if ($this->option('demo') && blank(config('saucebase.demo_password'))) { - $this->components->error('Set DEMO_PASSWORD in .env to seed demo data. Every demo account uses it.'); - - return self::FAILURE; - } - $modules = $this->argument('modules') ?: ($this->input->isInteractive() ? $this->pick() : []); if ($modules === null) { @@ -45,13 +42,12 @@ public function handle(): int return self::FAILURE; } - $output = fn (string $type, string $output) => $this->output->write($output); $packages = array_map(fn (string $name) => "saucebase/{$name}", $modules); $locked = $this->lockedModules(); - if (! Process::path(base_path())->forever()->run(['composer', 'require', ...$packages, '--no-interaction'], $output)->successful()) { - $this->components->error('Composer could not install the modules. Nothing else was changed.'); + if (! $this->requirePackages($packages)) { + $this->components->error('Composer could not install the modules. composer.json and composer.lock are back as they were; run composer install to remove anything Composer left in vendor/ or modules/.'); return self::FAILURE; } @@ -64,26 +60,7 @@ public function handle(): int ...$modules, ], $after); - // TTY, so a module's own install command can ask its questions. - return Process::path(base_path())->forever()->tty(SymfonyProcess::isTtySupported() && $this->input->isInteractive()) - ->run([PHP_BINARY, 'artisan', 'saucebase:module-setup', ...$modules, ...($this->option('demo') ? ['--demo'] : [])], $output) - ->successful() ? self::SUCCESS : self::FAILURE; - } - - /** @return array Each Saucebase module in composer.lock => the modules it requires. */ - private function lockedModules(): array - { - $packages = collect(json_decode((string) @file_get_contents(base_path('composer.lock')), true)['packages'] ?? []) - ->where('type', 'saucebase-module'); - $names = $packages->pluck('name')->all(); - - return $packages->mapWithKeys(fn (array $package): array => [ - Str::after($package['name'], '/') => collect(array_keys($package['require'] ?? [])) - ->intersect($names) - ->map(fn (string $name): string => Str::after($name, '/')) - ->values() - ->all(), - ])->all(); + return $this->runSetup($modules, $this->option('state'), (bool) $this->option('force')) ? self::SUCCESS : self::FAILURE; } /** @return string[]|null Module names on Packagist the app doesn't require yet; null when it has them all. */ diff --git a/src/Console/Commands/ModuleSetupCommand.php b/src/Console/Commands/ModuleSetupCommand.php index d061320..02d7c60 100644 --- a/src/Console/Commands/ModuleSetupCommand.php +++ b/src/Console/Commands/ModuleSetupCommand.php @@ -8,8 +8,13 @@ use InterNACHI\Modular\Support\ModuleRegistry; use Saucebase\Core\ModuleTaskfile; use Saucebase\Core\ProjectConfig; +use Saucebase\Core\Settings\InstallSettings; +use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\StringInput; +use function Laravel\Prompts\confirm; + /** * Wires installed modules into the application. `saucebase:module-install` runs it in a * new process. Safe to run again. @@ -18,7 +23,10 @@ class ModuleSetupCommand extends Command { protected $signature = 'saucebase:module-setup {modules* : Installed module names} - {--demo : Also seed demo content}'; + {--state= : Also seed a state (showcase: sample content)} + {--force : Seed in production without asking} + {--configure : These modules are being installed: set their install settings (a template\'s configure, --set, then prompts)} + {--set=* : Configure a module, module.key=value: an install setting or an answer for its install command (tenancy.mode=subdomain)}'; protected $description = 'Apply patches, migrate and seed installed modules'; @@ -36,12 +44,21 @@ public function handle(ModuleRegistry $registry, ProjectConfig $config): int } } + // Checked before anything is written, so a bad entry changes nothing. + $plan = $this->configuration($modules); + + if (is_string($plan)) { + $this->components->error($plan); + + return self::FAILURE; + } + $conflicts = $this->applyPatches($modules); $steps = [ ['migrate', ['--force' => true]], // Together: seeding them one by one would hide each from the others' SeedAfter. - ['modules:seed', ['--module' => array_map(fn ($module) => $module->name, $modules), '--demo' => $this->option('demo')]], + ['modules:seed', ['--module' => array_map(fn ($module) => $module->name, $modules), '--state' => $this->option('state'), '--force' => $this->option('force')]], ]; foreach ($modules as $module) { @@ -62,13 +79,20 @@ public function handle(ModuleRegistry $registry, ProjectConfig $config): int return self::FAILURE; } - $steps[] = [substr($line, strlen('php artisan ')), null]; + $steps[] = [substr($line, strlen('php artisan ')).$this->appendOptions($line, $plan[$module->name]['answers']), null]; } } - foreach ($steps as [$command, $arguments]) { - if ($this->runStep($command, $arguments) !== self::SUCCESS) { - $this->components->error("`{$command}` failed. Fix it, then run this again: php artisan saucebase:module-setup ".implode(' ', $this->argument('modules')).($this->option('demo') ? ' --demo' : '')); + foreach ($steps as $index => [$command, $arguments]) { + $failed = $this->runStep($command, $arguments) !== self::SUCCESS; + + // Once migrated (the settings exist), before seeders read them. + if (! $failed && $index === 0 && $this->option('configure')) { + $this->applySettings($plan); + } + + if ($failed) { + $this->components->error("`{$command}` failed. Fix it, then run this again: php artisan saucebase:module-setup ".implode(' ', $this->argument('modules')).($this->option('state') ? ' --state='.$this->option('state') : '').($this->option('force') ? ' --force' : '')); return self::FAILURE; } @@ -96,6 +120,143 @@ public function handle(ModuleRegistry $registry, ProjectConfig $config): int return self::SUCCESS; } + /** + * What this run configures, checked before anything is written: each module's keys + * from `extra.saucebase.configure.` in the modules being set up (a template's), + * then `--set` flags, which win. A key marked #[InstallSetting] is a setting, cast and + * validated; any other key answers the module's install command, `--key=value`. + * + * @param ModuleConfig[] $modules + * @return array, flags: array, answers: array, options: array}>|string + */ + private function configuration(array $modules): array|string + { + $plan = []; + + foreach ($modules as $module) { + $plan[$module->name] = ['settings' => InstallSettings::of($module), 'template' => [], 'flags' => [], 'answers' => [], 'options' => $this->installOptions($module)]; + } + + $entries = []; + + foreach ($modules as $module) { + $declared = data_get(json_decode((string) @file_get_contents($module->path('composer.json')), true), 'extra.saucebase.configure', []); + + foreach ((array) $declared as $target => $values) { + foreach ((array) $values as $key => $value) { + $entries[] = ['template', (string) $target, (string) $key, $value]; + } + } + } + + foreach ((array) $this->option('set') as $flag) { + if (! preg_match('/^([a-z0-9-]+)\.([A-Za-z_][A-Za-z0-9_-]*)=(.*)$/', (string) $flag, $match)) { + return "configure: --set takes module.key=value: {$flag}"; + } + + $entries[] = ['flags', $match[1], $match[2], $match[3]]; + } + + try { + foreach ($entries as [$source, $target, $key, $value]) { + $settings = $plan[$target]['settings'] ?? throw new \InvalidArgumentException("{$target} is not being installed here."); + + if ($settings->marks($key)) { + $plan[$target][$source][$key] = $settings->cast($key, $value); + } elseif ($settings->declares($key)) { + throw new \InvalidArgumentException("{$target}.{$key} can't be set at install: it is not marked #[InstallSetting]."); + } elseif (! isset($plan[$target]['options'][$key])) { + throw new \InvalidArgumentException("{$target}.{$key} is neither an install setting nor an option of {$target}'s install command."); + } elseif (! $plan[$target]['options'][$key]->acceptValue()) { + // A flag: on or off, whatever spelling the template or `--set` used. + $flag = is_bool($value) ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + $plan[$target]['answers'][$key] = $flag ?? throw new \InvalidArgumentException("{$target}.{$key} is a flag: true or false, not ".json_encode($value).'.'); + } elseif (! (is_scalar($value) || $value === null) + || (is_string($value) && ! preg_match('#^[A-Za-z0-9._:/@+-]*$#', $value))) { + // Option names and plain values only, so an answer can never become another command. + throw new \InvalidArgumentException("{$target}.{$key} answers the install command, so it takes an option name and a plain value: ".json_encode($value)); + } else { + $plan[$target]['answers'][$key] = $value; + } + } + } catch (\InvalidArgumentException $e) { + return 'configure: '.$e->getMessage(); + } + + return $plan; + } + + /** + * The options a module's install commands take: the only answers `configure` may give + * it. Read from the commands themselves, so a typo fails before anything is written. + * + * @return array + */ + private function installOptions(ModuleConfig $module): array + { + $options = []; + $composer = json_decode((string) @file_get_contents($module->path('composer.json')), true); + + foreach ((array) data_get($composer, 'extra.saucebase.post-install', []) as $line) { + $name = strtok(substr((string) $line, strlen('php artisan ')), ' '); + + if (str_starts_with((string) $line, 'php artisan ') && $name && $this->getApplication()?->has($name)) { + $options += $this->getApplication()->find($name)->getNativeDefinition()->getOptions(); + } + } + + return $options; + } + + /** + * Saves each module's settings: a flag beats the person's answer, which beats the + * template's value. Asked only when somebody is there and wants to. + * + * @param array, flags: array, answers: array}> $plan + */ + private function applySettings(array $plan): void + { + foreach ($plan as $name => ['settings' => $settings, 'template' => $template, 'flags' => $flags]) { + if ($settings->isEmpty()) { + continue; + } + + $answers = $this->input->isInteractive() && confirm(__('Configure :module?', ['module' => $name]), false) + ? $settings->ask($template, array_keys($flags)) + : []; + + $settings->save([...$template, ...$answers, ...$flags]); + } + } + + /** + * `--option=value` for each answer the line doesn't already give, a bare `--option` for + * true; false and null are left out. The line's own options win. + * + * @param array $options + */ + private function appendOptions(string $line, array $options): string + { + $appended = ''; + // The answers cover all of a module's post-install commands; each gets only its own. + $name = strtok(substr($line, strlen('php artisan ')), ' '); + $definition = $name && $this->getApplication()?->has($name) ? $this->getApplication()->find($name)->getNativeDefinition() : null; + + foreach ($options as $option => $value) { + if ($definition !== null && ! $definition->hasOption($option)) { + continue; + } + + if ($value === false || $value === null || preg_match('/(^|\s)--'.preg_quote($option, '/').'(=|\s|$)/', $line)) { + continue; + } + + $appended .= $value === true ? " --{$option}" : " --{$option}={$value}"; + } + + return $appended; + } + /** * A post-install line keeps its own options (`tenancy:install --mode=path`), and * asks its questions when this command can. @@ -111,7 +272,14 @@ private function runStep(string $command, ?array $arguments): int $input = new StringInput($command); $input->setInteractive($this->input->isInteractive()); - return $this->getApplication()->find((string) $input->getFirstArgument())->run($input, $this->output); + try { + return $this->getApplication()->find((string) $input->getFirstArgument())->run($input, $this->output); + } catch (ExceptionInterface $e) { + // An answer the command doesn't take (a typo in `configure`): said, not thrown. + $this->components->error($e->getMessage()); + + return self::FAILURE; + } } /** diff --git a/src/Console/Commands/RecipeToModuleCommand.php b/src/Console/Commands/RecipeToModuleCommand.php index ce2ab32..38e1419 100644 --- a/src/Console/Commands/RecipeToModuleCommand.php +++ b/src/Console/Commands/RecipeToModuleCommand.php @@ -78,13 +78,29 @@ public function handle(): int $isContributor = $frontendConfig->isContributor(); $this->templatePath = $this->recipes()[$this->getRecipe()]['path']; + $isTemplate = $this->makesTemplate(); + $current = $frontendConfig->template(); + + if ($isTemplate && $current !== null && $current !== $this->moduleFolder) { + error("This app already builds the {$current} template. An app builds one template."); + + return self::FAILURE; + } $this->tempFolder = base_path('saucebase-temp'); $this->generate(); $this->fs->remove($this->moduleConfigPath.$this->moduleFolder.'/recipe.json'); - // A contributor checkout keeps both frameworks; core finds the setup in either. - if (! $isContributor) { + if ($isTemplate) { + // Published to apps of its stack, so it keeps the folder the installer flattens. + if (! $isContributor) { + $this->fs->remove($this->moduleConfigPath.$this->moduleFolder.'/resources/js/'.($framework === 'vue' ? 'react' : 'vue')); + } + + $this->describeTemplate(); + $frontendConfig->setTemplate($this->moduleFolder); + } elseif (! $isContributor) { + // A contributor checkout keeps both frameworks; core finds the setup in either. $this->keepOnlyFramework($framework); } @@ -208,7 +224,7 @@ protected function generate(): void $this->deleteDir($this->tempFolder); $this->copyDir($this->templatePath, $this->tempFolder.'/Module'); - $finder = (new Finder)->files()->in($this->tempFolder); + $finder = (new Finder)->files()->ignoreDotFiles(false)->in($this->tempFolder); $this->renameFiles($finder); $this->updateFilesContent($finder); @@ -391,6 +407,36 @@ protected function keepOnlyFramework(string $framework): void $this->fs->remove(["{$js}/vue", "{$js}/react"]); } + /** A template, by the package type its recipe (or --type) gives it. */ + private function makesTemplate(): bool + { + $type = json_decode((string) file_get_contents($this->templatePath.'/composer.json'), true)['type'] ?? ''; + + return ($type === '{COMPOSER_TYPE}' ? $this->composerType : $type) === 'saucebase-template'; + } + + /** + * The stacks it ships (the frontend folders it kept), and what it is built on: core and + * the app's Saucebase modules, so an app it installs into gets them too. + */ + private function describeTemplate(): void + { + $module = $this->moduleConfigPath.$this->moduleFolder; + $data = json_decode((string) file_get_contents("{$module}/composer.json"), true); + $data['extra']['saucebase']['frameworks'] = array_values(array_filter(['vue', 'react'], fn (string $stack) => is_dir("{$module}/resources/js/{$stack}"))); + + $locked = json_decode((string) @file_get_contents(base_path('composer.lock')), true)['packages'] ?? []; + + foreach ($locked as $package) { + if (($package['type'] ?? null) === 'saucebase-module' || $package['name'] === 'saucebase/core') { + // A released version: its minor and up. A branch (dev-dev): any. + $data['require'][$package['name']] = preg_match('/^v?(\d+)\.(\d+)/', $package['version'] ?? '', $match) ? "^{$match[1]}.{$match[2]}" : '*'; + } + } + + file_put_contents("{$module}/composer.json", json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n"); + } + protected function registerInComposer(): void { $path = base_path('composer.json'); diff --git a/src/Console/Commands/SeedModulesCommand.php b/src/Console/Commands/SeedModulesCommand.php index 23b1b52..82c1637 100644 --- a/src/Console/Commands/SeedModulesCommand.php +++ b/src/Console/Commands/SeedModulesCommand.php @@ -2,7 +2,9 @@ namespace Saucebase\Core\Console\Commands; +use Dotenv\Dotenv; use Illuminate\Console\Command; +use Illuminate\Console\ConfirmableTrait; use Illuminate\Support\Collection; use Illuminate\Support\Str; use InterNACHI\Modular\Support\ModuleRegistry; @@ -13,20 +15,29 @@ class SeedModulesCommand extends Command { + use ConfirmableTrait; + protected $signature = 'modules:seed {--module=* : Seed specific modules (case-insensitive), together. Omit to seed all.} - {--demo : Also run each module\'s Demo{Module}DatabaseSeeder with sample content.}'; + {--state= : Also run each module\'s seeder for this state, e.g. showcase runs ShowcaseBlogDatabaseSeeder} + {--force : Seed in production without asking}'; protected $description = 'Seed all installed modules that have a DatabaseSeeder'; public function handle(ModuleRegistry $registry): int { - if ($this->option('demo') && blank(config('saucebase.demo_password'))) { - $this->components->error('Set DEMO_PASSWORD in .env to seed demo data. Every demo account uses it.'); + $state = $this->option('state') ? Str::studly($this->option('state')) : null; + // Asked once here rather than by db:seed for every module. A state creates sample + // accounts and content: never in production by accident. + if (! $this->confirmToProceed()) { return self::FAILURE; } + if ($state !== null && blank(config('saucebase.demo_password'))) { + $this->makeDemoPassword(); + } + $modules = $registry->modules(); // A string when another command calls this with one name. @@ -51,30 +62,77 @@ public function handle(ModuleRegistry $registry): int $modules = $named; } - $this->seed($modules, fn (string $studly) => 'DatabaseSeeder'); + $required = $this->seeders($modules, fn (string $studly) => 'DatabaseSeeder'); + $stated = $state === null ? collect() : $this->seeders($modules, fn (string $studly) => "{$state}{$studly}DatabaseSeeder"); + + if ($state !== null && $stated->isEmpty()) { + $this->components->error("No module has a \"{$this->option('state')}\" state."); + + return self::FAILURE; + } + + // Every module's required data exists before any state refers to it. + return $this->seed($required) && $this->seed($stated) ? self::SUCCESS : self::FAILURE; + } + + /** + * Every account a state creates signs in with DEMO_PASSWORD. Without one, a random one + * (as the installer makes) is saved in .env and shown, never a guessable default. + */ + private function makeDemoPassword(): void + { + $env = $this->laravel->environmentFilePath(); + $saved = is_file($env) ? (Dotenv::parse((string) file_get_contents($env))['DEMO_PASSWORD'] ?? '') : ''; + + // Set in .env but hidden by a cached config: use it, or every run would replace it. + // Laravel reads these spellings as unset (Env::get), so they are not a password. + if (! in_array(strtolower(trim($saved)), ['', 'null', '(null)', 'empty', '(empty)'], true)) { + config(['saucebase.demo_password' => $saved]); + + return; + } + + $password = Str::password(10, symbols: false); + config(['saucebase.demo_password' => $password]); - if ($this->option('demo')) { - // Every module's required data exists before any demo content refers to it. - $this->seed($modules, fn (string $studly) => "Demo{$studly}DatabaseSeeder"); + if (! is_file($env)) { + $this->components->warn("No .env file: the demo accounts use the password {$password} for this run, not saved. Set DEMO_PASSWORD to keep one."); + + return; } - return self::SUCCESS; + $contents = (string) file_get_contents($env); + $line = "DEMO_PASSWORD={$password}"; + // The whole value: a quoted one may span lines. + $assignment = '/^DEMO_PASSWORD=(?:"(?:\\\\.|[^"\\\\])*"|\'[^\']*\'|[^\n]*)/m'; + $contents = preg_match($assignment, $contents) + ? preg_replace($assignment, $line, $contents) + : rtrim($contents, "\n").($contents === '' ? '' : "\n")."{$line}\n"; + + file_put_contents($env, $contents); + + $this->components->warn("DEMO_PASSWORD was not set. The demo accounts use {$password}, now saved in .env."); } /** * @param Collection $modules * @param callable(string): string $seederName + * @return Collection Module name => seeder class, for those that have one. */ - private function seed(Collection $modules, callable $seederName): void + private function seeders(Collection $modules, callable $seederName): Collection { - $seeders = $modules + return $modules ->mapWithKeys(function ($module) use ($seederName): array { $studly = Str::studly($module->name); return [$module->name => "Modules\\{$studly}\\Database\\Seeders\\".$seederName($studly)]; }) ->filter(fn (string $seeder): bool => class_exists($seeder)); + } + /** @param Collection $seeders */ + private function seed(Collection $seeders): bool + { $after = $seeders->map( fn (string $seeder): array => collect((new ReflectionClass($seeder)) ->getAttributes(SeedAfter::class)) @@ -85,10 +143,22 @@ private function seed(Collection $modules, callable $seederName): void foreach (DependencyOrder::sort($seeders->keys()->all(), $after->all()) as $name) { $seeder = $seeders[$name]; + $seeded = false; + $this->components->task( "{$name} ".class_basename($seeder), - fn () => $this->call('db:seed', ['--class' => $seeder]) === self::SUCCESS, + function () use ($seeder, &$seeded): bool { + // Asked once above; db:seed would ask again for every module. + return $seeded = $this->call('db:seed', ['--class' => $seeder, '--force' => true]) === self::SUCCESS; + }, ); + + // The modules after this one may build on its data. + if (! $seeded) { + return false; + } } + + return true; } } diff --git a/src/Console/Commands/TemplateCaptureCommand.php b/src/Console/Commands/TemplateCaptureCommand.php new file mode 100644 index 0000000..53103f6 --- /dev/null +++ b/src/Console/Commands/TemplateCaptureCommand.php @@ -0,0 +1,138 @@ +template(); + + if ($template === null) { + return $this->refuse('Run this in an app that builds a template: "template" in saucebase.json.'); + } + + // An installed app's frontend is flat; the stubs keep the stack folder install drops. + $stack = $config->isContributor() ? null : $config->getFramework(); + $stubs = base_path("modules/{$template}/stubs"); + + $paths = $files->isDirectory($stubs) + ? collect($files->allFiles($stubs, true))->map(fn ($file) => str_replace('\\', '/', $file->getRelativePathname())) + : collect(); + + // Named files and the stubs already there pass the same check, so a stub put in by hand can't leak either. + foreach ([...$paths, ...array_map(fn (string $path) => $this->stubPath($this->normalize($path), $stack), $this->argument('files'))] as $path) { + $path = $path === null ? null : $this->normalize($path); + + if ($path === null || ($path !== '.env.example' && Str::is(self::OWN, $path))) { + return $this->refuse(($path ?? 'A path outside the app').' belongs to the workspace, not the template.'); + } + + $paths->push($path); + } + + // Stub => the app file it comes from; another stack's stubs have none here. + $sources = $paths->unique()->sort()->values() + ->mapWithKeys(fn (string $path) => [$path => $this->appPath($path, $stack)]) + ->filter(); + + $missing = $sources->reject(fn (string $app) => $files->isFile(base_path($app))); + + if ($missing->isNotEmpty()) { + return $this->refuse('These stubs have no app file to copy: '.$missing->values()->implode(', ').'. Restore the file, or delete the stub.'); + } + + $stale = $sources->filter(fn (string $app, string $path) => ! $files->isFile("{$stubs}/{$path}") + || $files->get("{$stubs}/{$path}") !== $files->get(base_path($app)))->keys(); + + if ($this->option('check')) { + return $stale->isEmpty() ? self::SUCCESS : $this->refuse( + "modules/{$template}/stubs is out of date: ".$stale->implode(', ').'. Run: php artisan saucebase:template-capture' + ); + } + + foreach ($stale as $path) { + $files->ensureDirectoryExists(dirname("{$stubs}/{$path}")); + $files->copy(base_path($sources[$path]), "{$stubs}/{$path}"); + } + + $this->components->info($stale->isEmpty() ? 'Stubs are up to date.' : "Updated {$stale->count()} stubs in modules/{$template}/stubs."); + $this->components->bulletList($stale->all()); + + return self::SUCCESS; + } + + /** resources/js/pages/Index.vue → resources/js/vue/pages/Index.vue, in an installed app. */ + private function stubPath(?string $path, ?string $stack): ?string + { + if ($path === null || $stack === null || ! preg_match('#^resources/(js|views)/(?!vue/|react/)(.+)$#', $path, $match)) { + return $path; + } + + return "resources/{$match[1]}/{$stack}/{$match[2]}"; + } + + /** The app file a stub comes from; null for another stack's stub in an installed app. */ + private function appPath(string $stub, ?string $stack): ?string + { + if ($stack === null || ! preg_match('#^resources/(js|views)/(vue|react)/(.+)$#', $stub, $match)) { + return $stub; + } + + return $match[2] === $stack ? "resources/{$match[1]}/{$match[3]}" : null; + } + + /** `./.env` and `routes/../.env` are `.env`: dot segments resolved, so no spelling slips past OWN. Null: outside the app. */ + private function normalize(string $path): ?string + { + $parts = []; + + foreach (explode('/', str_replace('\\', '/', $path)) as $part) { + if ($part === '' || $part === '.') { + continue; + } + + if ($part === '..') { + if ($parts === []) { + return null; + } + + array_pop($parts); + + continue; + } + + $parts[] = $part; + } + + return $parts === [] ? null : implode('/', $parts); + } + + private function refuse(string $error): int + { + $this->components->error($error); + + return self::FAILURE; + } +} diff --git a/src/Console/Commands/TemplateInstallCommand.php b/src/Console/Commands/TemplateInstallCommand.php new file mode 100644 index 0000000..f6349f0 --- /dev/null +++ b/src/Console/Commands/TemplateInstallCommand.php @@ -0,0 +1,275 @@ +argument('template'), '/') ? $this->argument('template') : 'saucebase/'.$this->argument('template'); + $template = Str::afterLast($package, '/'); + + if ($config->isContributor()) { + return $this->refuse('Templates install into an application, not a Saucebase checkout. Use a sandbox app.'); + } + + $other = collect($this->lockedPackages()) + ->where('type', 'saucebase-template') + ->keys() + ->reject(fn (string $name) => $name === $template) + ->first(); + + if ($other !== null) { + return $this->refuse("This app already has the {$other} template. An app takes one template, installed fresh."); + } + + if (! $this->requirePackages([$package])) { + return $this->refuse('Composer could not install the template. composer.json and composer.lock are back as they were; run composer install to remove anything Composer left in vendor/ or modules/.'); + } + + if (($this->lockedPackages()[$template]['type'] ?? null) !== 'saucebase-template') { + return $this->refuse("{$package} is not a template. Install modules with saucebase:module-install."); + } + + $copies = $this->stubs($files, base_path("modules/{$template}/stubs"), $config->getFramework()); + + if (is_string($copies)) { + return $this->retry($copies); + } + + foreach ($copies as $target => $source) { + $files->ensureDirectoryExists(dirname(base_path($target))); + $files->copy($source, base_path($target)); + } + + $this->addMissingEnvKeys($files, $template); + + // The template and everything it depends on, not just what Composer added this run: + // on a retry Composer adds nothing, and a module whose setup failed must still run. + $after = $this->lockedModules(); + $modules = DependencyOrder::sort($this->closure($template, $after), $after); + + $force = (bool) $this->option('force'); + + if (! $this->runSetup($modules, null, $force)) { + return $this->retry('Setting up the template failed.'); + } + + // Last, in a process of its own: the state sees the app as every module's install + // command left it (tenancy's address mode, for one, decides where a seeded site lives). + $state = $this->state(); + + if ($state !== null && ! $this->seedState($modules, $state, $force)) { + return $this->retry('Seeding the template\'s state failed.'); + } + + return self::SUCCESS; + } + + /** + * Every stub's target, checked before anything is written. + * + * @return array|string Target path (relative to the app) => source file, or why the stubs are invalid. + */ + private function stubs(Filesystem $files, string $root, ?string $framework): array|string + { + if (! $files->isDirectory($root)) { + return []; + } + + $copies = []; + $frameworks = []; + + foreach (Finder::create()->in($root)->ignoreDotFiles(false)->ignoreVCS(true) as $file) { + $path = str_replace('\\', '/', $file->getRelativePathname()); + + if ($file->isLink()) { + return "stubs/{$path} is a symlink. Stubs must be real files."; + } + + if ($file->isDir()) { + continue; + } + + // resources/js/vue/pages/Index.vue → resources/js/pages/Index.vue + if (preg_match('#^resources/(js|views)/('.implode('|', self::FRAMEWORKS).')/(.+)$#', $path, $match)) { + $frameworks[$match[2]] = true; + + if ($match[2] !== $framework) { + continue; + } + + $target = "resources/{$match[1]}/{$match[3]}"; + } else { + $target = $path; + } + + if (in_array($target, self::REFUSED, true) || ($target !== '.env.example' && Str::startsWith(basename($target), '.env'))) { + return "stubs/{$path} would replace {$target}, which a template can't change."; + } + + if (isset($copies[$target])) { + return "Two stubs replace {$target}."; + } + + $copies[$target] = $file->getPathname(); + } + + if ($frameworks !== [] && ! isset($frameworks[$framework])) { + return "The template has no stubs for {$framework}."; + } + + return $copies; + } + + /** + * The app's .env predates the template, so settings the template documents in + * its .env.example are added to it: missing keys only, never a changed value. + */ + private function addMissingEnvKeys(Filesystem $files, string $template): void + { + $example = base_path("modules/{$template}/stubs/.env.example"); + $env = base_path('.env'); + + if (! $files->isFile($example) || ! $files->isFile($env)) { + return; + } + + $current = $files->get($env); + $missing = array_diff_key(Dotenv::parse($files->get($example)), Dotenv::parse($current)); + + if ($missing === []) { + return; + } + + $keys = array_keys($missing); + $count = count($keys).' missing '.Str::plural('key', count($keys)); + + // Without a person to ask (the installer), the example's defaults are added. + if ($this->input->isInteractive() && ! $this->confirm("Add {$count} from the {$template} template to .env?", true)) { + $this->components->warn('Without these keys the app may not work as expected: '.implode(', ', $keys) + .". Copy them from .env.example, and check the {$template} template's documentation."); + + return; + } + + $lines = $this->assignments($files->get($example), array_keys($missing)); + + $files->put($env, rtrim($current, "\n")."\n\n# Added by saucebase:template-install ({$template}): defaults from the template's .env.example.\n" + .implode("\n", $lines)."\n"); + + $this->components->info('Added to .env: '.implode(', ', $keys).'.'); + } + + /** + * The template and every module it requires, directly or through another module. + * + * @param array $dependencies + * @return list + */ + private function closure(string $template, array $dependencies): array + { + $found = []; + $pending = [$template]; + + while ($pending !== []) { + $name = array_pop($pending); + + if (! in_array($name, $found, true)) { + $found[] = $name; + $pending = [...$pending, ...$dependencies[$name] ?? []]; + } + } + + return $found; + } + + /** + * The example's own lines for these keys, so quoting stays as written. A quoted value + * that spans lines is taken whole, up to its closing quote. + * + * @param list $keys + * @return list + */ + private function assignments(string $example, array $keys): array + { + $taken = []; + $closing = null; + + foreach (preg_split('/\R/', $example) ?: [] as $line) { + if ($closing !== null) { + $taken[] = $line; + $closing = preg_match('/(?option('state') ?: null; + } + + private function retry(string $error): int + { + $command = 'php artisan saucebase:template-install '.$this->argument('template') + .($this->option('state') ? ' --state='.$this->option('state') : '') + .collect((array) $this->option('set'))->map(fn (string $set) => ' --set='.escapeshellarg($set))->implode(''); + + $this->components->error($error); + $this->line(" Fix it, then run again: {$command}"); + + return self::FAILURE; + } + + private function refuse(string $error): int + { + $this->components->error($error); + + return self::FAILURE; + } +} diff --git a/src/Console/Traits/InstallsSaucebasePackages.php b/src/Console/Traits/InstallsSaucebasePackages.php new file mode 100644 index 0000000..db65ad4 --- /dev/null +++ b/src/Console/Traits/InstallsSaucebasePackages.php @@ -0,0 +1,95 @@ +mapWithKeys(fn (string $file) => [base_path($file) => @file_get_contents(base_path($file))]); + + if (Process::path(base_path())->forever() + ->run(['composer', 'require', ...$packages, '--no-interaction'], $this->writeOutput(...)) + ->successful()) { + return true; + } + + $saved->filter(fn ($contents) => $contents !== false) + ->each(fn (string $contents, string $path) => file_put_contents($path, $contents)); + + return false; + } + + /** + * A new process, the first to load the packages Composer just installed. + * TTY, so a module's own install command can ask its questions. + * + * `--configure`: these modules are being installed now, so their install settings + * are set (a template's `configure`, the `--set` flags, then prompts). A plain re-run of + * `saucebase:module-setup` leaves settings an admin may have changed since alone. + * + * @param string[] $modules In the order to set them up. + */ + protected function runSetup(array $modules, ?string $state, bool $force): bool + { + $settings = array_map(fn (string $set) => "--set={$set}", (array) $this->option('set')); + + return Process::path(base_path())->forever()->tty(SymfonyProcess::isTtySupported() && $this->input->isInteractive()) + ->run([PHP_BINARY, 'artisan', 'saucebase:module-setup', ...$modules, ...($state ? ["--state={$state}"] : []), ...($force ? ['--force'] : []), '--configure', ...$settings], $this->writeOutput(...)) + ->successful(); + } + + /** + * The state's seeders, in a new process for the same reason as setup. + * + * @param string[] $modules + */ + protected function seedState(array $modules, string $state, bool $force): bool + { + return Process::path(base_path())->forever()->tty(SymfonyProcess::isTtySupported() && $this->input->isInteractive()) + ->run([PHP_BINARY, 'artisan', 'modules:seed', ...array_map(fn (string $module) => "--module={$module}", $modules), "--state={$state}", ...($force ? ['--force'] : [])], $this->writeOutput(...)) + ->successful(); + } + + /** @return array> Each Saucebase module or template in composer.lock, by short name. */ + protected function lockedPackages(): array + { + return collect(json_decode((string) @file_get_contents(base_path('composer.lock')), true)['packages'] ?? []) + ->whereIn('type', ['saucebase-module', 'saucebase-template']) + ->keyBy(fn (array $package): string => Str::after($package['name'], '/')) + ->all(); + } + + /** @return array Each Saucebase module or template in composer.lock => the modules it requires. */ + protected function lockedModules(): array + { + $packages = $this->lockedPackages(); + $names = array_column($packages, 'name'); + + return collect($packages)->map(fn (array $package): array => collect(array_keys($package['require'] ?? [])) + ->intersect($names) + ->map(fn (string $name): string => Str::after($name, '/')) + ->values() + ->all())->all(); + } + + private function writeOutput(string $type, string $output): void + { + $this->output->write($output); + } +} diff --git a/src/CoreServiceProvider.php b/src/CoreServiceProvider.php index e73dd80..917b347 100644 --- a/src/CoreServiceProvider.php +++ b/src/CoreServiceProvider.php @@ -22,6 +22,8 @@ use Saucebase\Core\Console\Commands\SeedModulesCommand; use Saucebase\Core\Console\Commands\SyncModuleBoostCommand; use Saucebase\Core\Console\Commands\SyncModuleTaskfileCommand; +use Saucebase\Core\Console\Commands\TemplateCaptureCommand; +use Saucebase\Core\Console\Commands\TemplateInstallCommand; use Saucebase\Core\Http\Middleware\HandleAppearance; use Saucebase\Core\Http\Middleware\HandleInertiaRequests; use Saucebase\Core\Http\Middleware\HandleLocalization; @@ -103,6 +105,8 @@ public function boot(): void GenerateModuleTypesCommand::class, InstallCommand::class, ModuleInstallCommand::class, + TemplateInstallCommand::class, + TemplateCaptureCommand::class, ModuleSetupCommand::class, RecipeToModuleCommand::class, SeedModulesCommand::class, diff --git a/src/Filament/Pages/Dashboard.php b/src/Filament/Pages/Dashboard.php index f4e838e..3cb688c 100644 --- a/src/Filament/Pages/Dashboard.php +++ b/src/Filament/Pages/Dashboard.php @@ -7,6 +7,7 @@ use Filament\Pages\Dashboard\Actions\FilterAction; use Filament\Pages\Dashboard as BaseDashboard; use Filament\Pages\Dashboard\Concerns\HasFiltersAction; +use Filament\Schemas\Components\Component; use Filament\Schemas\Components\Utilities\Set; use Saucebase\Core\Filament\Period; @@ -19,6 +20,16 @@ class Dashboard extends BaseDashboard { use HasFiltersAction; + /** + * Widgets come from whichever modules are installed, so a half-width one can end up + * alone on its row. Dense flow lets a later widget that fits fill the gap, at the cost + * of the occasional widget moving up past its sort order. + */ + public function getWidgetsContentComponent(): Component + { + return parent::getWidgetsContentComponent()->extraAttributes(['style' => 'grid-auto-flow: row dense'], merge: true); + } + protected function getHeaderActions(): array { return [ diff --git a/src/ProjectConfig.php b/src/ProjectConfig.php index aa43246..7ac8028 100644 --- a/src/ProjectConfig.php +++ b/src/ProjectConfig.php @@ -18,6 +18,20 @@ public function isContributor(): bool return ($this->load()['contributor'] ?? false) === true; } + /** The template a template workspace develops (its folder under modules/). */ + public function template(): ?string + { + return $this->load()['template'] ?? null; + } + + /** Names the template this app builds, in saucebase.json. */ + public function setTemplate(string $template): void + { + $this->data = [...$this->load(), 'template' => $template]; + + file_put_contents(base_path('saucebase.json'), json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n"); + } + /** Whether pages may render on the server. On unless the project turned it off. */ public function ssr(): bool { diff --git a/src/Settings/InstallSetting.php b/src/Settings/InstallSetting.php new file mode 100644 index 0000000..2d9ea35 --- /dev/null +++ b/src/Settings/InstallSetting.php @@ -0,0 +1,25 @@ + $rules Validation rules, run on every value: prompt, flag and template. + */ + public function __construct( + public readonly string $label, + public readonly array $rules = [], + public readonly ?string $hint = null, + ) {} +} diff --git a/src/Settings/InstallSettings.php b/src/Settings/InstallSettings.php new file mode 100644 index 0000000..e6350c3 --- /dev/null +++ b/src/Settings/InstallSettings.php @@ -0,0 +1,184 @@ +, property: ReflectionProperty, setting: InstallSetting}> $marked + * @param list $unmarked The module's other settings: never set at install. + */ + private function __construct(public readonly string $module, private readonly array $marked, private readonly array $unmarked) {} + + public static function of(ModuleConfig $module): self + { + $marked = []; + $unmarked = []; + + foreach (glob($module->path('src/Settings').'/*.php') ?: [] as $file) { + $class = $module->pathToFullyQualifiedClassName($file); + + if (! class_exists($class) || ! is_subclass_of($class, Settings::class)) { + continue; + } + + foreach ((new ReflectionClass($class))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { + $attribute = $property->getAttributes(InstallSetting::class)[0] ?? null; + + if ($attribute !== null) { + $marked[$property->getName()] = ['class' => $class, 'property' => $property, 'setting' => $attribute->newInstance()]; + } elseif ($property->getDeclaringClass()->getName() === $class) { + $unmarked[] = $property->getName(); + } + } + } + + return new self($module->name, $marked, $unmarked); + } + + public function marks(string $name): bool + { + return isset($this->marked[$name]); + } + + /** A setting of this module's that is not marked: refused, so a template can't reach it. */ + public function declares(string $name): bool + { + return in_array($name, $this->unmarked, true); + } + + public function isEmpty(): bool + { + return $this->marked === []; + } + + /** + * The value as the property's type, checked by its rules. + * + * @throws InvalidArgumentException Why the value is refused. + */ + public function cast(string $name, mixed $value): mixed + { + if (! isset($this->marked[$name])) { + throw new InvalidArgumentException("{$this->module}.{$name} can't be set at install: it is not marked #[InstallSetting]."); + } + + ['property' => $property, 'setting' => $setting] = $this->marked[$name]; + $type = $property->getType(); + $typeName = $type instanceof ReflectionNamedType ? $type->getName() : 'mixed'; + + if ($type?->allowsNull() && ($value === null || $value === '')) { + return null; + } + + $cast = match (true) { + $typeName === 'bool' => is_bool($value) ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE), + $typeName === 'int' => is_int($value) || (is_string($value) && preg_match('/^-?\d+$/', $value)) ? (int) $value : null, + $typeName === 'string' => is_scalar($value) ? (string) $value : null, + is_subclass_of($typeName, BackedEnum::class) => is_int($value) || is_string($value) ? $typeName::tryFrom($value) : null, + default => throw new InvalidArgumentException("{$this->module}.{$name} has a type install settings don't support yet: {$typeName}."), + }; + + if ($cast === null) { + throw new InvalidArgumentException("{$this->module}.{$name} must be a {$this->describe($typeName)}: ".json_encode($value).'.'); + } + + // The type's own rule first: `between` and `max` measure a number only next to one. + $rules = [...($typeName === 'int' ? ['integer'] : []), ...$setting->rules]; + $validator = Validator::make(['value' => $cast instanceof BackedEnum ? $cast->value : $cast], ['value' => $rules]); + + if ($validator->fails()) { + throw new InvalidArgumentException("{$this->module}.{$name}: ".$validator->errors()->first('value')); + } + + return $cast; + } + + /** + * Asks for each setting not in `$skip`, the prompt picked by its type. + * + * @param array $defaults Cast values to start from (a template's); else the current one. + * @param list $skip Set by a flag: not asked. + * @return array + */ + public function ask(array $defaults, array $skip): array + { + $answers = []; + + foreach ($this->marked as $name => ['class' => $class, 'property' => $property, 'setting' => $setting]) { + if (in_array($name, $skip, true)) { + continue; + } + + $default = array_key_exists($name, $defaults) ? $defaults[$name] : app($class)->{$name}; + $typeName = $property->getType() instanceof ReflectionNamedType ? $property->getType()->getName() : 'mixed'; + $label = __($setting->label); + $hint = $setting->hint ? __($setting->hint) : ''; + $validate = function (string $value) use ($name): ?string { + try { + $this->cast($name, $value); + + return null; + } catch (InvalidArgumentException $e) { + return $e->getMessage(); + } + }; + + $answer = match (true) { + $typeName === 'bool' => confirm($label, (bool) $default, hint: $hint), + is_subclass_of($typeName, BackedEnum::class) => select( + $label, + collect($typeName::cases())->mapWithKeys(fn (BackedEnum $case) => [$case->value => method_exists($case, 'getLabel') ? $case->getLabel() : $case->name])->all(), + $default instanceof BackedEnum ? $default->value : $default, + hint: $hint, + ), + default => text($label, default: (string) $default, validate: $validate, hint: $hint), + }; + + $answers[$name] = $this->cast($name, $answer); + } + + return $answers; + } + + /** @param array $values Cast values, by property. */ + public function save(array $values): void + { + foreach (collect($values)->groupBy(fn ($value, string $name) => $this->marked[$name]['class'], preserveKeys: true) as $class => $group) { + $settings = app($class); + + foreach ($group as $name => $value) { + $settings->{$name} = $value; + } + + $settings->save(); + } + } + + private function describe(string $typeName): string + { + return match (true) { + $typeName === 'bool' => 'yes or no', + $typeName === 'int' => 'whole number', + is_subclass_of($typeName, BackedEnum::class) => 'one of '.implode(', ', array_map(fn (BackedEnum $case) => $case->value, $typeName::cases())), + default => $typeName, + }; + } +} diff --git a/stubs/app/README.md b/stubs/app/README.md index dd65708..75a436e 100644 --- a/stubs/app/README.md +++ b/stubs/app/README.md @@ -15,10 +15,10 @@ Built with [Saucebase](https://github.com/saucebase-dev/saucebase), on Laravel a ## Sign in -With demo data, sign in as `chef@saucebase.dev`, a full admin. Every demo account uses the +With the showcase state, sign in as `chef@saucebase.dev`, a full admin. Every showcase account uses the password saved in `.env` as `DEMO_PASSWORD`. The admin panel is at `/admin`. -Reload the demo data with `task db:reset:demo`. +Reload the showcase data with `task db:reset:showcase`. ## Modules diff --git a/stubs/app/Taskfile.yml b/stubs/app/Taskfile.yml index 5533df7..e88fa7a 100644 --- a/stubs/app/Taskfile.yml +++ b/stubs/app/Taskfile.yml @@ -99,16 +99,16 @@ tasks: - '{{.APP}} php artisan migrate:fresh --seed' - '{{.APP}} php artisan modules:seed' - db:reset:demo: - desc: Reset database and load sample content (the auth module's demo includes an admin) + db:reset:showcase: + desc: Reset database and load sample content (the auth module's showcase includes an admin) prompt: This will erase ALL data. Are you sure? cmds: - '{{.APP}} php artisan migrate:fresh --seed' - - '{{.APP}} php artisan modules:seed --demo' + - '{{.APP}} php artisan modules:seed --state=showcase' - db:seed:demo: + db:seed:showcase: desc: Seed every module with sample content - cmd: '{{.APP}} php artisan modules:seed --demo' + cmd: '{{.APP}} php artisan modules:seed --state=showcase' # ── Translation ─────────────────────────────────────────────── diff --git a/stubs/app/routes/navigation.php b/stubs/app/routes/navigation.php index 45b53cd..bd6d2a1 100644 --- a/stubs/app/routes/navigation.php +++ b/stubs/app/routes/navigation.php @@ -53,37 +53,6 @@ function (Section $section) { } ); -Navigation::add( - 'Discord', - 'https://discord.gg/hCajBky39t', - function (Section $section) { - $section->attributes([ - 'group' => 'secondary', - 'slug' => 'discord', - 'icon' => 'discord', - 'external' => true, - 'newPage' => true, - 'order' => 5, - 'class' => 'bg-[#5865F2]/10 text-[#4752C4] hover:bg-[#5865F2]/20 hover:text-[#3C45A5] dark:text-[#949CF7] dark:hover:text-[#B5BAFA]', - ]); - } -); - -Navigation::add( - 'Discord', - 'https://discord.gg/hCajBky39t', - function (Section $section) { - $section->attributes([ - 'group' => 'landing', - 'slug' => 'discord', - 'external' => true, - 'newPage' => true, - 'order' => 99, - 'class' => 'text-[#4752C4] hover:text-[#3C45A5] dark:text-[#949CF7] dark:hover:text-[#B5BAFA]', - ]); - } -); - Navigation::addWhen( fn () => Auth::user()?->can('access admin panel') ?? false, 'Admin', diff --git a/stubs/recipes/basic/.github/workflows/test.yml b/stubs/recipes/basic/.github/workflows/test.yml index 45e8231..55282c7 100644 --- a/stubs/recipes/basic/.github/workflows/test.yml +++ b/stubs/recipes/basic/.github/workflows/test.yml @@ -13,5 +13,5 @@ jobs: test: uses: saucebase-dev/core/.github/workflows/test-module.yml@main with: - module: ___Module___ + module: {module-} # dependencies: saucebase/auth # add space-separated packages if needed diff --git a/stubs/recipes/basic/Taskfile.yml b/stubs/recipes/basic/Taskfile.yml index 86b45ac..8fe05a0 100644 --- a/stubs/recipes/basic/Taskfile.yml +++ b/stubs/recipes/basic/Taskfile.yml @@ -14,9 +14,9 @@ tasks: # ── Database ────────────────────────────────────────────────── - db:seed:demo: + db:seed:showcase: desc: Seed the {Module} module with sample content - cmd: '{{.APP}} php artisan modules:seed --module={module} --demo' + cmd: '{{.APP}} php artisan modules:seed --module={module} --state=showcase' # ── Code Generation ──────────────────────────────────────────── diff --git a/stubs/recipes/basic/database/seeders/DemoModuleDatabaseSeeder.php b/stubs/recipes/basic/database/seeders/DemoModuleDatabaseSeeder.php deleted file mode 100644 index 9a85d9a..0000000 --- a/stubs/recipes/basic/database/seeders/DemoModuleDatabaseSeeder.php +++ /dev/null @@ -1,18 +0,0 @@ - -
+
{/* Header Section */}
diff --git a/stubs/recipes/basic/resources/js/vue/pages/Index.vue b/stubs/recipes/basic/resources/js/vue/pages/Index.vue index c1f1c7e..2c287b9 100644 --- a/stubs/recipes/basic/resources/js/vue/pages/Index.vue +++ b/stubs/recipes/basic/resources/js/vue/pages/Index.vue @@ -13,7 +13,7 @@ const title = '{Module}';