diff --git a/.github/workflows/demo.yaml b/.github/workflows/demo.yaml new file mode 100644 index 00000000..af1c9a81 --- /dev/null +++ b/.github/workflows/demo.yaml @@ -0,0 +1,90 @@ +name: Demo + +# The demo application, with PHP as WebAssembly, on GitHub Pages: see +# wasm-demo/castor.php. GitHub Pages must deploy from GitHub Actions, in the +# settings of the repository. + +on: + push: + branches: [ main ] + workflow_dispatch: ~ + +permissions: + contents: read + pages: write + id-token: write + +# One deployment at a time, the last push wins +concurrency: + group: pages + cancel-in-progress: true + +jobs: + deploy: + runs-on: ubuntu-latest + name: "Build and deploy the demo" + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + env: + COMPOSER_ROOT_VERSION: "dev-main" + defaults: + run: + working-directory: wasm-demo + steps: + - name: "Checkout" + uses: actions/checkout@v4 + + - name: "Setup PHP" + uses: shivammathur/setup-php@v2 + with: + php-version: "8.5" + tools: 'castor, composer:v2, flex' + coverage: none + + - name: "Setup node" + uses: actions/setup-node@v4 + with: + node-version: 24 + + - name: "Install PHP dependencies" + run: composer install --no-interaction --no-scripts + working-directory: . + + - name: "Install php-wasm-builder" + run: castor castor:composer install --no-interaction + + - name: "Configure GitHub Pages" + id: pages + uses: actions/configure-pages@v5 + + # The cache of the layers needs the docker-container driver of + # buildx, and the runtime token and URLs of GitHub Actions + - name: "Setup buildx" + uses: docker/setup-buildx-action@v3 + + - name: "Expose the GitHub Actions runtime" + uses: crazy-max/ghaction-github-runtime@v3 + + - name: "Build the demo" + run: > + castor demo:build + --base-path='${{ steps.pages.outputs.base_path }}/' + --set='*.cache-from=type=gha' + --set='*.cache-to=type=gha,mode=max,ignore-error=true' + + - name: "Check the pages of the admin panel" + run: castor demo:check + + # Only demo:check runs PHP in node + - name: "Remove the build for node" + run: rm public/build/php-node.* + + - name: "Upload the demo" + uses: actions/upload-pages-artifact@v3 + with: + path: wasm-demo/public + + - name: "Deploy to GitHub Pages" + id: deployment + uses: actions/deploy-pages@v4 diff --git a/config/routes.yaml b/config/routes.yaml index 9790f123..466f5cdb 100644 --- a/config/routes.yaml +++ b/config/routes.yaml @@ -1,8 +1,8 @@ index: path: / - controller: Symfony\Bundle\FrameworkBundle\Controller\TemplateController + controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController defaults: - template: base.html.twig + route: sylius_admin_ui_dashboard basic_create: path: /basic/create diff --git a/wasm-demo/.gitignore b/wasm-demo/.gitignore new file mode 100644 index 00000000..02ca1cbc --- /dev/null +++ b/wasm-demo/.gitignore @@ -0,0 +1,8 @@ +/.castor/vendor/ +/build/ +/public/build/ +/public/assets/ +/public/avatars/ +/public/bundles/ +/public/404.html +/.castor.stub.php diff --git a/wasm-demo/castor.composer.json b/wasm-demo/castor.composer.json new file mode 100644 index 00000000..2174784a --- /dev/null +++ b/wasm-demo/castor.composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "lyrixx/php-wasm-builder": "^1.0" + } +} diff --git a/wasm-demo/castor.composer.lock b/wasm-demo/castor.composer.lock new file mode 100644 index 00000000..d28e6184 --- /dev/null +++ b/wasm-demo/castor.composer.lock @@ -0,0 +1,64 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "97a46a37ed63ca804f0891c1c941ee32", + "packages": [ + { + "name": "lyrixx/php-wasm-builder", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/lyrixx/php-wasm-builder.git", + "reference": "59301bdddfd3d7387e8d7ae3b5e73ff633779a70" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lyrixx/php-wasm-builder/zipball/59301bdddfd3d7387e8d7ae3b5e73ff633779a70", + "reference": "59301bdddfd3d7387e8d7ae3b5e73ff633779a70", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions-internal.php", + "src/functions.php" + ], + "psr-4": { + "PhpWasm\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Builds PHP as WebAssembly: a Dockerfile, and a castor function to build stacks (a PHP version, extensions, what to embed) with one command", + "keywords": [ + "castor", + "emscripten", + "php", + "wasm", + "webassembly" + ], + "support": { + "issues": "https://github.com/lyrixx/php-wasm-builder/issues", + "source": "https://github.com/lyrixx/php-wasm-builder/tree/v1.0.0" + }, + "time": "2026-11-24T11:17:01+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/wasm-demo/castor.php b/wasm-demo/castor.php new file mode 100644 index 00000000..e16e303c --- /dev/null +++ b/wasm-demo/castor.php @@ -0,0 +1,247 @@ +php(WASM_PHP_VERSION) + ->extensions('ctype', 'dom', 'fileinfo', 'filter', 'iconv', 'mbstring', 'pdo_sqlite', 'session', 'simplexml', 'tokenizer', 'xml', 'xmlreader', 'xmlwriter') + ->memory('256mb') + ->embed(EMBED, at: '/app') + ->warmup('bin/console', 'cache:warmup') + ->opcache(Opcache::Runtime) + ->targets(Target::Web, Target::Node) + ->outputDir(PUBLIC_DIR . '/build'); +} + +#[AsTask(name: 'embed', namespace: 'demo', description: 'Prepares the application to embed, in build/embed, and its public files, in public/')] +function embed( + #[AsOption(description: 'The admin UI: shadcn or bootstrap', autocomplete: ['shadcn', 'bootstrap'])] + string $ui = 'shadcn', + #[AsOption(description: 'The color themes of shadcn, "none" for the neutral one', mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, autocomplete: ['blue', 'green', 'orange', 'rose', 'slate', 'stone', 'violet', 'zinc', 'none'])] + array $theme = ['rose'], +): void { + if (!in_array($ui, ['shadcn', 'bootstrap'], true)) { + throw new \InvalidArgumentException(\sprintf('The admin UI is "shadcn" or "bootstrap", not "%s".', $ui)); + } + + io()->section('The database, with the fixtures'); + $db = ROOT . '/var/demo.db'; + fs()->remove($db); + $dev = context() + ->withWorkingDirectory(ROOT) + ->withEnvironment(['APP_ENV' => 'dev', 'DATABASE_URL' => 'sqlite:///%kernel.project_dir%/var/demo.db']); + run(['php', 'bin/console', 'importmap:install'], context: $dev); + run(['php', 'bin/console', 'doctrine:schema:create', '-q'], context: $dev); + run(['php', 'bin/console', 'doctrine:fixtures:load', '-n', '-q'], context: $dev); + + io()->section('The application, without its dev dependencies'); + fs()->remove(EMBED); + fs()->mkdir(EMBED); + $mirror = static fn (string $path) => fs()->mirror(ROOT . "/{$path}", EMBED . "/{$path}"); + foreach (['app', 'assets', 'bin', 'config', 'templates', 'translations'] as $path) { + $mirror($path); + } + // Only Foundry needs them, a dev dependency + fs()->remove([EMBED . '/app/DataFixtures', EMBED . '/app/Factory', EMBED . '/app/Story']); + // symfony.lock: Flex does not run the recipes again + foreach (['importmap.php', 'symfony.lock'] as $path) { + fs()->copy(ROOT . "/{$path}", EMBED . "/{$path}"); + } + fs()->copy(ROOT . '/public/index.php', EMBED . '/public/index.php'); + foreach ((new Finder())->directories()->in(ROOT . '/src')->depth(0) as $package) { + foreach (['assets', 'config', 'public', 'src', 'templates', 'translations'] as $path) { + if (is_dir("{$package}/{$path}")) { + $mirror("src/{$package->getFilename()}/{$path}"); + } + } + } + fs()->mirror(__DIR__ . '/overlay', EMBED, options: ['override' => true]); + // DoctrineBundle 3 does not have them anymore, and the monorepo never runs + // in prod + $doctrine = EMBED . '/config/packages/doctrine.yaml'; + fs()->dumpFile($doctrine, preg_replace('/^\s+(auto_generate_proxy_classes|proxy_dir):.*\n/m', '', file_get_contents($doctrine))); + + $composer = json_decode(file_get_contents(ROOT . '/composer.json'), true, flags: \JSON_THROW_ON_ERROR); + foreach ($composer['require-dev'] as $package => $constraint) { + if (!in_array($package, DEV_ONLY_PACKAGES, true)) { + $composer['require'][$package] = $constraint; + } + } + unset($composer['require-dev'], $composer['autoload-dev'], $composer['scripts']); + $composer['autoload']['psr-4']['App\\'] = 'app/'; + $composer['config']['platform']['php'] = WASM_PHP_VERSION; + fs()->dumpFile(EMBED . '/composer.json', json_encode($composer, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES) . "\n"); + + $embed = context()->withWorkingDirectory(EMBED)->withEnvironment(['APP_ENV' => 'prod', 'APP_DEBUG' => '0']); + run(['composer', 'update', '--no-dev', '--no-scripts', '--no-interaction', '--classmap-authoritative'], context: $embed); + fs()->mirror(ROOT . '/assets/vendor', EMBED . '/assets/vendor'); + + io()->section(\sprintf('The %s admin UI', $ui)); + // The script of the monorepo: the bundle, its configuration, the template + // namespaces, and the Tailwind stylesheet of shadcn + run(['bin/switch-admin-ui', $ui], context: $embed); + if ('shadcn' === $ui) { + run(['bin/switch-admin-theme', ...$theme], context: $embed); + // What only works with shadcn, as the test credentials on the login + // page: before the Tailwind stylesheet is built, for its classes + fs()->mirror(__DIR__ . '/overlay-shadcn', EMBED, options: ['override' => true]); + } + + io()->section('The public files, that the server serves, not PHP'); + // Iconify is called for the icons that are not local: PHP has no network + // in the browser + run(['php', 'bin/console', 'ux:icons:lock', '-q'], context: $embed); + // ux:icons:lock only finds the ones of the templates: the menus and the + // grids name theirs in PHP and in the configuration + $icons = []; + foreach ((new Finder())->files()->in([EMBED . '/app', EMBED . '/config', EMBED . '/src', EMBED . '/templates'])->name(['*.php', '*.yaml', '*.twig']) as $file) { + // The usual sets, and any icon given to setIcon() or to an "icon" key + preg_match_all('/[\'"]((?:tabler|lucide|mdi):[a-z0-9-]+)[\'"]/', $file->getContents(), $matches); + array_push($icons, ...$matches[1]); + preg_match_all('/(?:setIcon\(\s*|[\'"]?icon[\'"]?\s*(?:=>|:)\s*)[\'"]([a-z0-9-]+:[a-z0-9-]+)[\'"]/', $file->getContents(), $matches); + array_push($icons, ...$matches[1]); + } + foreach (array_unique($icons) as $icon) { + if (!is_file(EMBED . '/assets/icons/' . str_replace(':', '/', $icon) . '.svg')) { + run(['php', 'bin/console', 'ux:icons:import', $icon, '-q'], context: $embed->withAllowFailure()); + } + } + run(['php', 'bin/console', 'assets:install', 'public', '--no-interaction', '-q'], context: $embed); + run(['php', 'bin/console', 'tailwind:build', '--minify', '-q'], context: $embed); + run(['php', 'bin/console', 'asset-map:compile', '-q'], context: $embed); + foreach (['assets', 'bundles'] as $path) { + fs()->remove(PUBLIC_DIR . "/{$path}"); + fs()->rename(EMBED . "/public/{$path}", PUBLIC_DIR . "/{$path}"); + } + fs()->remove(PUBLIC_DIR . '/avatars'); + fs()->mirror(ROOT . '/public/avatars', PUBLIC_DIR . '/avatars'); + // What PHP reads of the compiled assets, to render the importmap + fs()->mkdir(EMBED . '/public/assets'); + foreach ((new Finder())->files()->in(PUBLIC_DIR . '/assets')->depth(0)->name('*.json') as $file) { + fs()->copy($file->getPathname(), EMBED . '/public/assets/' . $file->getFilename()); + } + // Compiled in public/, and the cache is warmed up in PHP as WebAssembly, + // with the paths it has there + fs()->remove([EMBED . '/assets/vendor', EMBED . '/var']); + fs()->remove((new Finder())->directories()->in(EMBED . '/src')->depth(1)->name(['assets', 'public'])); + + // What is embedded is in the memory of PHP: only the English data of + // symfony/intl, 27 MB with every locale + fs()->remove((new Finder())->files()->in(EMBED . '/vendor/symfony/intl/Resources/data')->notName(['en.php', 'en_*.php', 'root.php', 'meta.php', '*.txt'])); + fs()->remove((new Finder())->directories()->in(EMBED . '/vendor')->depth('< 4')->name(['tests', 'Tests', 'doc', 'docs'])); + + io()->section('The database, and the name of the build'); + // Keep in sync with public/sw.js + fs()->copy($db, EMBED . '/data/demo.db'); + fs()->dumpFile(EMBED . '/data/build-id', bin2hex(random_bytes(8))); + + run(['du', '-sh', EMBED, EMBED . '/vendor']); +} + +#[AsTask(name: 'build', namespace: 'demo', description: 'Builds PHP as WebAssembly, with the application')] +function build_task( + #[AsOption(description: 'The admin UI: shadcn or bootstrap', autocomplete: ['shadcn', 'bootstrap'])] + string $ui = 'shadcn', + #[AsOption(description: 'The color themes of shadcn, "none" for the neutral one', mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, autocomplete: ['blue', 'green', 'orange', 'rose', 'slate', 'stone', 'violet', 'zinc', 'none'])] + array $theme = ['rose'], + #[AsOption(description: 'Where the demo is in the URLs, "/Stack/" on the GitHub Pages of Sylius/Stack')] + string $basePath = '/', + #[AsOption(description: 'Given to "docker buildx bake --set", for a cache', mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY)] + array $set = [], + #[AsOption(description: 'Do not prepare the application again')] + bool $skipEmbed = false, +): void { + if (!preg_match('{^/([a-zA-Z0-9._-]+/)*$}', $basePath)) { + throw new \InvalidArgumentException(\sprintf('The base path starts and ends with a slash, as "/Stack/": "%s" does not.', $basePath)); + } + if (!$skipEmbed) { + embed($ui, $theme); + } + + // A cache made on the host has its paths, and its 64-bit integers: PHP as + // WebAssembly makes its own, with 32-bit ones + fs()->remove(EMBED . '/var'); + + // The web server serves the avatars, under the base path: vich_uploader_asset() + // does not add it. Keep in sync with config/packages/vich_uploader.yaml + $vich = EMBED . '/config/packages/vich_uploader.yaml'; + fs()->dumpFile($vich, preg_replace('{(uri_prefix:\s*)\S*(avatars/speakers)}', '${1}' . $basePath . '${2}', file_get_contents($vich))); + + io()->section('PHP as WebAssembly'); + build([stack()], $set); + + // php-web.mjs does not change when only the application does: the browser + // updates the service worker when a script that it imports changes, and + // fetches the .wasm again with another URL. Keep in sync with public/sw.js + fs()->dumpFile(PUBLIC_DIR . '/build/version.js', \sprintf("export default '%s';\n", file_get_contents(EMBED . '/data/build-id'))); + + // GitHub Pages answers a link to a page of the application, before the + // service worker is there, with 404.html: the start page, whose relative + // URLs are the ones of the root of the demo + fs()->dumpFile(PUBLIC_DIR . '/404.html', str_replace('', \sprintf("\n ", htmlspecialchars($basePath)), file_get_contents(PUBLIC_DIR . '/index.html'))); +} + +#[AsTask(name: 'check', namespace: 'demo', description: 'Logs in, and checks that the pages of the admin panel answer, in PHP as WebAssembly, in node')] +function check(): void +{ + run(['node', 'check.mjs', PUBLIC_DIR . '/build/php-node.mjs']); +} + +#[AsTask(name: 'serve', namespace: 'demo', description: 'Serves the demo on http://localhost:8000')] +function serve(): void +{ + io()->writeln('http://localhost:8000'); + run(['php', '-S', 'localhost:8000', '-t', PUBLIC_DIR], context: context()->withTimeout(null)); +} diff --git a/wasm-demo/check.mjs b/wasm-demo/check.mjs new file mode 100644 index 00000000..3944b504 --- /dev/null +++ b/wasm-demo/check.mjs @@ -0,0 +1,100 @@ +// Checks the demo without a browser: PHP as WebAssembly, in node, logs in, +// then follows the links of the admin panel from the dashboard, and fails on +// any page that does not answer. Run by castor demo:check, before a deploy. +// +// node check.mjs public/build/php-node.mjs + +import { pathToFileURL } from 'node:url'; +import path from 'node:path'; + +// Keep in sync with castor.php and public/sw.js +const DOCUMENT_ROOT = '/app/public'; +const ORIGIN = 'http://localhost'; +const MAX_PAGES = 150; +// What changes the data or ends the session: not followed +const SKIPPED = [/\/logout/, /\/delete/, /\/bulk-delete/]; + +const build = path.resolve(process.argv[2] ?? 'public/build/php-node.mjs'); +const { default: createPhp } = await import(pathToFileURL(build)); +const php = await createPhp(); + +const { exitCode, stdout } = await php.runCode(` + @mkdir('/stack/sessions', 0777, true); + copy('/app/data/demo.db', '/stack/data.db'); +`); +if (0 !== exitCode) { + throw new Error(`The database is not created: ${stdout}`); +} + +const cookies = new Map(); +const decoder = new TextDecoder(); + +async function request(method, url, body = '') { + const headers = { Origin: ORIGIN, Cookie: [...cookies].map(([name, value]) => `${name}=${value}`).join('; ') }; + if ('' !== body) { + headers['Content-Type'] = 'application/x-www-form-urlencoded'; + } + const response = await php.request({ method, url: ORIGIN + url, headers, body }, { documentRoot: DOCUMENT_ROOT }); + for (const [name, value] of response.headers) { + if ('set-cookie' === name.toLowerCase()) { + const [pair] = value.split(';'); + const separator = pair.indexOf('='); + cookies.set(pair.slice(0, separator), pair.slice(separator + 1)); + } + } + + return { ...response, text: decoder.decode(response.body) }; +} + +const home = await request('GET', '/'); +const homeLocation = home.headers.find(([name]) => 'location' === name.toLowerCase())?.[1] ?? ''; +if (![301, 302].includes(home.status) || !homeLocation.endsWith('/admin/')) { + throw new Error(`The home page does not redirect to the admin panel (${home.status}, ${homeLocation}): ${home.stderr}`); +} +console.log(`${home.status} / -> ${homeLocation}`); + +const login = await request('GET', '/admin/login'); +const token = login.text.match(/name="_csrf_admin_security_token" value="([^"]+)"/)?.[1]; +if (200 !== login.status || undefined === token) { + throw new Error(`The login page answers ${login.status}: ${login.stderr}`); +} +const loggedIn = await request('POST', '/admin/login_check', new URLSearchParams({ + _username: 'admin@example.com', + _password: 'admin', + _csrf_admin_security_token: token, +}).toString()); +const location = loggedIn.headers.find(([name]) => 'location' === name.toLowerCase())?.[1] ?? ''; +if (302 !== loggedIn.status || location.includes('/login')) { + throw new Error(`The login fails (${loggedIn.status}, ${location}): ${loggedIn.stderr}`); +} + +const queue = ['/admin/']; +const seen = new Set(queue); +const failures = []; +let visited = 0; +while (queue.length > 0 && visited < MAX_PAGES) { + const url = queue.shift(); + visited++; + const response = await request('GET', url); + console.log(`${response.status} ${url}`); + if (response.status >= 500) { + failures.push(`${url}: ${response.stderr.split('\n').find((line) => line.includes('[critical]')) ?? response.stderr}`); + continue; + } + + for (const [, href] of response.text.matchAll(/href="(\/admin\/[^"#]*)"/g)) { + const link = href.replaceAll('&', '&'); + // Once per page: not each sorting, filter and page of a grid + const page = link.split('?')[0]; + if (!seen.has(page) && !SKIPPED.some((pattern) => pattern.test(link))) { + seen.add(page); + queue.push(link); + } + } +} + +if (failures.length > 0) { + console.error(`\n${failures.length} page(s) fail:\n${failures.join('\n')}`); + process.exit(1); +} +console.log(`\n${visited} pages answer.`); diff --git a/wasm-demo/overlay-shadcn/config/packages/demo_login.yaml b/wasm-demo/overlay-shadcn/config/packages/demo_login.yaml new file mode 100644 index 00000000..45aa1c5e --- /dev/null +++ b/wasm-demo/overlay-shadcn/config/packages/demo_login.yaml @@ -0,0 +1,10 @@ +# The credentials of the demo, on the login page, as on demo.sylius.com: after +# the header, before the flashes and the form, whose priority is 0 +sylius_twig_hooks: + hooks: + 'sylius_admin.security.login.page.content': + header: + priority: 200 + credentials: + template: 'demo/security/login/credentials.html.twig' + priority: 100 diff --git a/wasm-demo/overlay-shadcn/templates/demo/security/login/credentials.html.twig b/wasm-demo/overlay-shadcn/templates/demo/security/login/credentials.html.twig new file mode 100644 index 00000000..3940aafb --- /dev/null +++ b/wasm-demo/overlay-shadcn/templates/demo/security/login/credentials.html.twig @@ -0,0 +1,10 @@ + + {{ ux_icon('lucide:info', {'aria-hidden': 'true'}) }} + {{ 'app.demo.test_credentials'|trans({}, 'demo') }} + +

+ {{ 'app.demo.username'|trans({}, 'demo') }}: admin@example.com
+ {{ 'app.demo.password'|trans({}, 'demo') }}: admin +

+
+
diff --git a/wasm-demo/overlay-shadcn/translations/demo.en.yaml b/wasm-demo/overlay-shadcn/translations/demo.en.yaml new file mode 100644 index 00000000..408c2ace --- /dev/null +++ b/wasm-demo/overlay-shadcn/translations/demo.en.yaml @@ -0,0 +1,5 @@ +app: + demo: + password: Password + test_credentials: Test credentials + username: Username diff --git a/wasm-demo/overlay/.env b/wasm-demo/overlay/.env new file mode 100644 index 00000000..89c8486e --- /dev/null +++ b/wasm-demo/overlay/.env @@ -0,0 +1,8 @@ +# The application runs in the browser: nothing here is a secret. +APP_ENV=prod +APP_DEBUG=0 +APP_LOCALE=en +APP_SECRET=it-runs-in-a-browser-it-is-not-a-secret + +# /stack is kept in IndexedDB, keep in sync with ../../public/sw.js +DATABASE_URL="sqlite:////stack/data.db" diff --git a/wasm-demo/overlay/config/packages/wasm.yaml b/wasm-demo/overlay/config/packages/wasm.yaml new file mode 100644 index 00000000..1319a301 --- /dev/null +++ b/wasm-demo/overlay/config/packages/wasm.yaml @@ -0,0 +1,8 @@ +# What the application needs to run as WebAssembly, in a service worker: the +# sessions are in /stack, that is kept in IndexedDB, as the database. The +# service worker is stopped after 30 s without a request, and the files in +# memory with it. +framework: + session: + handler_id: session.handler.native_file + save_path: /stack/sessions diff --git a/wasm-demo/public/index.html b/wasm-demo/public/index.html new file mode 100644 index 00000000..68bf31dd --- /dev/null +++ b/wasm-demo/public/index.html @@ -0,0 +1,66 @@ + + + + + + Sylius Stack, in the browser + + + + +

Sylius Stack, in the browser

+

PHP, compiled to WebAssembly, runs Symfony, Doctrine and SQLite in a service worker: no server runs PHP.

+
+

Starting PHP in the service worker…

+

Log in with admin@example.com / admin.

+ + + + diff --git a/wasm-demo/public/sw.js b/wasm-demo/public/sw.js new file mode 100644 index 00000000..d9637b60 --- /dev/null +++ b/wasm-demo/public/sw.js @@ -0,0 +1,41 @@ +// The web server of the demo: PHP, as WebAssembly, runs the Sylius Stack test +// application in this service worker, and answers every request of its scope. +// The browser stops it after 30 s without a request, and PHP with it: the next +// request starts PHP again, that finds the database and the sessions in +// IndexedDB. + +import createPhp, { serveInServiceWorker } from './build/php-web.mjs'; +// The name of the build, written by castor demo:build: a new build is a new +// service worker, and a new .wasm, not the ones the browser has +import version from './build/version.js'; + +// Written by castor demo:embed, keep in sync with ../castor.php and +// ../overlay/.env +const DATA = '/app/data'; +const PERSISTED = '/stack'; + +serveInServiceWorker(async () => { + const php = await createPhp({ + persist: PERSISTED, + locateFile: (path, directory) => `${directory}${path}?v=${version}`, + }); + + // A new build comes with a new database, with the fixtures. Done in PHP, + // not with php.FS: it does not see what IndexedDB has before the first run + const { exitCode, stdout } = await php.runCode(` + if (@file_get_contents('${PERSISTED}/build-id') !== file_get_contents('${DATA}/build-id')) { + @mkdir('${PERSISTED}/sessions', 0777, true); + copy('${DATA}/demo.db', '${PERSISTED}/data.db'); + copy('${DATA}/build-id', '${PERSISTED}/build-id'); + } + `); + if (0 !== exitCode) { + throw new Error(`The database is not created: ${stdout}`); + } + + return php; +}, { + documentRoot: '/app/public', + // Served by the web server, not by PHP: see castor demo:embed + except: ['build/', 'assets/', 'bundles/', 'avatars/'], +});