@milesroxas/design-hub 0.12.0 → 0.13.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/README.md +4 -4
- package/core/review/service.test.ts +39 -38
- package/core/review/store.ts +2 -2
- package/core/review/suite-kv.ts +17 -0
- package/dist/core/review/store.js +2 -2
- package/dist/core/review/suite-kv.d.ts +7 -0
- package/dist/core/review/suite-kv.js +12 -0
- package/dist/scripts/client.js +3 -3
- package/dist/scripts/lib/cli.js +5 -0
- package/dist/scripts/lib/fake-host.d.ts +1 -2
- package/dist/scripts/lib/fake-host.js +20 -9
- package/dist/scripts/lib/host.d.ts +13 -25
- package/dist/scripts/lib/host.js +15 -324
- package/dist/scripts/lib/studio-deps.d.ts +16 -0
- package/dist/scripts/lib/studio-deps.js +41 -16
- package/dist/scripts/lib/studios.d.ts +14 -4
- package/dist/scripts/lib/studios.js +23 -5
- package/dist/scripts/lib/vercel-host.d.ts +17 -0
- package/dist/scripts/lib/vercel-host.js +410 -0
- package/dist/scripts/share.js +3 -2
- package/dist/scripts/studio.d.ts +8 -2
- package/dist/scripts/studio.js +38 -14
- package/dist/server/api.d.ts +6 -5
- package/dist/server/api.js +12 -10
- package/dist/server/gate.d.ts +97 -0
- package/dist/server/gate.js +537 -0
- package/dist/server/mark.d.ts +17 -0
- package/dist/server/mark.js +46 -1
- package/dist/server/session.d.ts +2 -1
- package/dist/server/session.js +2 -2
- package/dist/server/stores/backends.d.ts +22 -0
- package/dist/server/stores/backends.js +96 -0
- package/dist/server/{fake-upstash.js → stores/fake-upstash.js} +1 -1
- package/dist/server/stores/index.d.ts +41 -0
- package/dist/server/stores/index.js +63 -0
- package/dist/server/stores/pglite.d.ts +16 -0
- package/dist/server/stores/pglite.js +98 -0
- package/dist/server/stores/postgres.d.ts +63 -0
- package/dist/server/stores/postgres.js +153 -0
- package/dist/server/{upstash.d.ts → stores/upstash.d.ts} +1 -1
- package/dist/vercel/files.js +1 -1
- package/dist/vercel/proxy.d.ts +6 -82
- package/dist/vercel/proxy.js +18 -525
- package/dist/vite/plugin.js +1 -1
- package/package.json +3 -1
- package/skills/miles-deploy/SKILL.md +2 -1
- package/templates/studio/.env.example +3 -0
- package/templates/studio/README.md +13 -0
- package/templates/studio/package.json +1 -1
- /package/dist/server/{fake-upstash.d.ts → stores/fake-upstash.d.ts} +0 -0
- /package/dist/server/{upstash.js → stores/upstash.js} +0 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type TestStore = {
|
|
2
|
+
name: 'upstash' | 'postgres';
|
|
3
|
+
/** The env names that point a site at this store. */
|
|
4
|
+
env: Record<string, string>;
|
|
5
|
+
/** The names of another store of the same kind: another site, the same rows. */
|
|
6
|
+
other: Record<string, string>;
|
|
7
|
+
/** A store of the other kind, which beside this one names two databases. */
|
|
8
|
+
rival: Record<string, string>;
|
|
9
|
+
/** Before each test: an empty store, answering. */
|
|
10
|
+
start(): Promise<void>;
|
|
11
|
+
/** After each test. */
|
|
12
|
+
stop(): void;
|
|
13
|
+
/** Every store call fails until `up`. */
|
|
14
|
+
down(): void;
|
|
15
|
+
up(): void;
|
|
16
|
+
/** From now on, every store call by its Redis name and key (`HGET hub4:…`), in order. */
|
|
17
|
+
watch(): string[];
|
|
18
|
+
};
|
|
19
|
+
/** For a test file that runs a suite on Postgres: call before the suite loads. */
|
|
20
|
+
export declare function onPostgres(): void;
|
|
21
|
+
/** The store the suites of this test file run on. */
|
|
22
|
+
export declare const testStore: () => TestStore;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// The review store a studio site's tests run on, picked once per test file:
|
|
3
|
+
// the fake Upstash (by default) or the embedded Postgres, each reached the
|
|
4
|
+
// way the site reaches it, from the env, through chooseStore. A suite is
|
|
5
|
+
// written once against this and run on each: vercel/gate.postgres.test.ts
|
|
6
|
+
// picks Postgres, then loads the gate suite.
|
|
7
|
+
import { fakeUpstash } from './fake-upstash.js';
|
|
8
|
+
import { postgresThrough } from './index.js';
|
|
9
|
+
import { pgliteQuery } from './pglite.js';
|
|
10
|
+
import { createTable, STATEMENTS, TABLE } from './postgres.js';
|
|
11
|
+
/** The fake Upstash behind the global fetch, as the site's adapter calls it. */
|
|
12
|
+
function upstash() {
|
|
13
|
+
const real = globalThis.fetch;
|
|
14
|
+
let failing = false;
|
|
15
|
+
let seen = null;
|
|
16
|
+
let store = fakeUpstash();
|
|
17
|
+
return {
|
|
18
|
+
name: 'upstash',
|
|
19
|
+
env: { KV_REST_API_URL: 'https://kv.test', KV_REST_API_TOKEN: 't' },
|
|
20
|
+
other: { KV_REST_API_URL: 'https://kv-other.test', KV_REST_API_TOKEN: 't' },
|
|
21
|
+
rival: { DATABASE_URL: 'postgres://studio:pw@db.test/hub' },
|
|
22
|
+
async start() {
|
|
23
|
+
store = fakeUpstash();
|
|
24
|
+
failing = false;
|
|
25
|
+
seen = null;
|
|
26
|
+
globalThis.fetch = ((url, init) => {
|
|
27
|
+
if (failing)
|
|
28
|
+
return Promise.resolve(new Response('{"error":"down"}', { status: 500 }));
|
|
29
|
+
const [cmd, key] = JSON.parse(String(init?.body));
|
|
30
|
+
seen?.push(`${cmd} ${key}`);
|
|
31
|
+
return store(url, init);
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
stop() {
|
|
35
|
+
globalThis.fetch = real;
|
|
36
|
+
},
|
|
37
|
+
down() {
|
|
38
|
+
failing = true;
|
|
39
|
+
},
|
|
40
|
+
up() {
|
|
41
|
+
failing = false;
|
|
42
|
+
},
|
|
43
|
+
watch() {
|
|
44
|
+
seen = [];
|
|
45
|
+
return seen;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** Which op a statement is, by the adapter's own SQL. */
|
|
50
|
+
const OPS = Object.entries(STATEMENTS).map(([op, text]) => [text.replace('$t', TABLE), op.toUpperCase()]);
|
|
51
|
+
/** The embedded Postgres behind every connection string, as the site's adapter queries it. */
|
|
52
|
+
function postgres() {
|
|
53
|
+
let failing = false;
|
|
54
|
+
let seen = null;
|
|
55
|
+
let query;
|
|
56
|
+
return {
|
|
57
|
+
name: 'postgres',
|
|
58
|
+
env: { DATABASE_URL: 'postgres://studio:pw@db.test/hub?sslmode=require' },
|
|
59
|
+
other: { DATABASE_URL: 'postgres://studio:pw@db-other.test/hub?sslmode=require' },
|
|
60
|
+
rival: { KV_REST_API_URL: 'https://kv.test' },
|
|
61
|
+
async start() {
|
|
62
|
+
query ??= await pgliteQuery();
|
|
63
|
+
const db = query;
|
|
64
|
+
failing = false;
|
|
65
|
+
seen = null;
|
|
66
|
+
await createTable(db);
|
|
67
|
+
await db(`TRUNCATE ${TABLE}`, []);
|
|
68
|
+
postgresThrough(() => async (text, params) => {
|
|
69
|
+
if (failing)
|
|
70
|
+
throw new Error('the store is down');
|
|
71
|
+
const op = OPS.find(([sql]) => sql === text)?.[1];
|
|
72
|
+
if (op)
|
|
73
|
+
seen?.push(`${op} ${params[0]}`);
|
|
74
|
+
return db(text, params);
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
stop() { },
|
|
78
|
+
down() {
|
|
79
|
+
failing = true;
|
|
80
|
+
},
|
|
81
|
+
up() {
|
|
82
|
+
failing = false;
|
|
83
|
+
},
|
|
84
|
+
watch() {
|
|
85
|
+
seen = [];
|
|
86
|
+
return seen;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
let picked = 'upstash';
|
|
91
|
+
/** For a test file that runs a suite on Postgres: call before the suite loads. */
|
|
92
|
+
export function onPostgres() {
|
|
93
|
+
picked = 'postgres';
|
|
94
|
+
}
|
|
95
|
+
/** The store the suites of this test file run on. */
|
|
96
|
+
export const testStore = () => (picked === 'postgres' ? postgres() : upstash());
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
// A fetch that answers like Upstash's REST API from memory, for tests that
|
|
3
3
|
// exercise a studio site's code path (its gate and functions) without an account.
|
|
4
|
-
import { memoryKV } from '
|
|
4
|
+
import { memoryKV } from '../../core/review/store.js';
|
|
5
5
|
/** How many keys one SCAN call looks at: few, so a walk takes many calls, some of them finding nothing. */
|
|
6
6
|
const SCAN_PAGE = 2;
|
|
7
7
|
/** A Redis glob as a RegExp: `*`, `?`, `[…]`, and `\` before a character that stands for itself. */
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { KV } from '../../core/review/store.ts';
|
|
2
|
+
import { type Query } from './postgres.ts';
|
|
3
|
+
export type StoreKind = 'upstash' | 'postgres';
|
|
4
|
+
/**
|
|
5
|
+
* The store an env names: its kind, the site its tokens are signed to, how
|
|
6
|
+
* to open it, and how to make what it needs before its first write (the
|
|
7
|
+
* Postgres table), which only `studio create` runs.
|
|
8
|
+
*/
|
|
9
|
+
export type StoreChoice = {
|
|
10
|
+
kind: StoreKind;
|
|
11
|
+
site: string;
|
|
12
|
+
open(): KV;
|
|
13
|
+
prepare(): Promise<void>;
|
|
14
|
+
};
|
|
15
|
+
type Env = Record<string, string | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* How a connection string becomes a Query: the driver, one pool per string
|
|
18
|
+
* per instance, kept for the life of the instance so every request reuses
|
|
19
|
+
* its connections. Tests put an embedded Postgres here (postgresThrough).
|
|
20
|
+
*/
|
|
21
|
+
type Pool = Query & {
|
|
22
|
+
end?(): Promise<void>;
|
|
23
|
+
};
|
|
24
|
+
/** For tests: every connection string opens `to` from here on, until another call. */
|
|
25
|
+
export declare function postgresThrough(to: (url: string) => Pool): void;
|
|
26
|
+
/**
|
|
27
|
+
* Closes every pool this process opened, for a command once it is done: an
|
|
28
|
+
* idle connection would otherwise keep the process alive until it times out.
|
|
29
|
+
*/
|
|
30
|
+
export declare function closeStores(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* The review store the env names, null when it names none, or why none can
|
|
33
|
+
* be opened: a store of each kind, or two Postgres databases. Nothing is
|
|
34
|
+
* connected until `open` is called.
|
|
35
|
+
*/
|
|
36
|
+
export declare function chooseStore(env: Env): StoreChoice | {
|
|
37
|
+
error: string;
|
|
38
|
+
} | null;
|
|
39
|
+
/** The site the env's store gives the gate to sign tokens to; empty when it names none, or two. */
|
|
40
|
+
export declare function storeSite(env: Env): string;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createTable, driverQuery, isPostgresUrl, postgresKV, postgresSite } from './postgres.js';
|
|
2
|
+
import { storeConfig, upstashKV } from './upstash.js';
|
|
3
|
+
/** The env names each kind of store is read from. */
|
|
4
|
+
const STORE_ENV = {
|
|
5
|
+
upstash: ['KV_REST_API_URL', 'KV_REST_API_TOKEN', 'UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'],
|
|
6
|
+
postgres: ['DATABASE_URL', 'POSTGRES_URL'],
|
|
7
|
+
};
|
|
8
|
+
let connect = driverQuery;
|
|
9
|
+
const pools = new Map();
|
|
10
|
+
const pool = (url) => pools.get(url) ?? pools.set(url, connect(url)).get(url);
|
|
11
|
+
/** For tests: every connection string opens `to` from here on, until another call. */
|
|
12
|
+
export function postgresThrough(to) {
|
|
13
|
+
connect = to;
|
|
14
|
+
pools.clear();
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Closes every pool this process opened, for a command once it is done: an
|
|
18
|
+
* idle connection would otherwise keep the process alive until it times out.
|
|
19
|
+
*/
|
|
20
|
+
export async function closeStores() {
|
|
21
|
+
const open = [...pools.values()];
|
|
22
|
+
pools.clear();
|
|
23
|
+
await Promise.all(open.map((p) => p.end?.()));
|
|
24
|
+
}
|
|
25
|
+
/** The Postgres connection string an env names, the names it was read from, or why it is refused. */
|
|
26
|
+
function postgresUrl(env) {
|
|
27
|
+
const [a, b] = STORE_ENV.postgres.map((name) => (isPostgresUrl(env[name]) ? env[name] : undefined));
|
|
28
|
+
if (a && b && postgresSite(a) !== postgresSite(b))
|
|
29
|
+
return { error: 'DATABASE_URL and POSTGRES_URL name two different databases.' };
|
|
30
|
+
const url = a ?? b;
|
|
31
|
+
return url ? { url } : null;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The review store the env names, null when it names none, or why none can
|
|
35
|
+
* be opened: a store of each kind, or two Postgres databases. Nothing is
|
|
36
|
+
* connected until `open` is called.
|
|
37
|
+
*/
|
|
38
|
+
export function chooseStore(env) {
|
|
39
|
+
const upstash = storeConfig(env);
|
|
40
|
+
const pg = postgresUrl(env);
|
|
41
|
+
if (pg && 'error' in pg)
|
|
42
|
+
return pg;
|
|
43
|
+
// An Upstash URL alone, with no token, still names a store: never a reason to take the Postgres one.
|
|
44
|
+
if ((upstash || env.KV_REST_API_URL || env.UPSTASH_REDIS_REST_URL) && pg)
|
|
45
|
+
return {
|
|
46
|
+
error: 'Both an Upstash store (KV_REST_API_URL) and a Postgres one (DATABASE_URL or POSTGRES_URL) are set, and a studio has one database.',
|
|
47
|
+
};
|
|
48
|
+
if (upstash)
|
|
49
|
+
return { kind: 'upstash', site: upstash.url, open: () => upstashKV(upstash), prepare: async () => { } };
|
|
50
|
+
if (pg)
|
|
51
|
+
return {
|
|
52
|
+
kind: 'postgres',
|
|
53
|
+
site: postgresSite(pg.url),
|
|
54
|
+
open: () => postgresKV(pool(pg.url)),
|
|
55
|
+
prepare: () => createTable(pool(pg.url)),
|
|
56
|
+
};
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
/** The site the env's store gives the gate to sign tokens to; empty when it names none, or two. */
|
|
60
|
+
export function storeSite(env) {
|
|
61
|
+
const chosen = chooseStore(env);
|
|
62
|
+
return chosen && 'site' in chosen ? chosen.site : '';
|
|
63
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { KV, Snapshot } from '../../core/review/store.ts';
|
|
2
|
+
import { type Query } from './postgres.ts';
|
|
3
|
+
/** The process's one embedded Postgres, as a Query. */
|
|
4
|
+
export declare function pgliteQuery(): Promise<Query>;
|
|
5
|
+
/**
|
|
6
|
+
* A store made at once and ready on its first call, so a test builds it
|
|
7
|
+
* where it built a memory store. `after` runs after every op, with its name
|
|
8
|
+
* and arguments, before the op answers.
|
|
9
|
+
*/
|
|
10
|
+
export declare function deferredKV(ready: Promise<KV>, after?: (op: keyof KV, args: string[]) => Promise<void>): KV;
|
|
11
|
+
/**
|
|
12
|
+
* The memory store's shape on the embedded Postgres: a store on a new table
|
|
13
|
+
* of its own, holding `initial`, that calls `onChange` with every key after
|
|
14
|
+
* each write, as memoryKV does.
|
|
15
|
+
*/
|
|
16
|
+
export declare function pgliteKV(initial?: Snapshot, onChange?: (s: Snapshot) => void): KV;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// A real Postgres in this process (PGlite, Postgres compiled to WebAssembly),
|
|
3
|
+
// for the tests that run the Postgres adapter's own SQL with no server to
|
|
4
|
+
// install: the conformance suite, the gate's and the service's. Each store
|
|
5
|
+
// it hands out is a table of its own, so no test sees another's rows.
|
|
6
|
+
import { after } from 'node:test';
|
|
7
|
+
import { PGlite } from '@electric-sql/pglite';
|
|
8
|
+
import { createTable, postgresKV } from './postgres.js';
|
|
9
|
+
let db;
|
|
10
|
+
let tables = 0;
|
|
11
|
+
// Closed when the file's tests end, or it holds the process open for seconds after. Registered as
|
|
12
|
+
// the module loads, so on the file's root, never on whichever test happened to open it first.
|
|
13
|
+
after(async () => (await db)?.close());
|
|
14
|
+
/** The process's one embedded Postgres, as a Query. */
|
|
15
|
+
export async function pgliteQuery() {
|
|
16
|
+
db ??= PGlite.create();
|
|
17
|
+
const pg = await db;
|
|
18
|
+
return async (text, params) => {
|
|
19
|
+
const result = await pg.query(text, params);
|
|
20
|
+
return { rows: result.rows, count: result.affectedRows ?? 0 };
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** A new, empty table in the embedded Postgres, made, and its name. */
|
|
24
|
+
async function freshTable(query) {
|
|
25
|
+
const table = `kv_test_${++tables}`;
|
|
26
|
+
await createTable(query, table);
|
|
27
|
+
return table;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Every key, hash or set, as the memory store's Snapshot; a key with members
|
|
31
|
+
* is a set when `sets` names it. As in the memory store, a hash written to
|
|
32
|
+
* and emptied by hdel is still listed, empty, until del or delPrefix.
|
|
33
|
+
*/
|
|
34
|
+
async function snapshotOf(query, table, sets, hashes) {
|
|
35
|
+
const { rows } = await query(`SELECT key, field, value FROM ${table} ORDER BY key, field`, []);
|
|
36
|
+
const out = { hashes: Object.fromEntries([...hashes].map((k) => [k, {}])), sets: {} };
|
|
37
|
+
for (const { key, field, value } of rows) {
|
|
38
|
+
if (sets.has(key))
|
|
39
|
+
out.sets[key] = [...(out.sets[key] ?? []), field];
|
|
40
|
+
else
|
|
41
|
+
out.hashes[key] = { ...out.hashes[key], [field]: value };
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
const WRITES = ['hset', 'hdel', 'hsetnx', 'hincrby', 'sadd', 'del', 'delPrefix'];
|
|
46
|
+
const OPS = Object.keys(postgresKV(async () => ({ rows: [], count: 0 })));
|
|
47
|
+
/**
|
|
48
|
+
* A store made at once and ready on its first call, so a test builds it
|
|
49
|
+
* where it built a memory store. `after` runs after every op, with its name
|
|
50
|
+
* and arguments, before the op answers.
|
|
51
|
+
*/
|
|
52
|
+
export function deferredKV(ready, after) {
|
|
53
|
+
const kv = {};
|
|
54
|
+
for (const op of OPS)
|
|
55
|
+
kv[op] = async (...args) => {
|
|
56
|
+
const out = await (await ready)[op](...args);
|
|
57
|
+
await after?.(op, args);
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
return kv;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The memory store's shape on the embedded Postgres: a store on a new table
|
|
64
|
+
* of its own, holding `initial`, that calls `onChange` with every key after
|
|
65
|
+
* each write, as memoryKV does.
|
|
66
|
+
*/
|
|
67
|
+
export function pgliteKV(initial, onChange) {
|
|
68
|
+
const sets = new Set(Object.keys(initial?.sets ?? {}));
|
|
69
|
+
const hashes = new Set(Object.keys(initial?.hashes ?? {}));
|
|
70
|
+
const made = (async () => {
|
|
71
|
+
const query = await pgliteQuery();
|
|
72
|
+
const table = await freshTable(query);
|
|
73
|
+
const kv = postgresKV(query, table);
|
|
74
|
+
for (const [key, fields] of Object.entries(initial?.hashes ?? {}))
|
|
75
|
+
for (const [field, value] of Object.entries(fields))
|
|
76
|
+
await kv.hset(key, field, value);
|
|
77
|
+
for (const [key, members] of Object.entries(initial?.sets ?? {}))
|
|
78
|
+
for (const member of members)
|
|
79
|
+
await kv.sadd(key, member);
|
|
80
|
+
return { query, table, kv };
|
|
81
|
+
})();
|
|
82
|
+
return deferredKV(made.then((m) => m.kv), async (op, args) => {
|
|
83
|
+
if (op === 'sadd')
|
|
84
|
+
sets.add(args[0]);
|
|
85
|
+
if (op === 'hset' || op === 'hsetnx' || op === 'hincrby')
|
|
86
|
+
hashes.add(args[0]);
|
|
87
|
+
if (op === 'del')
|
|
88
|
+
hashes.delete(args[0]);
|
|
89
|
+
if (op === 'delPrefix')
|
|
90
|
+
for (const k of hashes)
|
|
91
|
+
if (k.startsWith(args[0]))
|
|
92
|
+
hashes.delete(k);
|
|
93
|
+
if (!onChange || !WRITES.includes(op))
|
|
94
|
+
return;
|
|
95
|
+
const { query, table } = await made;
|
|
96
|
+
onChange(await snapshotOf(query, table, sets, hashes));
|
|
97
|
+
});
|
|
98
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { KV } from '../../core/review/store.ts';
|
|
2
|
+
/** One statement with its parameters: the rows it returned and how many it changed. */
|
|
3
|
+
export type Query = (text: string, params: string[]) => Promise<{
|
|
4
|
+
rows: Record<string, string>[];
|
|
5
|
+
count: number;
|
|
6
|
+
}>;
|
|
7
|
+
/** The table a studio's store is, unless a test names its own. */
|
|
8
|
+
export declare const TABLE = "design_hub_kv";
|
|
9
|
+
/** The statements, by op: the adapter's whole SQL, in one place. `$t` is the table. */
|
|
10
|
+
export declare const STATEMENTS: {
|
|
11
|
+
readonly hget: 'SELECT value FROM $t WHERE key = $1 AND field = $2';
|
|
12
|
+
readonly hset: 'INSERT INTO $t (key, field, value) VALUES ($1, $2, $3) ON CONFLICT (key, field) DO UPDATE SET value = EXCLUDED.value';
|
|
13
|
+
readonly hdel: 'DELETE FROM $t WHERE key = $1 AND field = $2';
|
|
14
|
+
readonly hsetnx: 'INSERT INTO $t (key, field, value) VALUES ($1, $2, $3) ON CONFLICT (key, field) DO NOTHING RETURNING 1 AS won';
|
|
15
|
+
readonly hgetall: 'SELECT field, value FROM $t WHERE key = $1';
|
|
16
|
+
readonly hincrby: 'INSERT INTO $t AS t (key, field, value) VALUES ($1, $2, ($3::bigint)::text) ON CONFLICT (key, field) DO UPDATE SET value = (t.value::bigint + $3::bigint)::text RETURNING value';
|
|
17
|
+
readonly sadd: "INSERT INTO $t (key, field, value) VALUES ($1, $2, '') ON CONFLICT (key, field) DO NOTHING";
|
|
18
|
+
readonly smembers: 'SELECT field FROM $t WHERE key = $1';
|
|
19
|
+
readonly del: 'DELETE FROM $t WHERE key = $1';
|
|
20
|
+
readonly delPrefix: "DELETE FROM $t WHERE key LIKE $1 ESCAPE '\\'";
|
|
21
|
+
};
|
|
22
|
+
/** The prefix as a LIKE pattern that matches only keys starting with its own text: `\`, `%` and `_` stand for themselves. */
|
|
23
|
+
export declare const likePrefix: (prefix: string) => string;
|
|
24
|
+
/**
|
|
25
|
+
* Makes the table when it is not there, and closes it to every role but its
|
|
26
|
+
* owner: row level security on, with no policy. The owner, the role the
|
|
27
|
+
* adapter connects as, is not subject to it; any other role reads and writes
|
|
28
|
+
* nothing, whatever it was granted. That matters on Supabase, whose default
|
|
29
|
+
* grants give every new table in `public` to `anon` and serve it over the
|
|
30
|
+
* project's Data API to anyone with its anon key. Both steps hold for a table
|
|
31
|
+
* already there, so `studio deploy` closes one made before. Run by `studio
|
|
32
|
+
* create` and `studio deploy`, the setup path, never by a visitor's request:
|
|
33
|
+
* the gate and the functions only read and write rows.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createTable(query: Query, table?: string): Promise<void>;
|
|
36
|
+
export declare function postgresKV(query: Query, table?: string): KV;
|
|
37
|
+
export declare const isPostgresUrl: (url: string | undefined) => url is string;
|
|
38
|
+
/**
|
|
39
|
+
* Which database a connection string names, with no credential in it:
|
|
40
|
+
* `postgres://<host>:<port>/<database>`. The gate signs it into every token
|
|
41
|
+
* (server/session.ts), as it does Upstash's URL, so two studios with one
|
|
42
|
+
* GATE_SECRET never take each other's cookies.
|
|
43
|
+
*/
|
|
44
|
+
export declare function postgresSite(url: string): string;
|
|
45
|
+
/**
|
|
46
|
+
* TLS for a connection: always for a host other than this machine, whatever
|
|
47
|
+
* the string says, verified against the system's authorities when its
|
|
48
|
+
* `sslmode` is verify-full or verify-ca, and otherwise encrypted unverified,
|
|
49
|
+
* as libpq does for `sslmode=require` (what Neon's and Supabase's strings
|
|
50
|
+
* say). This machine's own server is plain unless the string asks for TLS.
|
|
51
|
+
*/
|
|
52
|
+
export declare function tlsFor(url: string): false | 'require' | 'verify-full';
|
|
53
|
+
/**
|
|
54
|
+
* A Query on the driver (postgres.js) for one connection string. The string's
|
|
55
|
+
* query parameters are dropped (the driver would send `channel_binding` and
|
|
56
|
+
* the like to the server as settings) and TLS set by tlsFor. Unnamed
|
|
57
|
+
* statements only (`prepare: false`), so a transaction-mode pooler can run
|
|
58
|
+
* each on any server connection; no type lookup on connect; no notices
|
|
59
|
+
* printed, since a command's stdout is its one JSON object.
|
|
60
|
+
*/
|
|
61
|
+
export declare function driverQuery(url: string): Query & {
|
|
62
|
+
end(): Promise<void>;
|
|
63
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// The review store on Postgres: any Postgres by its connection string (Neon,
|
|
3
|
+
// Supabase, a server of your own), in one table `(key, field, value)`, the
|
|
4
|
+
// `KV` port's Redis shape kept as it is (core/review/store.ts). A hash is
|
|
5
|
+
// its key's rows; a set is its key's rows with each member a field and an
|
|
6
|
+
// empty value. No key is ever both (the service never mixes them).
|
|
7
|
+
//
|
|
8
|
+
// Every op is one statement, so each that is atomic on Upstash is atomic
|
|
9
|
+
// here with no transaction and no lock held between statements: `hdel` is a
|
|
10
|
+
// DELETE that answers its row count, `hsetnx` an INSERT … ON CONFLICT DO
|
|
11
|
+
// NOTHING that answers whether it inserted, `hincrby` an INSERT … ON
|
|
12
|
+
// CONFLICT DO UPDATE that adds to the stored value and answers the sum. A
|
|
13
|
+
// statement holds no session state and no named prepared statement, so it
|
|
14
|
+
// runs through a transaction-mode pooler (Neon's and Supabase's pooled URLs).
|
|
15
|
+
//
|
|
16
|
+
// The adapter runs its SQL through a Query, so the conformance suite runs
|
|
17
|
+
// the same statements on an embedded Postgres (server/stores/pglite.ts) and,
|
|
18
|
+
// with DESIGN_HUB_TEST_POSTGRES, on a real server through the driver.
|
|
19
|
+
import postgres from 'postgres';
|
|
20
|
+
/** The table a studio's store is, unless a test names its own. */
|
|
21
|
+
export const TABLE = 'design_hub_kv';
|
|
22
|
+
const IDENT = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
23
|
+
function tableName(table) {
|
|
24
|
+
if (!IDENT.test(table))
|
|
25
|
+
throw new Error(`Not a table name: ${JSON.stringify(table)}.`);
|
|
26
|
+
return table;
|
|
27
|
+
}
|
|
28
|
+
/** The statements, by op: the adapter's whole SQL, in one place. `$t` is the table. */
|
|
29
|
+
export const STATEMENTS = {
|
|
30
|
+
hget: 'SELECT value FROM $t WHERE key = $1 AND field = $2',
|
|
31
|
+
hset: 'INSERT INTO $t (key, field, value) VALUES ($1, $2, $3) ON CONFLICT (key, field) DO UPDATE SET value = EXCLUDED.value',
|
|
32
|
+
hdel: 'DELETE FROM $t WHERE key = $1 AND field = $2',
|
|
33
|
+
hsetnx: 'INSERT INTO $t (key, field, value) VALUES ($1, $2, $3) ON CONFLICT (key, field) DO NOTHING RETURNING 1 AS won',
|
|
34
|
+
hgetall: 'SELECT field, value FROM $t WHERE key = $1',
|
|
35
|
+
// The row is locked by the conflict and the add made on its value as it is then, so two at once both add.
|
|
36
|
+
hincrby: 'INSERT INTO $t AS t (key, field, value) VALUES ($1, $2, ($3::bigint)::text) ON CONFLICT (key, field) DO UPDATE SET value = (t.value::bigint + $3::bigint)::text RETURNING value',
|
|
37
|
+
sadd: "INSERT INTO $t (key, field, value) VALUES ($1, $2, '') ON CONFLICT (key, field) DO NOTHING",
|
|
38
|
+
smembers: 'SELECT field FROM $t WHERE key = $1',
|
|
39
|
+
del: 'DELETE FROM $t WHERE key = $1',
|
|
40
|
+
delPrefix: "DELETE FROM $t WHERE key LIKE $1 ESCAPE '\\'",
|
|
41
|
+
};
|
|
42
|
+
/** The prefix as a LIKE pattern that matches only keys starting with its own text: `\`, `%` and `_` stand for themselves. */
|
|
43
|
+
export const likePrefix = (prefix) => `${prefix.replace(/[\\%_]/g, '\\$&')}%`;
|
|
44
|
+
/**
|
|
45
|
+
* Makes the table when it is not there, and closes it to every role but its
|
|
46
|
+
* owner: row level security on, with no policy. The owner, the role the
|
|
47
|
+
* adapter connects as, is not subject to it; any other role reads and writes
|
|
48
|
+
* nothing, whatever it was granted. That matters on Supabase, whose default
|
|
49
|
+
* grants give every new table in `public` to `anon` and serve it over the
|
|
50
|
+
* project's Data API to anyone with its anon key. Both steps hold for a table
|
|
51
|
+
* already there, so `studio deploy` closes one made before. Run by `studio
|
|
52
|
+
* create` and `studio deploy`, the setup path, never by a visitor's request:
|
|
53
|
+
* the gate and the functions only read and write rows.
|
|
54
|
+
*/
|
|
55
|
+
export async function createTable(query, table = TABLE) {
|
|
56
|
+
const t = tableName(table);
|
|
57
|
+
await query(`CREATE TABLE IF NOT EXISTS ${t} (key text NOT NULL, field text NOT NULL, value text NOT NULL, PRIMARY KEY (key, field))`, []);
|
|
58
|
+
await query(`ALTER TABLE ${t} ENABLE ROW LEVEL SECURITY`, []);
|
|
59
|
+
}
|
|
60
|
+
export function postgresKV(query, table = TABLE) {
|
|
61
|
+
const t = tableName(table);
|
|
62
|
+
const run = (op, params) => query(STATEMENTS[op].replace('$t', t), params);
|
|
63
|
+
return {
|
|
64
|
+
hget: async (key, field) => (await run('hget', [key, field])).rows[0]?.value ?? null,
|
|
65
|
+
hset: async (key, field, value) => {
|
|
66
|
+
await run('hset', [key, field, value]);
|
|
67
|
+
},
|
|
68
|
+
hdel: async (key, field) => (await run('hdel', [key, field])).count,
|
|
69
|
+
hsetnx: async (key, field, value) => (await run('hsetnx', [key, field, value])).rows.length === 1,
|
|
70
|
+
hgetall: async (key) => Object.fromEntries((await run('hgetall', [key])).rows.map((r) => [r.field, r.value])),
|
|
71
|
+
hincrby: async (key, field, by) => Number((await run('hincrby', [key, field, String(by)])).rows[0].value),
|
|
72
|
+
sadd: async (key, member) => {
|
|
73
|
+
await run('sadd', [key, member]);
|
|
74
|
+
},
|
|
75
|
+
smembers: async (key) => (await run('smembers', [key])).rows.map((r) => r.field),
|
|
76
|
+
del: async (key) => {
|
|
77
|
+
await run('del', [key]);
|
|
78
|
+
},
|
|
79
|
+
delPrefix: async (prefix) => {
|
|
80
|
+
await run('delPrefix', [likePrefix(prefix)]);
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** A connection string's parts: postgres:// or postgresql://, else null. */
|
|
85
|
+
function parse(url) {
|
|
86
|
+
try {
|
|
87
|
+
const parsed = new URL(url);
|
|
88
|
+
return /^postgres(ql)?:$/.test(parsed.protocol) && parsed.hostname ? parsed : null;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export const isPostgresUrl = (url) => !!url && parse(url) !== null;
|
|
95
|
+
const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
96
|
+
/**
|
|
97
|
+
* Which database a connection string names, with no credential in it:
|
|
98
|
+
* `postgres://<host>:<port>/<database>`. The gate signs it into every token
|
|
99
|
+
* (server/session.ts), as it does Upstash's URL, so two studios with one
|
|
100
|
+
* GATE_SECRET never take each other's cookies.
|
|
101
|
+
*/
|
|
102
|
+
export function postgresSite(url) {
|
|
103
|
+
const u = parse(url);
|
|
104
|
+
if (!u)
|
|
105
|
+
return '';
|
|
106
|
+
const database = decodeURIComponent(u.pathname.slice(1)) || decodeURIComponent(u.username);
|
|
107
|
+
return `postgres://${u.hostname.toLowerCase()}:${u.port || '5432'}/${database}`;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* TLS for a connection: always for a host other than this machine, whatever
|
|
111
|
+
* the string says, verified against the system's authorities when its
|
|
112
|
+
* `sslmode` is verify-full or verify-ca, and otherwise encrypted unverified,
|
|
113
|
+
* as libpq does for `sslmode=require` (what Neon's and Supabase's strings
|
|
114
|
+
* say). This machine's own server is plain unless the string asks for TLS.
|
|
115
|
+
*/
|
|
116
|
+
export function tlsFor(url) {
|
|
117
|
+
const u = parse(url);
|
|
118
|
+
const mode = u?.searchParams.get('sslmode') ?? '';
|
|
119
|
+
if (mode === 'verify-full' || mode === 'verify-ca')
|
|
120
|
+
return 'verify-full';
|
|
121
|
+
if (u && LOCAL.has(u.hostname))
|
|
122
|
+
return mode === 'require' ? 'require' : false;
|
|
123
|
+
return 'require';
|
|
124
|
+
}
|
|
125
|
+
/** At most this many connections per instance, reused across requests. */
|
|
126
|
+
const POOL = 3;
|
|
127
|
+
/**
|
|
128
|
+
* A Query on the driver (postgres.js) for one connection string. The string's
|
|
129
|
+
* query parameters are dropped (the driver would send `channel_binding` and
|
|
130
|
+
* the like to the server as settings) and TLS set by tlsFor. Unnamed
|
|
131
|
+
* statements only (`prepare: false`), so a transaction-mode pooler can run
|
|
132
|
+
* each on any server connection; no type lookup on connect; no notices
|
|
133
|
+
* printed, since a command's stdout is its one JSON object.
|
|
134
|
+
*/
|
|
135
|
+
export function driverQuery(url) {
|
|
136
|
+
const u = parse(url);
|
|
137
|
+
if (!u)
|
|
138
|
+
throw new Error('Not a Postgres connection string.');
|
|
139
|
+
const sql = postgres(`${u.protocol}//${u.username}${u.password ? `:${u.password}` : ''}@${u.host}${u.pathname}`, {
|
|
140
|
+
ssl: tlsFor(url),
|
|
141
|
+
max: POOL,
|
|
142
|
+
idle_timeout: 20,
|
|
143
|
+
connect_timeout: 10,
|
|
144
|
+
prepare: false,
|
|
145
|
+
fetch_types: false,
|
|
146
|
+
onnotice: () => { },
|
|
147
|
+
});
|
|
148
|
+
const query = async (text, params) => {
|
|
149
|
+
const result = await sql.unsafe(text, params);
|
|
150
|
+
return { rows: [...result], count: result.count ?? 0 };
|
|
151
|
+
};
|
|
152
|
+
return Object.assign(query, { end: () => sql.end() });
|
|
153
|
+
}
|
package/dist/vercel/files.js
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
// `private, no-store` with no ETag, so every view reads it fresh.
|
|
8
8
|
import { filePath } from '../core/files.js';
|
|
9
9
|
import { blobFiles } from '../server/blob.js';
|
|
10
|
+
import { admit, DEFAULT_SITE_NAME, findPlace, isRead, notFound, plain, refuse, storeDown, } from '../server/gate.js';
|
|
10
11
|
import { hostCache } from '../server/hosts.js';
|
|
11
|
-
import { admit, DEFAULT_SITE_NAME, findPlace, isRead, notFound, plain, refuse, storeDown, } from './proxy.js';
|
|
12
12
|
/** A path's last segment names a file (`app.js`) rather than a page of the hub (`guide`, a prototype). */
|
|
13
13
|
const isFileName = (file) => (file.at(-1) ?? '').includes('.');
|
|
14
14
|
/**
|