@supacloud/lite 0.2.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/CHANGELOG.md +29 -0
- package/LICENSE +201 -0
- package/LICENSES/PGLITE-APACHE-2.0.txt +176 -0
- package/LICENSES/TINBASE-MIT.txt +21 -0
- package/README.md +170 -0
- package/RELEASING.md +22 -0
- package/THIRD_PARTY_NOTICES.md +24 -0
- package/dist/cli.js +9018 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8469 -0
- package/dist/project-runtime.d.ts +65 -0
- package/dist/project-runtime.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/handler.d.ts +140 -0
- package/dist/vendor/tinbase/auth/handler.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/inbox.d.ts +34 -0
- package/dist/vendor/tinbase/auth/inbox.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/oauth.d.ts +88 -0
- package/dist/vendor/tinbase/auth/oauth.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/password.d.ts +9 -0
- package/dist/vendor/tinbase/auth/password.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/qr.d.ts +9 -0
- package/dist/vendor/tinbase/auth/qr.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/rate-limit.d.ts +34 -0
- package/dist/vendor/tinbase/auth/rate-limit.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/redirect.d.ts +21 -0
- package/dist/vendor/tinbase/auth/redirect.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/settings.d.ts +56 -0
- package/dist/vendor/tinbase/auth/settings.d.ts.map +1 -0
- package/dist/vendor/tinbase/auth/totp.d.ts +20 -0
- package/dist/vendor/tinbase/auth/totp.d.ts.map +1 -0
- package/dist/vendor/tinbase/cron/service.d.ts +47 -0
- package/dist/vendor/tinbase/cron/service.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/bootstrap.d.ts +21 -0
- package/dist/vendor/tinbase/db/bootstrap.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/database.d.ts +168 -0
- package/dist/vendor/tinbase/db/database.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/emulated.d.ts +53 -0
- package/dist/vendor/tinbase/db/emulated.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/engine.d.ts +47 -0
- package/dist/vendor/tinbase/db/engine.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/inspect.d.ts +19 -0
- package/dist/vendor/tinbase/db/inspect.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/pglite-engine.d.ts +9 -0
- package/dist/vendor/tinbase/db/pglite-engine.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/schema-diff.d.ts +32 -0
- package/dist/vendor/tinbase/db/schema-diff.d.ts.map +1 -0
- package/dist/vendor/tinbase/db/sql-compat.d.ts +33 -0
- package/dist/vendor/tinbase/db/sql-compat.d.ts.map +1 -0
- package/dist/vendor/tinbase/functions/deno-shim.d.ts +15 -0
- package/dist/vendor/tinbase/functions/deno-shim.d.ts.map +1 -0
- package/dist/vendor/tinbase/functions/handler.d.ts +36 -0
- package/dist/vendor/tinbase/functions/handler.d.ts.map +1 -0
- package/dist/vendor/tinbase/gen-types.d.ts +23 -0
- package/dist/vendor/tinbase/gen-types.d.ts.map +1 -0
- package/dist/vendor/tinbase/index.d.ts +82 -0
- package/dist/vendor/tinbase/index.d.ts.map +1 -0
- package/dist/vendor/tinbase/jwt.d.ts +31 -0
- package/dist/vendor/tinbase/jwt.d.ts.map +1 -0
- package/dist/vendor/tinbase/log-buffer.d.ts +28 -0
- package/dist/vendor/tinbase/log-buffer.d.ts.map +1 -0
- package/dist/vendor/tinbase/net/service.d.ts +72 -0
- package/dist/vendor/tinbase/net/service.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/bun-server.d.ts +23 -0
- package/dist/vendor/tinbase/node/bun-server.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/bundle-function.d.ts +8 -0
- package/dist/vendor/tinbase/node/bundle-function.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/config-toml.d.ts +34 -0
- package/dist/vendor/tinbase/node/config-toml.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/fs-driver.d.ts +27 -0
- package/dist/vendor/tinbase/node/fs-driver.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/load-config.d.ts +82 -0
- package/dist/vendor/tinbase/node/load-config.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/load-functions.d.ts +24 -0
- package/dist/vendor/tinbase/node/load-functions.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/project.d.ts +21 -0
- package/dist/vendor/tinbase/node/project.d.ts.map +1 -0
- package/dist/vendor/tinbase/node/server-shared.d.ts +10 -0
- package/dist/vendor/tinbase/node/server-shared.d.ts.map +1 -0
- package/dist/vendor/tinbase/realtime/engine.d.ts +82 -0
- package/dist/vendor/tinbase/realtime/engine.d.ts.map +1 -0
- package/dist/vendor/tinbase/rest/build.d.ts +101 -0
- package/dist/vendor/tinbase/rest/build.d.ts.map +1 -0
- package/dist/vendor/tinbase/rest/errors.d.ts +11 -0
- package/dist/vendor/tinbase/rest/errors.d.ts.map +1 -0
- package/dist/vendor/tinbase/rest/handler.d.ts +28 -0
- package/dist/vendor/tinbase/rest/handler.d.ts.map +1 -0
- package/dist/vendor/tinbase/rest/parse.d.ts +95 -0
- package/dist/vendor/tinbase/rest/parse.d.ts.map +1 -0
- package/dist/vendor/tinbase/retention/service.d.ts +41 -0
- package/dist/vendor/tinbase/retention/service.d.ts.map +1 -0
- package/dist/vendor/tinbase/security.d.ts +23 -0
- package/dist/vendor/tinbase/security.d.ts.map +1 -0
- package/dist/vendor/tinbase/storage/driver.d.ts +17 -0
- package/dist/vendor/tinbase/storage/driver.d.ts.map +1 -0
- package/dist/vendor/tinbase/storage/handler.d.ts +76 -0
- package/dist/vendor/tinbase/storage/handler.d.ts.map +1 -0
- package/dist/vendor/tinbase/storage/image-transform.d.ts +38 -0
- package/dist/vendor/tinbase/storage/image-transform.d.ts.map +1 -0
- package/dist/vendor/tinbase/storage/s3-driver.d.ts +36 -0
- package/dist/vendor/tinbase/storage/s3-driver.d.ts.map +1 -0
- package/dist/vendor/tinbase/types.d.ts +171 -0
- package/dist/vendor/tinbase/types.d.ts.map +1 -0
- package/dist/vendor/tinbase/webhooks/service.d.ts +71 -0
- package/dist/vendor/tinbase/webhooks/service.d.ts.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Idempotent bootstrap SQL that shapes a fresh database like a Supabase
|
|
3
|
+
* project. Two variants: the full {@link BOOTSTRAP_SQL} for the real engines,
|
|
4
|
+
* and the reduced {@link MINIMAL_BOOTSTRAP_SQL} below for the pg-mem subset.
|
|
5
|
+
* Both are safe to re-run (create ... if not exists / create or replace).
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Reduced bootstrap for subset engines (pg-mem) that can't run plpgsql, RLS
|
|
9
|
+
* policies, extensions, or LISTEN/NOTIFY. Just the schemas, core tables, and
|
|
10
|
+
* SQL-language auth helpers needed for the REST + auth CRUD surface. No RLS is
|
|
11
|
+
* enforced here - this path is for local-dev/preview only.
|
|
12
|
+
*/
|
|
13
|
+
export declare const MINIMAL_BOOTSTRAP_SQL = "\ncreate schema if not exists auth;\ncreate schema if not exists storage;\ncreate schema if not exists supabase_migrations;\n\ncreate table if not exists auth.users (\n id uuid primary key default gen_random_uuid(),\n aud text default 'authenticated',\n role text default 'authenticated',\n email text unique,\n encrypted_password text,\n email_confirmed_at timestamptz,\n last_sign_in_at timestamptz,\n raw_app_meta_data jsonb default '{}'::jsonb,\n raw_user_meta_data jsonb default '{}'::jsonb,\n is_super_admin boolean default false,\n created_at timestamptz default now(),\n updated_at timestamptz default now(),\n phone text unique,\n phone_confirmed_at timestamptz,\n banned_until timestamptz,\n deleted_at timestamptz,\n is_anonymous boolean default false\n);\n\ncreate table if not exists auth.refresh_tokens (\n id bigserial primary key,\n token text unique not null,\n user_id uuid not null,\n parent text,\n session_id uuid,\n revoked boolean default false,\n created_at timestamptz default now(),\n updated_at timestamptz default now()\n);\n\ncreate table if not exists auth.one_time_tokens (\n id uuid primary key default gen_random_uuid(),\n user_id uuid,\n email text not null,\n token_type text not null,\n token text not null,\n attempts int not null default 0,\n created_at timestamptz default now(),\n expires_at timestamptz not null\n);\n\ncreate table if not exists auth.identities (\n id uuid primary key default gen_random_uuid(),\n user_id uuid not null,\n provider text not null,\n provider_id text not null,\n identity_data jsonb default '{}'::jsonb,\n last_sign_in_at timestamptz default now(),\n created_at timestamptz default now(),\n updated_at timestamptz default now(),\n unique (provider, provider_id)\n);\n\ncreate table if not exists auth.flow_state (\n id uuid primary key default gen_random_uuid(),\n provider text not null,\n provider_state text not null unique,\n redirect_to text,\n code_challenge text,\n code_challenge_method text,\n auth_code text unique,\n user_id uuid,\n created_at timestamptz default now(),\n expires_at timestamptz not null\n);\n\ncreate table if not exists auth.mfa_factors (\n id uuid primary key default gen_random_uuid(),\n user_id uuid not null,\n friendly_name text,\n factor_type text not null default 'totp',\n status text not null default 'unverified',\n secret text,\n created_at timestamptz default now(),\n updated_at timestamptz default now()\n);\n\ncreate table if not exists auth.mfa_challenges (\n id uuid primary key default gen_random_uuid(),\n factor_id uuid not null,\n verified_at timestamptz,\n created_at timestamptz default now(),\n expires_at timestamptz not null\n);\n\ncreate table if not exists auth.audit_log_entries (\n id uuid primary key default gen_random_uuid(),\n payload jsonb,\n created_at timestamptz default now(),\n ip_address varchar(64) not null default ''\n);\n\n-- runtime-mutable instance settings (Studio auth toggles)\ncreate table if not exists auth.config (\n key text primary key,\n value jsonb not null,\n updated_at timestamptz default now()\n);\n\ncreate table if not exists storage.buckets (\n id text primary key,\n name text not null unique,\n owner uuid,\n public boolean default false,\n file_size_limit bigint,\n allowed_mime_types text[],\n created_at timestamptz default now(),\n updated_at timestamptz default now()\n);\n\ncreate table if not exists storage.objects (\n id uuid primary key default gen_random_uuid(),\n bucket_id text not null,\n name text not null,\n owner uuid,\n version text,\n metadata jsonb default '{}'::jsonb,\n created_at timestamptz default now(),\n updated_at timestamptz default now(),\n last_accessed_at timestamptz default now(),\n unique (bucket_id, name)\n);\n\ncreate table if not exists supabase_migrations.schema_migrations (\n version text primary key,\n name text,\n statements text[],\n applied_at timestamptz default now()\n);\n\ncreate table if not exists supabase_migrations.seed_files (\n path text primary key,\n hash text,\n applied_at timestamptz default now()\n);\n";
|
|
14
|
+
/**
|
|
15
|
+
* Full bootstrap for the real engines (PGlite / native embedded Postgres):
|
|
16
|
+
* extensions, the anon/authenticated/service_role roles, GoTrue-compatible auth
|
|
17
|
+
* schema, storage schema with default RLS policies, migration bookkeeping, and
|
|
18
|
+
* the realtime CDC + broadcast plumbing.
|
|
19
|
+
*/
|
|
20
|
+
export declare const BOOTSTRAP_SQL = "\n-- \u2500\u2500 Extensions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- Supabase enables these by default and migrations lean on them\n-- (uuid_generate_v4(), crypt(), citext, pg_trgm, \u2026). Each is created into the\n-- 'extensions' schema like hosted Supabase; any not available in this engine\n-- build is skipped rather than aborting the whole bootstrap.\ncreate schema if not exists extensions;\ndo $$\ndeclare ext text;\nbegin\n foreach ext in array array['uuid-ossp','pgcrypto','citext','pg_trgm','ltree','hstore','fuzzystrmatch'] loop\n begin\n execute format('create extension if not exists %I with schema extensions', ext);\n exception when others then\n -- extension not bundled in this engine build; continue\n end;\n end loop;\nend $$;\n\n-- uuid-ossp isn't in every Postgres build (it needs an external UUID lib at\n-- build time - e.g. the theseus Linux binaries omit it). uuid_generate_v4() is\n-- the single most-used function from it, so shim it onto core gen_random_uuid()\n-- (also a v4 UUID) whenever the real extension isn't present, so migrations\n-- that call it work identically on every engine and platform.\ndo $$\nbegin\n if not exists (\n select 1 from pg_proc p join pg_namespace n on n.oid = p.pronamespace\n where p.proname = 'uuid_generate_v4' and n.nspname in ('public', 'extensions')\n ) then\n create function extensions.uuid_generate_v4() returns uuid\n language sql volatile as 'select gen_random_uuid()';\n end if;\nend $$;\n\n-- Make extension functions resolvable unqualified (uuid_generate_v4(), \u2026) on\n-- the current session (migrations run here) and for future connections.\ndo $$\nbegin\n execute 'alter database ' || quote_ident(current_database()) ||\n ' set search_path to \"$user\", public, extensions';\nexception when others then\n -- some engines disallow altering the current database; session SET below still applies\nend $$;\nset search_path to \"$user\", public, extensions;\n\n-- \u2500\u2500 Roles \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\ndo $$\nbegin\n if not exists (select from pg_roles where rolname = 'anon') then\n create role anon nologin noinherit;\n end if;\n if not exists (select from pg_roles where rolname = 'authenticated') then\n create role authenticated nologin noinherit;\n end if;\n if not exists (select from pg_roles where rolname = 'service_role') then\n create role service_role nologin noinherit bypassrls;\n end if;\nend $$;\n\ngrant usage on schema extensions to anon, authenticated, service_role;\nalter role anon set search_path to \"$user\", public, extensions;\nalter role authenticated set search_path to \"$user\", public, extensions;\nalter role service_role set search_path to \"$user\", public, extensions;\n\ngrant usage on schema public to anon, authenticated, service_role;\ngrant all on all tables in schema public to anon, authenticated, service_role;\ngrant all on all sequences in schema public to anon, authenticated, service_role;\ngrant execute on all functions in schema public to anon, authenticated, service_role;\n\nalter default privileges in schema public\n grant all on tables to anon, authenticated, service_role;\nalter default privileges in schema public\n grant all on sequences to anon, authenticated, service_role;\nalter default privileges in schema public\n grant execute on functions to anon, authenticated, service_role;\n\n-- \u2500\u2500 Auth schema (GoTrue-compatible subset) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\ncreate schema if not exists auth;\n\ncreate table if not exists auth.users (\n instance_id uuid default '00000000-0000-0000-0000-000000000000',\n id uuid primary key default gen_random_uuid(),\n aud text default 'authenticated',\n role text default 'authenticated',\n email text unique,\n encrypted_password text,\n email_confirmed_at timestamptz,\n invited_at timestamptz,\n confirmation_token text default '',\n confirmation_sent_at timestamptz,\n recovery_token text default '',\n recovery_sent_at timestamptz,\n email_change_token_new text default '',\n email_change text default '',\n email_change_sent_at timestamptz,\n email_change_token_current text default '',\n email_change_confirm_status smallint default 0,\n last_sign_in_at timestamptz,\n raw_app_meta_data jsonb default '{}'::jsonb,\n raw_user_meta_data jsonb default '{}'::jsonb,\n is_super_admin boolean default false,\n created_at timestamptz default now(),\n updated_at timestamptz default now(),\n phone text unique,\n phone_confirmed_at timestamptz,\n phone_change text default '',\n phone_change_token text default '',\n phone_change_sent_at timestamptz,\n reauthentication_token text default '',\n reauthentication_sent_at timestamptz,\n banned_until timestamptz,\n deleted_at timestamptz,\n is_anonymous boolean default false\n);\n\ncreate table if not exists auth.refresh_tokens (\n id bigint generated by default as identity primary key,\n token text unique not null,\n user_id uuid not null references auth.users(id) on delete cascade,\n parent text,\n session_id uuid,\n revoked boolean default false,\n created_at timestamptz default now(),\n updated_at timestamptz default now()\n);\n\ncreate index if not exists refresh_tokens_user_id_idx on auth.refresh_tokens(user_id);\n\ncreate table if not exists auth.one_time_tokens (\n id uuid primary key default gen_random_uuid(),\n user_id uuid references auth.users(id) on delete cascade,\n email text not null,\n token_type text not null, -- otp | magiclink | recovery\n token text not null,\n attempts int not null default 0,\n created_at timestamptz default now(),\n expires_at timestamptz not null\n);\n\ncreate table if not exists auth.identities (\n id uuid primary key default gen_random_uuid(),\n user_id uuid not null references auth.users(id) on delete cascade,\n provider text not null,\n provider_id text not null,\n identity_data jsonb default '{}'::jsonb,\n last_sign_in_at timestamptz default now(),\n created_at timestamptz default now(),\n updated_at timestamptz default now(),\n unique (provider, provider_id)\n);\n\n-- OAuth / PKCE flow state, bridging /authorize \u2192 provider \u2192 /callback \u2192 exchange\ncreate table if not exists auth.flow_state (\n id uuid primary key default gen_random_uuid(),\n provider text not null,\n provider_state text not null unique,\n redirect_to text,\n code_challenge text,\n code_challenge_method text,\n auth_code text unique,\n user_id uuid references auth.users(id) on delete cascade,\n created_at timestamptz default now(),\n expires_at timestamptz not null\n);\n\ncreate table if not exists auth.mfa_factors (\n id uuid primary key default gen_random_uuid(),\n user_id uuid not null references auth.users(id) on delete cascade,\n friendly_name text,\n factor_type text not null default 'totp',\n status text not null default 'unverified', -- unverified | verified\n secret text,\n created_at timestamptz default now(),\n updated_at timestamptz default now()\n);\n\ncreate table if not exists auth.mfa_challenges (\n id uuid primary key default gen_random_uuid(),\n factor_id uuid not null references auth.mfa_factors(id) on delete cascade,\n verified_at timestamptz,\n created_at timestamptz default now(),\n expires_at timestamptz not null\n);\n\n-- append-only security audit trail (GoTrue-compatible shape)\ncreate table if not exists auth.audit_log_entries (\n instance_id uuid default '00000000-0000-0000-0000-000000000000',\n id uuid primary key default gen_random_uuid(),\n payload jsonb,\n created_at timestamptz default now(),\n ip_address varchar(64) not null default ''\n);\ncreate index if not exists audit_logs_instance_id_idx on auth.audit_log_entries(created_at);\n\n-- runtime-mutable instance settings (Studio auth toggles)\ncreate table if not exists auth.config (\n key text primary key,\n value jsonb not null,\n updated_at timestamptz default now()\n);\n\ngrant usage on schema auth to anon, authenticated, service_role;\n\ncreate or replace function auth.jwt() returns jsonb\nlanguage sql stable as $$\n select coalesce(\n nullif(current_setting('request.jwt.claims', true), ''),\n '{}'\n )::jsonb\n$$;\n\ncreate or replace function auth.uid() returns uuid\nlanguage sql stable as $$\n select nullif(auth.jwt() ->> 'sub', '')::uuid\n$$;\n\ncreate or replace function auth.role() returns text\nlanguage sql stable as $$\n select coalesce(auth.jwt() ->> 'role', 'anon')\n$$;\n\ncreate or replace function auth.email() returns text\nlanguage sql stable as $$\n select auth.jwt() ->> 'email'\n$$;\n\ngrant execute on function auth.jwt(), auth.uid(), auth.role(), auth.email()\n to anon, authenticated, service_role;\n\n-- \u2500\u2500 Storage schema (storage-api-compatible subset) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\ncreate schema if not exists storage;\n\ncreate table if not exists storage.buckets (\n id text primary key,\n name text not null unique,\n owner uuid,\n public boolean default false,\n file_size_limit bigint,\n allowed_mime_types text[],\n created_at timestamptz default now(),\n updated_at timestamptz default now()\n);\n\ncreate table if not exists storage.objects (\n id uuid primary key default gen_random_uuid(),\n bucket_id text not null references storage.buckets(id),\n name text not null,\n owner uuid,\n version text,\n metadata jsonb default '{}'::jsonb,\n created_at timestamptz default now(),\n updated_at timestamptz default now(),\n last_accessed_at timestamptz default now(),\n unique (bucket_id, name)\n);\n\ncreate index if not exists objects_bucket_name_idx on storage.objects(bucket_id, name);\n\ngrant usage on schema storage to anon, authenticated, service_role;\ngrant select on storage.buckets to anon, authenticated, service_role;\ngrant all on storage.buckets to service_role;\ngrant all on storage.objects to anon, authenticated, service_role;\n\ncreate or replace function storage.foldername(name text) returns text[]\nlanguage sql immutable as $$\n select (string_to_array(name, '/'))[1 : array_length(string_to_array(name, '/'), 1) - 1]\n$$;\n\ncreate or replace function storage.filename(name text) returns text\nlanguage sql immutable as $$\n select (string_to_array(name, '/'))[array_length(string_to_array(name, '/'), 1)]\n$$;\n\ncreate or replace function storage.extension(name text) returns text\nlanguage sql immutable as $$\n select reverse(split_part(reverse(storage.filename(name)), '.', 1))\n$$;\n\nalter table storage.objects enable row level security;\n\ndrop policy if exists tinbase_authenticated_all on storage.objects;\ndrop policy if exists tinbase_public_read on storage.objects;\n\n-- \u2500\u2500 Migration bookkeeping (same table the Supabase CLI uses) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\ncreate schema if not exists supabase_migrations;\n\ncreate table if not exists supabase_migrations.schema_migrations (\n version text primary key,\n name text,\n statements text[],\n applied_at timestamptz default now()\n);\n\ncreate table if not exists supabase_migrations.seed_files (\n path text primary key,\n hash text,\n applied_at timestamptz default now()\n);\n\n-- \u2500\u2500 Realtime CDC plumbing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\ncreate schema if not exists tinbase;\n\ncreate or replace function tinbase.cdc_notify() returns trigger\nlanguage plpgsql security definer as $$\ndeclare\n payload text;\nbegin\n payload := json_build_object(\n 'schema', TG_TABLE_SCHEMA,\n 'table', TG_TABLE_NAME,\n 'type', TG_OP,\n 'commit_timestamp', to_char(now() at time zone 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),\n 'record', case when TG_OP in ('INSERT', 'UPDATE') then row_to_json(NEW) else null end,\n 'old_record', case when TG_OP in ('UPDATE', 'DELETE') then row_to_json(OLD) else null end\n )::text;\n -- pg_notify payloads are capped at ~8kB; degrade like Supabase does.\n if octet_length(payload) > 7500 then\n payload := json_build_object(\n 'schema', TG_TABLE_SCHEMA,\n 'table', TG_TABLE_NAME,\n 'type', TG_OP,\n 'commit_timestamp', to_char(now() at time zone 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),\n 'record', null,\n 'old_record', null,\n 'errors', json_build_array('Payload too large')\n )::text;\n end if;\n perform pg_notify('tinbase_cdc', payload);\n return coalesce(NEW, OLD);\nend $$;\n\n-- \u2500\u2500 Realtime Authorization + broadcast-from-database \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- Mirrors Supabase Realtime: developers write RLS policies on\n-- realtime.messages using realtime.topic(); a SELECT policy grants a private\n-- channel's subscribers the right to *receive*, an INSERT policy the right to\n-- *broadcast*. realtime.send() lets the database push a broadcast to a topic.\ncreate schema if not exists realtime;\n\ncreate table if not exists realtime.messages (\n id uuid not null default gen_random_uuid(),\n topic text not null,\n extension text not null,\n event text,\n payload jsonb,\n private boolean default false,\n inserted_at timestamptz not null default now(),\n updated_at timestamptz not null default now(),\n primary key (id)\n);\nalter table realtime.messages enable row level security;\n\ngrant usage on schema realtime to anon, authenticated, service_role;\ngrant all on realtime.messages to anon, authenticated, service_role;\n\n-- the topic currently being authorized/broadcast (set per operation)\ncreate or replace function realtime.topic() returns text\n language sql stable as $$ select nullif(current_setting('realtime.topic', true), '') $$;\n\n-- push a broadcast message to all subscribers of <topic> from SQL / triggers.\n-- Delivered over the websocket by the in-process realtime engine, which listens\n-- on the 'tinbase_realtime_broadcast' channel.\ncreate or replace function realtime.send(payload jsonb, event text, topic text, private boolean default true)\n returns void language plpgsql security definer as $$\nbegin\n perform pg_notify(\n 'tinbase_realtime_broadcast',\n json_build_object('topic', topic, 'event', event, 'payload', payload, 'private', private)::text\n );\nexception when others then\n -- never let a notify failure abort the caller's transaction\n null;\nend $$;\n\ngrant execute on function realtime.topic() to anon, authenticated, service_role;\ngrant execute on function realtime.send(jsonb, text, text, boolean) to anon, authenticated, service_role;\n";
|
|
21
|
+
//# sourceMappingURL=bootstrap.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/db/bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,4iIA6IjC,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,aAAa,66eAwXzB,CAAA"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import type { DbEngine, EngineResults } from './engine.js';
|
|
2
|
+
import type { MigrationFile, RequestContext } from '../types.js';
|
|
3
|
+
/** One column of an introspected table. */
|
|
4
|
+
export interface ColumnInfo {
|
|
5
|
+
name: string;
|
|
6
|
+
/** underlying pg type name (pg_type.typname / information_schema.udt_name). */
|
|
7
|
+
udtName: string;
|
|
8
|
+
isNullable: boolean;
|
|
9
|
+
hasDefault: boolean;
|
|
10
|
+
isPrimaryKey: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** A foreign-key constraint, with source and target columns paired by position. */
|
|
13
|
+
export interface ForeignKey {
|
|
14
|
+
constraintName: string;
|
|
15
|
+
srcSchema: string;
|
|
16
|
+
srcTable: string;
|
|
17
|
+
srcColumns: string[];
|
|
18
|
+
tgtSchema: string;
|
|
19
|
+
tgtTable: string;
|
|
20
|
+
tgtColumns: string[];
|
|
21
|
+
}
|
|
22
|
+
/** An introspected table: its columns and primary-key column names. */
|
|
23
|
+
export interface TableInfo {
|
|
24
|
+
schema: string;
|
|
25
|
+
name: string;
|
|
26
|
+
columns: ColumnInfo[];
|
|
27
|
+
primaryKey: string[];
|
|
28
|
+
/**
|
|
29
|
+
* Column-sets with a uniqueness guarantee (each PRIMARY KEY / UNIQUE
|
|
30
|
+
* constraint, columns in definition order). Used to decide embed cardinality:
|
|
31
|
+
* a foreign key whose columns are a unique key on the referencing side is a
|
|
32
|
+
* one-to-one relationship (PostgREST serializes it as an object, not array).
|
|
33
|
+
*/
|
|
34
|
+
uniqueKeys: string[][];
|
|
35
|
+
}
|
|
36
|
+
/** One argument of a database function. */
|
|
37
|
+
export interface FunctionArg {
|
|
38
|
+
name: string;
|
|
39
|
+
type: string;
|
|
40
|
+
}
|
|
41
|
+
/** An introspected database function (used to route RPC calls). */
|
|
42
|
+
export interface FunctionInfo {
|
|
43
|
+
schema: string;
|
|
44
|
+
name: string;
|
|
45
|
+
returnsSet: boolean;
|
|
46
|
+
returnType: string;
|
|
47
|
+
/** pg_type.typtype: b=base, c=composite, p=pseudo, d=domain, e=enum */
|
|
48
|
+
returnTypType: string;
|
|
49
|
+
/** pg_proc.provolatile: v=volatile, s=stable, i=immutable. Volatile calls may run DDL. */
|
|
50
|
+
volatility: string;
|
|
51
|
+
args: FunctionArg[];
|
|
52
|
+
}
|
|
53
|
+
/** Introspected shape of one schema: tables keyed by name, plus its foreign keys. */
|
|
54
|
+
export interface SchemaInfo {
|
|
55
|
+
tables: Map<string, TableInfo>;
|
|
56
|
+
foreignKeys: ForeignKey[];
|
|
57
|
+
}
|
|
58
|
+
/** A function that runs a parameterized query, e.g. one bound to a transaction. */
|
|
59
|
+
export type Querier = (sql: string, params?: unknown[]) => Promise<EngineResults>;
|
|
60
|
+
/**
|
|
61
|
+
* A change-data-capture event for one row, shaped like Supabase Realtime's
|
|
62
|
+
* `postgres_changes` payload. Emitted by the SQL trigger on the real engines
|
|
63
|
+
* and synthesized in JS on pg-mem (see {@link Database.emitCdc}).
|
|
64
|
+
*/
|
|
65
|
+
export interface CdcEvent {
|
|
66
|
+
schema: string;
|
|
67
|
+
table: string;
|
|
68
|
+
type: 'INSERT' | 'UPDATE' | 'DELETE';
|
|
69
|
+
commit_timestamp: string;
|
|
70
|
+
/** post-image; null on DELETE (and on a payload that was too large). */
|
|
71
|
+
record: Record<string, unknown> | null;
|
|
72
|
+
/** pre-image; null on INSERT (and on a payload that was too large). */
|
|
73
|
+
old_record: Record<string, unknown> | null;
|
|
74
|
+
/** set when the row was dropped from the payload, e.g. 'Payload too large'. */
|
|
75
|
+
errors?: string[];
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The database facade: wraps a {@link DbEngine} with bootstrap, migration
|
|
79
|
+
* application, schema introspection (cached), and the realtime CDC pipeline.
|
|
80
|
+
*/
|
|
81
|
+
export declare class Database {
|
|
82
|
+
engine: DbEngine;
|
|
83
|
+
private schemaCache;
|
|
84
|
+
private fnCache;
|
|
85
|
+
private cdcListeners;
|
|
86
|
+
private cdcStarted;
|
|
87
|
+
private constructor();
|
|
88
|
+
/** Create a Database on PGlite (default) or any custom DbEngine. */
|
|
89
|
+
static create(dataDirOrEngine?: string | DbEngine, opts?: {
|
|
90
|
+
vaultKey?: string;
|
|
91
|
+
}): Promise<Database>;
|
|
92
|
+
/** Superuser query - used by auth/storage internals and introspection. */
|
|
93
|
+
query<T = any>(sql: string, params?: unknown[]): Promise<EngineResults<T>>;
|
|
94
|
+
/** Run one or more SQL statements with no params (superuser). */
|
|
95
|
+
exec(sql: string): Promise<unknown>;
|
|
96
|
+
/**
|
|
97
|
+
* Run `fn` inside a transaction with the request's Postgres role and JWT
|
|
98
|
+
* claims applied via SET LOCAL - this is what makes RLS behave exactly
|
|
99
|
+
* like hosted Supabase.
|
|
100
|
+
*/
|
|
101
|
+
withContext<T>(ctx: RequestContext, fn: (q: Querier) => Promise<T>): Promise<T>;
|
|
102
|
+
/**
|
|
103
|
+
* Apply any not-yet-recorded migrations (in lexicographic version order) and
|
|
104
|
+
* an optional seed, each in its own transaction, then invalidate the schema
|
|
105
|
+
* cache. Returns the names of what was applied this run.
|
|
106
|
+
*
|
|
107
|
+
* @throws whatever a migration throws, except on the pg-mem engine where an
|
|
108
|
+
* unsupported migration is skipped with a warning instead of aborting.
|
|
109
|
+
*/
|
|
110
|
+
runMigrations(migrations: MigrationFile[], seedSql?: string): Promise<string[]>;
|
|
111
|
+
/** Every migration recorded as applied, oldest version first. */
|
|
112
|
+
listAppliedMigrations(): Promise<{
|
|
113
|
+
version: string;
|
|
114
|
+
name: string | null;
|
|
115
|
+
}[]>;
|
|
116
|
+
/** Drop all cached introspection; call after any DDL changes the schema. */
|
|
117
|
+
invalidateSchemaCache(): void;
|
|
118
|
+
private rlsCache;
|
|
119
|
+
/** Names of tables in `schema` that have row-level security enabled. */
|
|
120
|
+
getRlsTables(schema: string): Promise<Set<string>>;
|
|
121
|
+
/** Introspect a schema's tables, columns, PKs, and FKs. Cached per schema. */
|
|
122
|
+
getSchemaInfo(schema: string): Promise<SchemaInfo>;
|
|
123
|
+
/**
|
|
124
|
+
* All overloads of a function by schema + name (cached). Multiple rows mean
|
|
125
|
+
* the name is overloaded on argument types.
|
|
126
|
+
*/
|
|
127
|
+
getFunctions(schema: string, name: string): Promise<FunctionInfo[]>;
|
|
128
|
+
/** Idempotently attach the CDC notify trigger to a table (real engines only). */
|
|
129
|
+
ensureCdcTrigger(schema: string, table: string): Promise<void>;
|
|
130
|
+
/**
|
|
131
|
+
* Register a CDC listener; the first call starts the single LISTEN on the
|
|
132
|
+
* shared `tinbase_cdc` channel. Returns an unsubscribe fn.
|
|
133
|
+
*/
|
|
134
|
+
onCdcEvent(cb: (e: CdcEvent) => void): Promise<() => void>;
|
|
135
|
+
/**
|
|
136
|
+
* True when the engine can't run the trigger + `pg_notify` CDC pipeline
|
|
137
|
+
* (pg-mem has no triggers/LISTEN/NOTIFY). For those engines the REST layer
|
|
138
|
+
* synthesizes change events in JS via {@link emitCdc}, since every write goes
|
|
139
|
+
* through it in-process.
|
|
140
|
+
*/
|
|
141
|
+
get jsCdc(): boolean;
|
|
142
|
+
/**
|
|
143
|
+
* Feed synthetic CDC events into the same listener set the trigger path uses,
|
|
144
|
+
* so realtime `postgres_changes` and database webhooks fire on engines without
|
|
145
|
+
* triggers/NOTIFY (pg-mem). Called by the REST handler after a committed
|
|
146
|
+
* mutation, one event per affected row.
|
|
147
|
+
*
|
|
148
|
+
* NOTE: these engines have no RLS, so events are delivered unfiltered - the
|
|
149
|
+
* per-subscriber row check in the realtime layer is a no-op here.
|
|
150
|
+
*/
|
|
151
|
+
emitCdc(meta: {
|
|
152
|
+
schema: string;
|
|
153
|
+
table: string;
|
|
154
|
+
type: CdcEvent['type'];
|
|
155
|
+
}, rows: Record<string, unknown>[]): void;
|
|
156
|
+
/** Close the underlying engine and its connection. */
|
|
157
|
+
close(): Promise<void>;
|
|
158
|
+
}
|
|
159
|
+
/** Parse pg_get_function_identity_arguments output: "a integer, b text[]". */
|
|
160
|
+
export declare function parseIdentityArgs(identity: string): FunctionArg[];
|
|
161
|
+
/**
|
|
162
|
+
* Double-quote an identifier for safe interpolation into SQL.
|
|
163
|
+
* @throws if the name contains a NUL, which Postgres identifiers can't hold.
|
|
164
|
+
*/
|
|
165
|
+
export declare function quoteIdent(name: string): string;
|
|
166
|
+
/** Single-quote a string literal for safe interpolation into SQL. */
|
|
167
|
+
export declare function quoteLiteral(value: string): string;
|
|
168
|
+
//# sourceMappingURL=database.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/db/database.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAY,MAAM,aAAa,CAAA;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEhE,2CAA2C;AAC3C,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,+EAA+E;IAC/E,OAAO,EAAE,MAAM,CAAA;IACf,UAAU,EAAE,OAAO,CAAA;IACnB,UAAU,EAAE,OAAO,CAAA;IACnB,YAAY,EAAE,OAAO,CAAA;CACtB;AAED,mFAAmF;AACnF,MAAM,WAAW,UAAU;IACzB,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MA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E,MAAM,GAAG,MAAM,CAElD"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure-SQL emulations of Supabase's queue and cron extensions, so migrations
|
|
3
|
+
* and app code that call pgmq.* / cron.* work with no C extension on either
|
|
4
|
+
* engine. pgmq is fully self-contained SQL. cron records jobs here; the
|
|
5
|
+
* in-process CronService (src/cron/service.ts) executes them.
|
|
6
|
+
*
|
|
7
|
+
* These match the real extensions' function signatures closely enough that
|
|
8
|
+
* `pgmq.send(...)`, `pgmq.read(...)`, `select cron.schedule(...)` etc. behave
|
|
9
|
+
* the same from the client's and a migration's point of view.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Self-contained SQL emulation of the pgmq extension: per-queue `q_<name>` /
|
|
13
|
+
* `a_<name>` tables plus create/send/read/pop/delete/archive/etc functions,
|
|
14
|
+
* matching pgmq's signatures. No C extension, no background worker needed.
|
|
15
|
+
*/
|
|
16
|
+
export declare const PGMQ_SQL = "\ncreate schema if not exists pgmq;\ngrant usage on schema pgmq to anon, authenticated, service_role;\n\ndo $$ begin\n if not exists (select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace\n where t.typname = 'message_record' and n.nspname = 'pgmq') then\n create type pgmq.message_record as (\n msg_id bigint, read_ct integer, enqueued_at timestamptz, vt timestamptz, message jsonb\n );\n end if;\nend $$;\n\ncreate or replace function pgmq.create(queue_name text) returns void language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\nbegin\n execute format('create table if not exists pgmq.%I (\n msg_id bigint generated always as identity primary key,\n read_ct integer not null default 0,\n enqueued_at timestamptz not null default now(),\n vt timestamptz not null default now(),\n message jsonb)', 'q_' || queue_name);\n execute format('create table if not exists pgmq.%I (\n msg_id bigint primary key, read_ct integer not null default 0,\n enqueued_at timestamptz not null, archived_at timestamptz not null default now(),\n vt timestamptz, message jsonb)', 'a_' || queue_name);\nend $pgmq$;\n\ncreate or replace function pgmq.send(queue_name text, msg jsonb, delay integer default 0)\nreturns bigint language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\ndeclare id bigint;\nbegin\n perform pgmq.create(queue_name);\n execute format('insert into pgmq.%I (vt, message) values (now() + make_interval(secs => $1), $2) returning msg_id', 'q_' || queue_name)\n into id using delay, msg;\n return id;\nend $pgmq$;\n\ncreate or replace function pgmq.read(queue_name text, vt integer, qty integer)\nreturns setof pgmq.message_record language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\nbegin\n return query execute format($fmt$\n with cte as (\n select msg_id from pgmq.%I where vt <= now() order by msg_id limit $1 for update skip locked\n )\n update pgmq.%I m set vt = now() + make_interval(secs => $2), read_ct = read_ct + 1\n from cte where m.msg_id = cte.msg_id\n returning m.msg_id, m.read_ct, m.enqueued_at, m.vt, m.message\n $fmt$, 'q_' || queue_name, 'q_' || queue_name) using qty, vt;\nend $pgmq$;\n\ncreate or replace function pgmq.pop(queue_name text)\nreturns setof pgmq.message_record language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\nbegin\n return query execute format($fmt$\n with cte as (select msg_id from pgmq.%I where vt <= now() order by msg_id limit 1 for update skip locked)\n delete from pgmq.%I m using cte where m.msg_id = cte.msg_id\n returning m.msg_id, m.read_ct, m.enqueued_at, m.vt, m.message\n $fmt$, 'q_' || queue_name, 'q_' || queue_name);\nend $pgmq$;\n\ncreate or replace function pgmq.delete(queue_name text, msg_id bigint)\nreturns boolean language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\ndeclare n integer;\nbegin\n execute format('delete from pgmq.%I where msg_id = $1', 'q_' || queue_name) using msg_id;\n get diagnostics n = row_count;\n return n > 0;\nend $pgmq$;\n\ncreate or replace function pgmq.archive(queue_name text, msg_id bigint)\nreturns boolean language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\ndeclare n integer;\nbegin\n execute format($fmt$\n with del as (delete from pgmq.%I where msg_id = $1 returning *)\n insert into pgmq.%I (msg_id, read_ct, enqueued_at, vt, message)\n select msg_id, read_ct, enqueued_at, vt, message from del\n $fmt$, 'q_' || queue_name, 'a_' || queue_name) using msg_id;\n get diagnostics n = row_count;\n return n > 0;\nend $pgmq$;\n\ncreate or replace function pgmq.drop_queue(queue_name text) returns boolean language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\nbegin\n execute format('drop table if exists pgmq.%I', 'q_' || queue_name);\n execute format('drop table if exists pgmq.%I', 'a_' || queue_name);\n return true;\nend $pgmq$;\n\ncreate or replace function pgmq.purge_queue(queue_name text) returns bigint language plpgsql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\ndeclare n bigint;\nbegin\n execute format('delete from pgmq.%I', 'q_' || queue_name);\n get diagnostics n = row_count;\n return n;\nend $pgmq$;\n\ncreate or replace function pgmq.list_queues()\nreturns table(queue_name text, is_partitioned boolean, is_unlogged boolean, created_at timestamptz)\nlanguage sql security definer set search_path = pgmq, pg_catalog, public as $pgmq$\n select substring(tablename from 3), false, false, now()\n from pg_tables where schemaname = 'pgmq' and left(tablename, 2) = 'q_';\n$pgmq$;\n\ngrant execute on all functions in schema pgmq to anon, authenticated, service_role;\n";
|
|
17
|
+
/**
|
|
18
|
+
* pg_cron emulation: the `cron.job` / `cron.job_run_details` tables and
|
|
19
|
+
* schedule/unschedule functions. This only records jobs; the in-process
|
|
20
|
+
* CronService (src/cron/service.ts) reads the table and runs them.
|
|
21
|
+
*/
|
|
22
|
+
export declare const CRON_SQL = "\ncreate schema if not exists cron;\n-- cron.schedule executes arbitrary SQL as the (superuser) function owner, so it\n-- must stay restricted to service_role - matching hosted Supabase, where\n-- authenticated cannot schedule jobs.\ngrant usage on schema cron to service_role;\n\ncreate table if not exists cron.job (\n jobid bigint generated always as identity primary key,\n schedule text not null,\n command text not null,\n jobname text unique,\n active boolean not null default true,\n created_at timestamptz not null default now()\n);\n\ncreate table if not exists cron.job_run_details (\n runid bigint generated always as identity primary key,\n jobid bigint,\n command text,\n status text,\n return_message text,\n start_time timestamptz,\n end_time timestamptz\n);\n\ncreate or replace function cron.schedule(job_name text, schedule text, command text)\nreturns bigint language plpgsql security definer set search_path = cron, pg_catalog, public as $cron$\ndeclare id bigint;\nbegin\n insert into cron.job (jobname, schedule, command) values (job_name, schedule, command)\n on conflict (jobname) do update set schedule = excluded.schedule, command = excluded.command, active = true\n returning jobid into id;\n return id;\nend $cron$;\n\ncreate or replace function cron.schedule(schedule text, command text)\nreturns bigint language plpgsql security definer set search_path = cron, pg_catalog, public as $cron$\nbegin\n return cron.schedule('job_' || floor(extract(epoch from clock_timestamp()) * 1000)::bigint::text, schedule, command);\nend $cron$;\n\ncreate or replace function cron.unschedule(job_name text)\nreturns boolean language plpgsql security definer set search_path = cron, pg_catalog, public as $cron$\ndeclare n integer;\nbegin\n delete from cron.job where jobname = job_name;\n get diagnostics n = row_count;\n return n > 0;\nend $cron$;\n\ncreate or replace function cron.unschedule(job_id bigint)\nreturns boolean language plpgsql security definer set search_path = cron, pg_catalog, public as $cron$\ndeclare n integer;\nbegin\n delete from cron.job where jobid = job_id;\n get diagnostics n = row_count;\n return n > 0;\nend $cron$;\n\ngrant execute on function cron.schedule(text,text,text), cron.schedule(text,text), cron.unschedule(text), cron.unschedule(bigint) to service_role;\n";
|
|
23
|
+
/**
|
|
24
|
+
* pg_net emulation - the `net.http_get/post/delete` SQL surface. The functions
|
|
25
|
+
* only enqueue into net.http_request_queue; the in-process NetService
|
|
26
|
+
* (src/net/service.ts) performs the HTTP and records the reply in
|
|
27
|
+
* net._http_response, exactly like pg_net's background worker. This lets the
|
|
28
|
+
* common Supabase pattern - a cron job that calls net.http_post to hit an Edge
|
|
29
|
+
* Function - run unchanged, with no C extension on either engine.
|
|
30
|
+
*/
|
|
31
|
+
export declare const NET_SQL = "\ncreate schema if not exists net;\n-- net.http_* can reach arbitrary URLs from the server (SSRF surface), so keep it\n-- restricted to service_role like hosted Supabase - not authenticated.\ngrant usage on schema net to service_role;\n\ncreate table if not exists net.http_request_queue (\n id bigint generated always as identity primary key,\n method text not null,\n url text not null,\n headers jsonb not null default '{}'::jsonb,\n body text,\n timeout_milliseconds int not null default 5000,\n created timestamptz not null default now()\n);\n\ncreate table if not exists net._http_response (\n id bigint primary key,\n status_code int,\n content_type text,\n headers jsonb,\n content text,\n timed_out boolean,\n error_msg text,\n created timestamptz not null default now()\n);\ngrant select on net._http_response to service_role;\n\n-- fold a jsonb param object into the URL as a query string (pg_net semantics)\ncreate or replace function net._merge_params(url text, params jsonb)\nreturns text language sql immutable as $net$\n select case\n when params is null or params = '{}'::jsonb then url\n else url || (case when position('?' in url) > 0 then '&' else '?' end) ||\n (select string_agg(key || '=' || (value #>> '{}'), '&') from jsonb_each(params))\n end;\n$net$;\n\ncreate or replace function net.http_get(url text, params jsonb default '{}'::jsonb, headers jsonb default '{}'::jsonb, timeout_milliseconds int default 5000)\nreturns bigint language plpgsql security definer set search_path = net, pg_catalog, public as $net$\ndeclare req_id bigint;\nbegin\n insert into net.http_request_queue (method, url, headers, body, timeout_milliseconds)\n values ('GET', net._merge_params(url, params), coalesce(headers, '{}'::jsonb), null, timeout_milliseconds)\n returning id into req_id;\n return req_id;\nend $net$;\n\ncreate or replace function net.http_post(url text, body jsonb default '{}'::jsonb, params jsonb default '{}'::jsonb, headers jsonb default '{}'::jsonb, timeout_milliseconds int default 5000)\nreturns bigint language plpgsql security definer set search_path = net, pg_catalog, public as $net$\ndeclare req_id bigint; hdrs jsonb;\nbegin\n hdrs := coalesce(headers, '{}'::jsonb);\n -- default the content type to JSON, matching pg_net, unless the caller set one\n if not (hdrs ? 'Content-Type' or hdrs ? 'content-type') then\n hdrs := hdrs || jsonb_build_object('Content-Type', 'application/json');\n end if;\n insert into net.http_request_queue (method, url, headers, body, timeout_milliseconds)\n values ('POST', net._merge_params(url, params), hdrs, body::text, timeout_milliseconds)\n returning id into req_id;\n return req_id;\nend $net$;\n\ncreate or replace function net.http_delete(url text, params jsonb default '{}'::jsonb, headers jsonb default '{}'::jsonb, timeout_milliseconds int default 5000)\nreturns bigint language plpgsql security definer set search_path = net, pg_catalog, public as $net$\ndeclare req_id bigint;\nbegin\n insert into net.http_request_queue (method, url, headers, body, timeout_milliseconds)\n values ('DELETE', net._merge_params(url, params), coalesce(headers, '{}'::jsonb), null, timeout_milliseconds)\n returning id into req_id;\n return req_id;\nend $net$;\n\ngrant execute on function net.http_get(text,jsonb,jsonb,int), net.http_post(text,jsonb,jsonb,jsonb,int), net.http_delete(text,jsonb,jsonb,int) to service_role;\n";
|
|
32
|
+
/**
|
|
33
|
+
* Small pure-SQL stand-ins for contrib extensions Supabase migrations lean on
|
|
34
|
+
* but which aren't in the PGlite / native builds. `moddatetime` (a BEFORE
|
|
35
|
+
* UPDATE trigger that stamps a timestamp column) is the common one - projects
|
|
36
|
+
* attach it as the updated_at trigger. Created only if absent, so a real
|
|
37
|
+
* extension (where present) still wins.
|
|
38
|
+
*/
|
|
39
|
+
export declare const EXT_COMPAT_SQL = "\ncreate schema if not exists extensions;\ndo $ensure_moddatetime$\nbegin\n if not exists (\n select 1 from pg_proc p join pg_namespace n on n.oid = p.pronamespace\n where n.nspname = 'extensions' and p.proname = 'moddatetime'\n ) then\n execute $fn$\n create function extensions.moddatetime() returns trigger language plpgsql as $mod$\n begin\n if TG_NARGS >= 1 then\n NEW := jsonb_populate_record(NEW, jsonb_build_object(TG_ARGV[0], now()));\n end if;\n return NEW;\n end\n $mod$\n $fn$;\n end if;\nend\n$ensure_moddatetime$;\n";
|
|
40
|
+
/**
|
|
41
|
+
* Supabase Vault emulation. Real Vault (supabase_vault + pgsodium) encrypts
|
|
42
|
+
* secrets at rest; we can't ship those C extensions. This stand-in keeps the
|
|
43
|
+
* same surface (vault.secrets, vault.decrypted_secrets, vault.create_secret /
|
|
44
|
+
* update_secret) but stores the secret encrypted with pgcrypto's authenticated
|
|
45
|
+
* symmetric encryption (pgp_sym_encrypt) under a key held in the GUC
|
|
46
|
+
* app.settings.vault_key, set at boot and never stored in the database.
|
|
47
|
+
*
|
|
48
|
+
* SECURITY: the stored `secret` column holds ciphertext; decrypted_secrets
|
|
49
|
+
* decrypts on read. If pgcrypto or the key is unavailable the functions raise,
|
|
50
|
+
* rather than silently falling back to cleartext.
|
|
51
|
+
*/
|
|
52
|
+
export declare const VAULT_SQL = "\ncreate schema if not exists vault;\ngrant usage on schema vault to service_role;\n\ncreate table if not exists vault.secrets (\n id uuid primary key default gen_random_uuid(),\n name text unique,\n description text not null default '',\n secret text not null,\n key_id uuid,\n nonce bytea,\n created_at timestamptz not null default now(),\n updated_at timestamptz not null default now()\n);\ngrant select, insert, update, delete on vault.secrets to service_role;\n\n-- the encryption key, from the GUC set at boot (empty string if unset)\ncreate or replace function vault._key() returns text\nlanguage sql stable as $vault$\n select coalesce(nullif(current_setting('app.settings.vault_key', true), ''), '')\n$vault$;\n\ncreate or replace function vault._encrypt(plain text) returns text\nlanguage plpgsql security definer set search_path = vault, extensions, pg_catalog, public as $vault$\ndeclare k text := vault._key();\nbegin\n if plain is null then return null; end if;\n if k = '' then raise exception 'vault key is not configured'; end if;\n return encode(pgp_sym_encrypt(plain, k), 'base64');\nend $vault$;\n\ncreate or replace function vault._decrypt(cipher text) returns text\nlanguage plpgsql security definer set search_path = vault, extensions, pg_catalog, public as $vault$\ndeclare k text := vault._key();\nbegin\n if cipher is null then return null; end if;\n if k = '' then raise exception 'vault key is not configured'; end if;\n return pgp_sym_decrypt(decode(cipher, 'base64'), k);\nend $vault$;\n\ncreate or replace view vault.decrypted_secrets as\n select id, name, description, secret, vault._decrypt(secret) as decrypted_secret, key_id, nonce, created_at, updated_at\n from vault.secrets;\ngrant select on vault.decrypted_secrets to service_role;\n\ncreate or replace function vault.create_secret(new_secret text, new_name text default null, new_description text default '', new_key_id uuid default null)\nreturns uuid language plpgsql security definer set search_path = vault, pg_catalog, public as $vault$\ndeclare rec_id uuid;\nbegin\n insert into vault.secrets (name, description, secret, key_id)\n values (new_name, coalesce(new_description, ''), vault._encrypt(new_secret), new_key_id)\n returning id into rec_id;\n return rec_id;\nend $vault$;\n\ncreate or replace function vault.update_secret(secret_id uuid, new_secret text default null, new_name text default null, new_description text default null, new_key_id uuid default null)\nreturns void language plpgsql security definer set search_path = vault, pg_catalog, public as $vault$\nbegin\n update vault.secrets set\n secret = case when new_secret is null then secret else vault._encrypt(new_secret) end,\n name = coalesce(new_name, name),\n description = coalesce(new_description, description),\n key_id = coalesce(new_key_id, key_id),\n updated_at = now()\n where id = secret_id;\nend $vault$;\n\ngrant execute on function vault.create_secret(text,text,text,uuid), vault.update_secret(uuid,text,text,text,uuid) to service_role;\n";
|
|
53
|
+
//# sourceMappingURL=emulated.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emulated.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/db/emulated.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH;;;;GAIG;AACH,eAAO,MAAM,QAAQ,ixJAyGpB,CAAA;AAID;;;;GAIG;AACH,eAAO,MAAM,QAAQ,uyEA6DpB,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,OAAO,82GA0EnB,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,ulBAqB1B,CAAA;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,SAAS,m/FAoErB,CAAA"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Database engine abstraction. Two implementations:
|
|
3
|
+
* - PGlite (WASM Postgres): portable, runs in the browser; heavier RAM.
|
|
4
|
+
* - Native embedded Postgres (Node only): PocketBase-class footprint.
|
|
5
|
+
* The rest of tinbase only talks to this interface.
|
|
6
|
+
*/
|
|
7
|
+
/** Result of a query: returned rows plus, for writes, the affected row count. */
|
|
8
|
+
export interface EngineResults<T = any> {
|
|
9
|
+
/** result rows, typed as `T` */
|
|
10
|
+
rows: T[];
|
|
11
|
+
/** rows touched by an INSERT/UPDATE/DELETE; undefined for plain SELECTs */
|
|
12
|
+
affectedRows?: number;
|
|
13
|
+
}
|
|
14
|
+
/** Handle passed to a transaction callback; scoped to the open transaction. */
|
|
15
|
+
export interface EngineTx {
|
|
16
|
+
/** run a parameterized query within the transaction */
|
|
17
|
+
query<T = any>(sql: string, params?: unknown[]): Promise<EngineResults<T>>;
|
|
18
|
+
/** run one or more statements within the transaction (no params) */
|
|
19
|
+
exec(sql: string): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The single database interface the rest of tinbase talks to, regardless of
|
|
23
|
+
* whether it's backed by PGlite, native embedded Postgres, or the pg-mem subset.
|
|
24
|
+
*/
|
|
25
|
+
export interface DbEngine {
|
|
26
|
+
/** true for subset engines (pg-mem) that can't run the full plpgsql/RLS bootstrap */
|
|
27
|
+
minimalBootstrap?: boolean;
|
|
28
|
+
/** run a parameterized query */
|
|
29
|
+
query<T = any>(sql: string, params?: unknown[]): Promise<EngineResults<T>>;
|
|
30
|
+
/** run multiple SQL statements (no params) */
|
|
31
|
+
exec(sql: string): Promise<void>;
|
|
32
|
+
/** serialized transaction; implementations must guarantee mutual exclusion */
|
|
33
|
+
transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T>;
|
|
34
|
+
/** subscribe to pg_notify on a channel; returns an unsubscribe function */
|
|
35
|
+
listen(channel: string, cb: (payload: string) => void): Promise<() => void>;
|
|
36
|
+
/** close the underlying connection/instance */
|
|
37
|
+
close(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** Simple async mutex for engines that serialize over one connection. */
|
|
40
|
+
export declare class Mutex {
|
|
41
|
+
private tail;
|
|
42
|
+
/** Acquire the lock; await the returned release fn's turn, then call it to free it. */
|
|
43
|
+
lock(): Promise<() => void>;
|
|
44
|
+
/** Run `fn` while holding the lock; releases even if `fn` throws. */
|
|
45
|
+
run<T>(fn: () => Promise<T>): Promise<T>;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=engine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"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K,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CACvB;AAED,yEAAyE;AACzE,qBAAa,KAAK;IAChB,OAAO,CAAC,IAAI,CAAmC;IAE/C,uFAAuF;IACjF,IAAI,IAAI,OAAO,CAAC,MAAM,IAAI,CAAC;IASjC,qEAAqE;IAC/D,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAQ/C"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `tinbase inspect` core: a lightweight database report - per-table row counts
|
|
3
|
+
* and on-disk size for a schema. Like a tiny `supabase inspect db`, enough to
|
|
4
|
+
* eyeball what's in a local project. (Uses pg_total_relation_size, so it runs
|
|
5
|
+
* on the real-Postgres engines, not the pg-mem subset.)
|
|
6
|
+
*/
|
|
7
|
+
import { type Database } from './database.js';
|
|
8
|
+
/** One row of the inspect report: a table with its row count and on-disk size. */
|
|
9
|
+
export interface TableInfo {
|
|
10
|
+
/** table name (unqualified) */
|
|
11
|
+
table: string;
|
|
12
|
+
/** live row count from count(*) */
|
|
13
|
+
rows: number;
|
|
14
|
+
/** human-readable total relation size (pg_size_pretty) */
|
|
15
|
+
size: string;
|
|
16
|
+
}
|
|
17
|
+
/** Report per-table row counts and on-disk sizes for a schema, largest first. */
|
|
18
|
+
export declare function inspectDb(db: Database, schema?: string): Promise<TableInfo[]>;
|
|
19
|
+
//# sourceMappingURL=inspect.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inspect.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/db/inspect.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAc,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAA;AAEzD,kFAAkF;AAClF,MAAM,WAAW,SAAS;IACxB,+BAA+B;IAC/B,KAAK,EAAE,MAAM,CAAA;IACb,mCAAmC;IACnC,IAAI,EAAE,MAAM,CAAA;IACZ,0DAA0D;IAC1D,IAAI,EAAE,MAAM,CAAA;CACb;AAED,iFAAiF;AACjF,wBAAsB,SAAS,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,SAAW,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAkBrF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DbEngine } from './engine.js';
|
|
2
|
+
/**
|
|
3
|
+
* Build a {@link DbEngine} backed by PGlite (WASM Postgres) at `dataDir`, or an
|
|
4
|
+
* in-memory database when `dataDir` is omitted. Loads the bundled contrib
|
|
5
|
+
* extensions Supabase enables by default.
|
|
6
|
+
* @throws if the PGlite WASM bundle isn't available in this build (use the native engine instead).
|
|
7
|
+
*/
|
|
8
|
+
export declare function createPgliteEngine(dataDir?: string): Promise<DbEngine>;
|
|
9
|
+
//# sourceMappingURL=pglite-engine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pglite-engine.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/db/pglite-engine.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAA2B,MAAM,aAAa,CAAA;AAEpE;;;;;GAKG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkE5E"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Database } from './database.js';
|
|
2
|
+
interface ColumnSnap {
|
|
3
|
+
name: string;
|
|
4
|
+
/** fully-specified type from format_type (e.g. `character varying(255)`) */
|
|
5
|
+
type: string;
|
|
6
|
+
nullable: boolean;
|
|
7
|
+
/** column default expression, or null when none */
|
|
8
|
+
default: string | null;
|
|
9
|
+
}
|
|
10
|
+
interface TableSnap {
|
|
11
|
+
name: string;
|
|
12
|
+
columns: Map<string, ColumnSnap>;
|
|
13
|
+
/** column names in declaration order, so DDL is emitted deterministically */
|
|
14
|
+
order: string[];
|
|
15
|
+
}
|
|
16
|
+
/** A structured snapshot of one schema, diffable into DDL by {@link diffSchemas}. */
|
|
17
|
+
export interface SchemaSnapshot {
|
|
18
|
+
/** table name → its columns */
|
|
19
|
+
tables: Map<string, TableSnap>;
|
|
20
|
+
/** table → (constraint name → definition from pg_get_constraintdef) */
|
|
21
|
+
constraints: Map<string, Map<string, string>>;
|
|
22
|
+
/** table → (index name → definition from pg_get_indexdef), excluding constraint-backing indexes */
|
|
23
|
+
indexes: Map<string, Map<string, string>>;
|
|
24
|
+
/** enum type name → its labels in sort order */
|
|
25
|
+
enums: Map<string, string[]>;
|
|
26
|
+
}
|
|
27
|
+
/** Snapshot a schema's tables, columns, constraints, indexes, and enums. */
|
|
28
|
+
export declare function snapshotSchema(db: Database, schema?: string): Promise<SchemaSnapshot>;
|
|
29
|
+
/** DDL to turn `from` into `to`, scoped to one schema. Empty array = no changes. */
|
|
30
|
+
export declare function diffSchemas(from: SchemaSnapshot, to: SchemaSnapshot, schema?: string): string[];
|
|
31
|
+
export {};
|
|
32
|
+
//# sourceMappingURL=schema-diff.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-diff.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/db/schema-diff.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAE7C,UAAU,UAAU;IAClB,IAAI,EAAE,MAAM,CAAA;IACZ,4EAA4E;IAC5E,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,OAAO,CAAA;IACjB,mDAAmD;IACnD,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;CACvB;AACD,UAAU,SAAS;IACjB,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;IAChC,6EAA6E;IAC7E,KAAK,EAAE,MAAM,EAAE,CAAA;CAChB;AAED,qFAAqF;AACrF,MAAM,WAAW,cAAc;IAC7B,+BAA+B;IAC/B,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;IAC9B,uEAAuE;IACvE,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAC7C,mGAAmG;IACnG,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IACzC,gDAAgD;IAChD,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAA;CAC7B;AAED,4EAA4E;AAC5E,wBAAsB,cAAc,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,SAAW,GAAG,OAAO,CAAC,cAAc,CAAC,CAqE7F;AAED,oFAAoF;AACpF,wBAAgB,WAAW,CAAC,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,cAAc,EAAE,MAAM,SAAW,GAAG,MAAM,EAAE,CAiFjG"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compatibility rewrites for user migration / seed SQL.
|
|
3
|
+
*
|
|
4
|
+
* tinbase can't install C extensions (pg_cron, pg_net, http, supabase_vault,
|
|
5
|
+
* hypopg, …) into the PGlite or embedded-native Postgres build, and several of
|
|
6
|
+
* them are emulated in pure SQL instead (cron, pg_net, pgmq - see
|
|
7
|
+
* db/emulated.ts). A real Supabase project's first migration typically runs a
|
|
8
|
+
* batch of `CREATE EXTENSION` statements; on stock Postgres a missing one
|
|
9
|
+
* aborts the whole migration with `extension "…" is not available`.
|
|
10
|
+
*
|
|
11
|
+
* `tolerateExtensionStatements` wraps every *top-level* CREATE/DROP EXTENSION
|
|
12
|
+
* statement in a `DO … EXCEPTION WHEN OTHERS` block (the same trick the
|
|
13
|
+
* bootstrap uses for its own extension list), so an unavailable extension is
|
|
14
|
+
* skipped with a NOTICE rather than aborting the migration. Extensions the
|
|
15
|
+
* engine does bundle are still created normally, and the emulated schemas
|
|
16
|
+
* created at bootstrap remain in place.
|
|
17
|
+
*
|
|
18
|
+
* It also strips `CONCURRENTLY` from index statements: tinbase applies each
|
|
19
|
+
* migration inside a transaction (for atomicity + rollback), and
|
|
20
|
+
* `CREATE/DROP INDEX CONCURRENTLY` / `REINDEX … CONCURRENTLY` are illegal in a
|
|
21
|
+
* transaction block. On a single-connection local dev database CONCURRENTLY
|
|
22
|
+
* buys nothing over a plain index, so we drop the keyword - the resulting index
|
|
23
|
+
* is identical.
|
|
24
|
+
*
|
|
25
|
+
* The scan is quote/comment-aware so it never touches these keywords when they
|
|
26
|
+
* appear inside a dollar-quoted function body, a string literal, or a comment.
|
|
27
|
+
*/
|
|
28
|
+
/**
|
|
29
|
+
* Rewrite user migration / seed SQL for the local engine: make CREATE/DROP
|
|
30
|
+
* EXTENSION tolerant, and strip CONCURRENTLY from index statements.
|
|
31
|
+
*/
|
|
32
|
+
export declare function rewriteMigrationSql(sql: string): string;
|
|
33
|
+
//# sourceMappingURL=sql-compat.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql-compat.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/db/sql-compat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CA0EvD"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type DenoHandler = (req: Request) => Response | Promise<Response>;
|
|
2
|
+
/**
|
|
3
|
+
* Run `fn` with the shim's Deno.env bound to `env`. The binding lives in an
|
|
4
|
+
* async-context store, so concurrent invocations each read their own env and
|
|
5
|
+
* one backend can never observe another's (or the host's) secrets.
|
|
6
|
+
*/
|
|
7
|
+
export declare function runWithDenoEnv<T>(env: Record<string, string>, fn: () => Promise<T>): Promise<T>;
|
|
8
|
+
/** Install globalThis.Deno if we're not already running under a Deno-like runtime. */
|
|
9
|
+
export declare function installDenoShim(): void;
|
|
10
|
+
/** Return and clear the handler captured by the most recent Deno.serve() call. */
|
|
11
|
+
export declare function takeCapturedHandler(): DenoHandler | undefined;
|
|
12
|
+
/** Clear any handler captured by Deno.serve(), without returning it. */
|
|
13
|
+
export declare function resetCapturedHandler(): void;
|
|
14
|
+
export {};
|
|
15
|
+
//# sourceMappingURL=deno-shim.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deno-shim.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/functions/deno-shim.ts"],"names":[],"mappings":"AAkBA,KAAK,WAAW,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAA;AAYjE;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAE/F;AAED,sFAAsF;AACtF,wBAAgB,eAAe,IAAI,IAAI,CAqCtC;AAED,kFAAkF;AAClF,wBAAgB,mBAAmB,IAAI,WAAW,GAAG,SAAS,CAI7D;AAED,wEAAwE;AACxE,wBAAgB,oBAAoB,IAAI,IAAI,CAE3C"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edge Functions (/functions/v1/*) - supabase.functions.invoke() support.
|
|
3
|
+
*
|
|
4
|
+
* A "function" is any fetch handler: (Request) => Response | Promise<Response>.
|
|
5
|
+
* The core takes a name → handler map (portable, works in the browser); the
|
|
6
|
+
* Node CLI populates it from supabase/functions/<name>/index.{ts,js,mjs}
|
|
7
|
+
* modules that `export default` a fetch handler.
|
|
8
|
+
*/
|
|
9
|
+
import type { RequestContext } from '../types.js';
|
|
10
|
+
/** An edge function: a fetch handler invoked with the resolved request context. */
|
|
11
|
+
export type EdgeFunction = (req: Request, ctx: FunctionContext) => Response | Promise<Response>;
|
|
12
|
+
/** Second argument passed to every {@link EdgeFunction} invocation. */
|
|
13
|
+
export interface FunctionContext {
|
|
14
|
+
/** verified request context (role + JWT claims) resolved by the router */
|
|
15
|
+
auth: RequestContext;
|
|
16
|
+
/** keys/urls so the function can create its own supabase-js client, plus any secrets loaded from supabase/functions/.env */
|
|
17
|
+
env: {
|
|
18
|
+
SUPABASE_URL: string;
|
|
19
|
+
SUPABASE_ANON_KEY: string;
|
|
20
|
+
SUPABASE_SERVICE_ROLE_KEY: string;
|
|
21
|
+
[key: string]: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Registry and dispatcher for edge functions, backing supabase.functions.invoke(). */
|
|
25
|
+
export declare class FunctionsHandler {
|
|
26
|
+
private functions;
|
|
27
|
+
private env;
|
|
28
|
+
constructor(functions: Map<string, EdgeFunction>, env: FunctionContext['env']);
|
|
29
|
+
/** Register (or replace) a function under `name`, served at /functions/v1/<name>. */
|
|
30
|
+
register(name: string, fn: EdgeFunction): void;
|
|
31
|
+
/** Names of all registered functions. */
|
|
32
|
+
list(): string[];
|
|
33
|
+
/** Dispatch a /functions/v1/<name> request to its handler, returning a 404 when unknown and a 500 when the handler throws or returns a non-Response. */
|
|
34
|
+
handle(req: Request, ctx: RequestContext, url: URL): Promise<Response>;
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../../src/vendor/tinbase/functions/handler.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAGjD,mFAAmF;AACnF,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,eAAe,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAA;AAE/F,uEAAuE;AACvE,MAAM,WAAW,eAAe;IAC9B,0EAA0E;IAC1E,IAAI,EAAE,cAAc,CAAA;IACpB,4HAA4H;IAC5H,GAAG,EAAE;QACH,YAAY,EAAE,MAAM,CAAA;QACpB,iBAAiB,EAAE,MAAM,CAAA;QACzB,yBAAyB,EAAE,MAAM,CAAA;QACjC,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;CACF;AAED,uFAAuF;AACvF,qBAAa,gBAAgB;IAEzB,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,GAAG;gBADH,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EACpC,GAAG,EAAE,eAAe,CAAC,KAAK,CAAC;IAGrC,qFAAqF;IACrF,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,YAAY,GAAG,IAAI;IAI9C,yCAAyC;IACzC,IAAI,IAAI,MAAM,EAAE;IAIhB,wJAAwJ;IAClJ,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,QAAQ,CAAC;CAuB7E"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generate a Supabase-shaped `Database` TypeScript type from the live schema,
|
|
3
|
+
* matching `supabase gen types typescript` closely enough that a typed
|
|
4
|
+
* supabase-js client works unchanged:
|
|
5
|
+
*
|
|
6
|
+
* export type Database = {
|
|
7
|
+
* public: {
|
|
8
|
+
* Tables: { <t>: { Row, Insert, Update, Relationships } }
|
|
9
|
+
* Views: { <v>: { Row } }
|
|
10
|
+
* Functions: { <f>: { Args, Returns } }
|
|
11
|
+
* Enums: { <e>: "a" | "b" }
|
|
12
|
+
* CompositeTypes: {}
|
|
13
|
+
* }
|
|
14
|
+
* }
|
|
15
|
+
*/
|
|
16
|
+
import { type Database } from './db/database.js';
|
|
17
|
+
/**
|
|
18
|
+
* Emit the `Database` type source (see module header) for one schema of the
|
|
19
|
+
* live database. Reads columns, enums, functions, and foreign keys, then formats
|
|
20
|
+
* them into the Supabase-shaped type text ready to write to a .d.ts.
|
|
21
|
+
*/
|
|
22
|
+
export declare function generateTypes(db: Database, schema?: string): Promise<string>;
|
|
23
|
+
//# sourceMappingURL=gen-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gen-types.d.ts","sourceRoot":"","sources":["../../../src/vendor/tinbase/gen-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAqB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AA2BnE;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,SAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CA4HpF"}
|