@karlis-vagalis/pi-flare 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kārlis Vagalis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # pi-flare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Create and run local web apps from your [Pi](https://pi.dev/) session.
4
+
5
+ Flare gives Pi tools to create websites and small apps, then serves them through
6
+ a shared [celld](https://celld.dev/) runtime. Apps are ordinary files: you or the
7
+ agent can edit them, and the changes go live without a deployment step.
8
+
9
+ Use a static app for a page, a Worker for a backend, or a durable app when you
10
+ need saved state.
11
+
12
+ ## Requirements
13
+
14
+ Install these before starting Pi:
15
+ - [Bun](https://bun.sh/) 1.3.10 or newer.
16
+ - [celld](https://celld.dev/), tested with 0.6.2.
17
+ - esbuild, tested with 0.28.2: `bun add --global esbuild`.
18
+
19
+ All three must be on `PATH`. Pi itself needs Node.js 22.12 or newer.
20
+
21
+ ## Install
22
+
23
+ Install from the [pi-mono repository](https://github.com/karlis-vagalis/pi-mono):
24
+
25
+ ```bash
26
+ pi install git:github.com/karlis-vagalis/pi-mono
27
+ ```
28
+
29
+ To install only Flare from npm, once it has been published:
30
+
31
+ ```bash
32
+ pi install npm:@karlis-vagalis/pi-flare
33
+ ```
34
+
35
+ Use one installation method, not both. Run `/reload` in an existing Pi session
36
+ after installing.
37
+
38
+ ## Use it
39
+
40
+ Run `/flare` to start the runtime and see your apps. You can then ask Pi to build
41
+ something:
42
+
43
+ > Create a small counter app with Flare. Save the count so it survives restarts.
44
+
45
+ Open [127.0.0.1:53762](http://127.0.0.1:53762/) to browse your apps. Source files
46
+ live under `~/.pi/flare/<app-id>/`. Static file edits are served immediately;
47
+ backend edits trigger a rebuild. Reload the browser to see frontend changes.
48
+
49
+ Pi gets five tools:
50
+
51
+ | Tool | What it does |
52
+ | -------------- | -------------------------------------------------- |
53
+ | `flare_create` | Create a static, Worker, or durable app |
54
+ | `flare_list` | List apps and build status |
55
+ | `flare_get` | Find an app's directory, URLs, and any build error |
56
+ | `flare_update` | Change its title, description, or expiry |
57
+ | `flare_delete` | Remove its source files, keeping durable data |
58
+
59
+ Apps stay until you delete them unless you set a lifetime with `ttl_seconds`.
60
+ The runtime stops when the last Pi session using it closes; app files and saved
61
+ state remain on disk.
62
+
63
+ ## Backups and settings
64
+
65
+ Flare backs up app files and durable data every 12 hours while it is running.
66
+ Backups go to `~/.pi/flare-backups` and are not pruned automatically.
67
+ - `/flare backup` makes a backup now.
68
+ - `/flare restore <backup>` restores all apps and durable data, after saving a
69
+ recovery backup of the current state.
70
+
71
+ Set `PI_FLARE_HOME` to change the app directory, or `PI_FLARE_BACKUP_DIR` to change
72
+ the backup location. See the [reference](docs/runtime.md) for all settings,
73
+ routing examples, backup details, and runtime limits.
74
+
75
+ ## Local use
76
+
77
+ Flare is for apps you trust, running on your own machine. Apps share a browser
78
+ origin and have no browser login. Keep the default loopback address unless you
79
+ understand the exposure; use an authenticated proxy before making apps reachable
80
+ from another machine.
81
+
82
+ ## Development
83
+
84
+ Flare is part of the [pi-mono workspace](https://github.com/karlis-vagalis/pi-mono).
85
+ From the repository root:
86
+
87
+ ```bash
88
+ bun install
89
+ bun run --filter @karlis-vagalis/pi-flare check
90
+ bun run --filter @karlis-vagalis/pi-flare build
91
+ bun run --filter @karlis-vagalis/pi-flare smoke
92
+ ```
93
+
94
+ The smoke check requires celld and esbuild. It uses temporary apps and ports,
95
+ not your existing Flare data.
96
+
97
+ Releases use the same version as the other extensions in this repository.
98
+ Maintainers can publish all packages locally with `just publish` from the root,
99
+ or push a `v*` tag to use the GitHub workflow.
100
+
101
+ ## License
102
+
103
+ [MIT](LICENSE)
package/dist/backup.js ADDED
@@ -0,0 +1,156 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { copyFile, cp, mkdir, open as promises_open, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
4
+ import { resolve } from "node:path";
5
+ import { z } from "zod";
6
+ import { containsPath } from "./schema.js";
7
+ import { appIds } from "./storage.js";
8
+ const SnapshotTimeSchema = z.string().regex(/^backup-\d+-[a-f0-9-]{36}$/).transform((name)=>Number(name.split("-")[1])).pipe(z.number().int().nonnegative());
9
+ const sqliteHeader = Buffer.from("SQLite format 3\0");
10
+ function backupRoot(settings) {
11
+ const key = createHash("sha256").update(settings.root).digest("hex").slice(0, 16);
12
+ return resolve(settings.backupDirectory, key);
13
+ }
14
+ async function latestBackup(settings) {
15
+ try {
16
+ const entries = await readdir(backupRoot(settings), {
17
+ withFileTypes: true
18
+ });
19
+ let latest;
20
+ for (const entry of entries){
21
+ if (!entry.isDirectory()) continue;
22
+ const time = SnapshotTimeSchema.safeParse(entry.name);
23
+ if (time.success) latest = Math.max(latest ?? 0, time.data);
24
+ }
25
+ return latest;
26
+ } catch (error) {
27
+ if ("ENOENT" !== error.code) throw error;
28
+ return;
29
+ }
30
+ }
31
+ async function copyState(source, destination) {
32
+ await mkdir(destination, {
33
+ recursive: true,
34
+ mode: 448
35
+ });
36
+ for (const entry of (await readdir(source, {
37
+ withFileTypes: true
38
+ }))){
39
+ if (/-(wal|shm|journal)$/.test(entry.name)) continue;
40
+ const from = resolve(source, entry.name);
41
+ const to = resolve(destination, entry.name);
42
+ if (entry.isDirectory()) {
43
+ await copyState(from, to);
44
+ continue;
45
+ }
46
+ if (!entry.isFile()) throw new Error(`Unsupported file in Flare durable state: ${from}`);
47
+ const file = await promises_open(from, "r");
48
+ const header = Buffer.alloc(sqliteHeader.length);
49
+ try {
50
+ await file.read(header, 0, header.length, 0);
51
+ } finally{
52
+ await file.close();
53
+ }
54
+ if (header.equals(sqliteHeader)) {
55
+ const database = new Database(from, {
56
+ readonly: true
57
+ });
58
+ try {
59
+ await writeFile(to, database.serialize(), {
60
+ mode: 384
61
+ });
62
+ } finally{
63
+ database.close();
64
+ }
65
+ } else await copyFile(from, to);
66
+ }
67
+ }
68
+ async function createBackup(settings) {
69
+ const base = backupRoot(settings);
70
+ await mkdir(base, {
71
+ recursive: true,
72
+ mode: 448
73
+ });
74
+ if (containsPath(await realpath(settings.root), await realpath(base))) throw new Error("Flare backups must be stored outside PI_FLARE_HOME");
75
+ const temporary = resolve(base, `.partial-${randomUUID()}`);
76
+ await mkdir(temporary, {
77
+ mode: 448
78
+ });
79
+ try {
80
+ for (const id of (await appIds(settings.root)))await cp(resolve(settings.root, id), resolve(temporary, id), {
81
+ recursive: true,
82
+ dereference: false,
83
+ verbatimSymlinks: true,
84
+ preserveTimestamps: true
85
+ });
86
+ const state = resolve(settings.root, "runtime/.celld/dev");
87
+ let hasState = true;
88
+ try {
89
+ await realpath(state);
90
+ } catch (error) {
91
+ if ("ENOENT" !== error.code) throw error;
92
+ hasState = false;
93
+ }
94
+ const savedState = resolve(temporary, "runtime/.celld/dev");
95
+ if (hasState) await copyState(state, savedState);
96
+ else await mkdir(savedState, {
97
+ recursive: true,
98
+ mode: 448
99
+ });
100
+ const completedAt = Date.now();
101
+ await writeFile(resolve(temporary, "backup.json"), `${JSON.stringify({
102
+ version: 2,
103
+ root: settings.root,
104
+ completedAt
105
+ }, null, 2)}\n`, {
106
+ mode: 384
107
+ });
108
+ const path = resolve(base, `backup-${completedAt}-${randomUUID()}`);
109
+ await rename(temporary, path);
110
+ console.log(`FLARE_BACKUP ${path}`);
111
+ return {
112
+ path,
113
+ completedAt
114
+ };
115
+ } finally{
116
+ await rm(temporary, {
117
+ recursive: true,
118
+ force: true
119
+ });
120
+ }
121
+ }
122
+ class Backups {
123
+ settings;
124
+ queue;
125
+ running;
126
+ nextAttempt = 0;
127
+ constructor(settings, queue = (action)=>action()){
128
+ this.settings = settings;
129
+ this.queue = queue;
130
+ }
131
+ check(now = Date.now()) {
132
+ if (this.running) return this.running;
133
+ if (now < this.nextAttempt) return Promise.resolve();
134
+ this.running = (async ()=>{
135
+ const latest = await latestBackup(this.settings);
136
+ if (void 0 !== latest && now < latest + this.settings.backupIntervalMs) {
137
+ this.nextAttempt = latest + this.settings.backupIntervalMs;
138
+ return;
139
+ }
140
+ await this.queue(async ()=>{
141
+ const snapshot = await createBackup(this.settings);
142
+ this.nextAttempt = snapshot.completedAt + this.settings.backupIntervalMs;
143
+ });
144
+ })().catch((error)=>{
145
+ this.nextAttempt = now + Math.min(this.settings.backupIntervalMs, 60000);
146
+ throw error;
147
+ }).finally(()=>{
148
+ this.running = void 0;
149
+ });
150
+ return this.running;
151
+ }
152
+ async wait() {
153
+ await this.running;
154
+ }
155
+ }
156
+ export { Backups, SnapshotTimeSchema, backupRoot, createBackup };
@@ -0,0 +1,165 @@
1
+ import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
2
+ const workers = new Map();
3
+ async function published(env, id) {
4
+ const response = await fetch(`${env.REGISTRY}/bundle/${id}`, {
5
+ headers: {
6
+ authorization: `Bearer ${env.TOKEN}`
7
+ }
8
+ });
9
+ if (!response.ok) throw Object.assign(new Error(`App unavailable (${response.status})`), {
10
+ status: response.status
11
+ });
12
+ return response.json();
13
+ }
14
+ function load(env, ctx, id, app) {
15
+ return env.LOADER.get(`${id}:${app.revision}`, ()=>({
16
+ compatibilityDate: "2026-01-01",
17
+ mainModule: "worker.js",
18
+ modules: {
19
+ "worker.js": app.source
20
+ },
21
+ limits: {
22
+ cpuMs: 50,
23
+ subRequests: 50
24
+ },
25
+ env: {
26
+ ...app.manifest.vars,
27
+ ASSETS: ctx.exports.Assets({
28
+ props: {
29
+ id
30
+ }
31
+ }),
32
+ OBJECTS: ctx.exports.Objects({
33
+ props: {
34
+ id
35
+ }
36
+ })
37
+ }
38
+ }));
39
+ }
40
+ export class Assets extends WorkerEntrypoint {
41
+ async fetch(request) {
42
+ const url = new URL(request.url);
43
+ return fetch(`${this.env.REGISTRY}/assets/${this.ctx.props.id}${url.pathname}${url.search}`, {
44
+ method: request.method,
45
+ headers: {
46
+ authorization: `Bearer ${this.env.TOKEN}`
47
+ }
48
+ });
49
+ }
50
+ }
51
+ export class Objects extends WorkerEntrypoint {
52
+ fetch(request) {
53
+ const url = new URL(request.url);
54
+ const [, className, name, ...path] = url.pathname.split("/");
55
+ if (!className || !name || !/^[A-Za-z0-9_-]{1,128}$/.test(name)) return new Response("Use /ClassName/object-name/path", {
56
+ status: 400
57
+ });
58
+ url.pathname = `/${path.join("/")}`;
59
+ const forwarded = new Request(url, request);
60
+ forwarded.headers.set("x-flare-class", className);
61
+ forwarded.headers.set("x-flare-name", name);
62
+ return this.env.SUPERVISOR.getByName(this.ctx.props.id).fetch(forwarded);
63
+ }
64
+ }
65
+ export class Supervisor extends DurableObject {
66
+ async fetch(request) {
67
+ const facet = await this.ctx.blockConcurrencyWhile(async ()=>{
68
+ const id = this.ctx.id.name;
69
+ const app = await published(this.env, id);
70
+ const className = request.headers.get("x-flare-class");
71
+ if ("worker" !== app.manifest.type || !app.manifest.objects.includes(className)) throw new Error("Durable class is not declared in app.json objects");
72
+ if (this.revision !== app.revision) {
73
+ for (const name of this.names ?? [])this.ctx.facets.abort(name, "App code reloaded");
74
+ this.worker?.dispose();
75
+ this.worker = load(this.env, this.ctx, id, app);
76
+ this.names = new Set();
77
+ this.revision = app.revision;
78
+ }
79
+ const name = request.headers.get("x-flare-name");
80
+ const key = JSON.stringify([
81
+ className,
82
+ name
83
+ ]);
84
+ this.names.add(key);
85
+ return this.ctx.facets.get(key, ()=>({
86
+ class: this.worker.getDurableObjectClass(className),
87
+ id: name
88
+ }));
89
+ });
90
+ const forwarded = new Request(request);
91
+ forwarded.headers.delete("x-flare-class");
92
+ forwarded.headers.delete("x-flare-name");
93
+ return facet.fetch(forwarded);
94
+ }
95
+ }
96
+ export default {
97
+ async fetch (request, env, ctx) {
98
+ const url = new URL(request.url);
99
+ if ("/_flare/health" === url.pathname) return new Response("pi-flare");
100
+ if ("/" === url.pathname) {
101
+ if ("GET" !== request.method && "HEAD" !== request.method) return new Response("Method not allowed", {
102
+ status: 405,
103
+ headers: {
104
+ Allow: "GET, HEAD"
105
+ }
106
+ });
107
+ const page = await fetch(`${env.REGISTRY}/directory`, {
108
+ method: request.method,
109
+ headers: {
110
+ authorization: `Bearer ${env.TOKEN}`
111
+ }
112
+ });
113
+ return new Response("HEAD" === request.method ? null : page.body, {
114
+ status: page.status,
115
+ headers: page.headers
116
+ });
117
+ }
118
+ const match = /^\/([a-z0-9]+(?:-[a-z0-9]+)*)(\/.*)?$/.exec(url.pathname);
119
+ if (!match) return new Response("Not found", {
120
+ status: 404
121
+ });
122
+ const [, id, path] = match;
123
+ if (!path) {
124
+ url.pathname += "/";
125
+ return Response.redirect(url, 308);
126
+ }
127
+ url.pathname = path;
128
+ try {
129
+ const app = await published(env, id);
130
+ const forwarded = new Request(url, request);
131
+ const assets = ctx.exports.Assets({
132
+ props: {
133
+ id
134
+ }
135
+ });
136
+ if ("static" === app.manifest.type) {
137
+ workers.get(id)?.worker.dispose();
138
+ workers.delete(id);
139
+ return assets.fetch(forwarded);
140
+ }
141
+ let cached = workers.get(id);
142
+ if (cached?.revision !== app.revision) {
143
+ cached?.worker.dispose();
144
+ cached = {
145
+ revision: app.revision,
146
+ worker: load(env, ctx, id, app)
147
+ };
148
+ workers.set(id, cached);
149
+ }
150
+ return await cached.worker.getEntrypoint().fetch(forwarded);
151
+ } catch (error) {
152
+ if (404 === error.status) {
153
+ workers.get(id)?.worker.dispose();
154
+ workers.delete(id);
155
+ return new Response("Not found", {
156
+ status: 404
157
+ });
158
+ }
159
+ console.error(`Flare ${id}:`, error);
160
+ return new Response("App unavailable; inspect flare_get and runtime.log", {
161
+ status: 503
162
+ });
163
+ }
164
+ }
165
+ };