Skip to content

Subscrio

Purpose

Subscrio is the entry point for the library. Configure its database connection, then use its objects to manage your catalog, subscriptions, feature checks, usage, and credits.

Access and initialization

Access

Create one instance for your application or dependency-injection scope. Install the schema for a new database, or verify and migrate an existing installation before using the catalog. Examples on the object pages use this initialized subscrio instance.

import { Subscrio } from 'subscrio';

const subscrio = new Subscrio({
  database: { connectionString: process.env.DATABASE_URL! }
});

const version = await subscrio.verifySchema();
if (version === null) await subscrio.installSchema();
else await subscrio.migrate();
using Subscrio.Core;
using Subscrio.Core.Config;

using var subscrio = new Subscrio.Core.Subscrio(new SubscrioConfig
{
    Database = new DatabaseConfig
    {
        ConnectionString = Environment.GetEnvironmentVariable("DATABASE_URL")!
    }
});

var version = await subscrio.VerifySchemaAsync();
if (version is null) await subscrio.InstallSchemaAsync();
else await subscrio.MigrateAsync();

For ASP.NET Core, register with services.AddSubscrio(config, ServiceLifetime.Scoped) from Subscrio.Core.DependencyInjection and inject Subscrio into each request scope. The container disposes it with the scope. See Getting Started for the complete registration example.

Constructor

Create the library instance and its public objects. Construction does not install the schema or apply initial configuration. TypeScript supports PostgreSQL; .NET supports PostgreSQL and SQL Server.

new Subscrio(config: SubscrioConfig)

Parameters

  • config: SubscrioConfig with the database connection and optional integration settings.

Example

const configured = new Subscrio({
  database: { connectionString: process.env.DATABASE_URL! },
  initialConfig: { type: 'file', filePath: './subscrio.json' }
});
Errors (1)
  • ConfigurationError: SQL Server was selected for the TypeScript runtime.
new Subscrio(SubscrioConfig config)

Parameters

  • config: SubscrioConfig with the database connection and optional integration settings.

Example

using var configured = new Subscrio.Core.Subscrio(new SubscrioConfig
{
    Database = new DatabaseConfig
    {
        ConnectionString = Environment.GetEnvironmentVariable("DATABASE_URL")!
    },
    InitialConfig = new InitialConfigOptions { FilePath = "./subscrio.json" }
});
Errors (1)
  • ArgumentException: The configured database provider is unsupported.

Method catalog

Database and connection failures may propagate from any operation. Method-specific errors are listed with each method.

Method Purpose
installSchema Installs the database schema.
migrate Applies pending schema migrations.
verifySchema Reads the installed schema version.
runInitialConfigSync Applies the initial catalog configuration.
dropSchema Permanently removes Subscrio tables and data.
close Releases database resources.
Method Purpose
InstallSchemaAsync Installs the database schema.
MigrateAsync Applies pending schema migrations.
VerifySchemaAsync Reads the installed schema version.
RunInitialConfigSyncAsync Applies the initial catalog configuration.
DropSchemaAsync Permanently removes Subscrio tables and data.
Dispose Releases database resources.

Method details

installSchema

Create the Subscrio tables and initial configuration. A supplied administrator passphrase is hashed and stored only if no hash exists; installation never replaces an existing hash. Use migration to upgrade an existing schema.

installSchema(adminPassphrase?: string): Promise<void>

Parameters

  • adminPassphrase: Optional passphrase. The argument takes precedence over the constructor setting; when omitted, the configured passphrase is used.

Returns No returned value.

Example

await subscrio.installSchema();
Errors (1)
  • ValidationError: The installed schema is newer than the library.
Task InstallSchemaAsync(string? adminPassphrase)

Parameters

  • adminPassphrase: Optional passphrase. The argument takes precedence over the constructor setting; when omitted, the configured passphrase is used.

Returns No returned value.

Example

await subscrio.InstallSchemaAsync();
Errors (1)
  • ValidationException: The installed schema is newer than the library.

migrate

Apply pending schema migrations and save the updated version. Already-applied migrations are skipped. See Schema Upgrade before upgrading an existing database.

migrate(): Promise<number>

Returns number: Number of migrations applied, or zero when already current.

Example

const applied = await subscrio.migrate();
console.log(applied);
Errors (1)
  • ValidationError: The installed schema is newer than the library.
Task<int> MigrateAsync()

Returns int: Number of migrations applied, or zero when already current.

Example

var applied = await subscrio.MigrateAsync();
Console.WriteLine(applied);
Errors (1)
  • ValidationException: The installed schema is newer than the library.

verifySchema

Read the stored schema version to determine whether installation or migration is needed. Unexpected database failures propagate to the caller.

verifySchema(): Promise<string | null>

Returns string | null: Installed version, or null when the schema or version is missing.

Example

const version = await subscrio.verifySchema();
console.log(version);
Task<string?> VerifySchemaAsync()

Returns string?: Installed version, or null when the schema or version is missing.

Example

var version = await subscrio.VerifySchemaAsync();
Console.WriteLine(version);

runInitialConfigSync

Apply the file or catalog configuration supplied to the constructor. Call this after schema setup; supplying configuration alone does not run a sync. In .NET, a file path takes precedence over an object, and empty initial-config options return null.

runInitialConfigSync(): Promise<ConfigSyncReport | null>

Returns ConfigSyncReport | null: Sync results, or null when no initial configuration was supplied.

Example

const report = await subscrio.runInitialConfigSync();
console.log(report);
Errors (1)
Task<ConfigSyncReport?> RunInitialConfigSyncAsync()

Returns ConfigSyncReport?: Sync results, or null when no initial configuration was supplied.

Example

var report = await subscrio.RunInitialConfigSyncAsync();
Console.WriteLine(report);
Errors (1)

dropSchema

Permanently remove all Subscrio tables and their data. If an administrator passphrase hash is stored, a matching passphrase is required. Without a stored hash, this operation does not require a passphrase.

dropSchema(adminPassphrase?: string): Promise<void>

Parameters

  • adminPassphrase: Optional passphrase. The argument takes precedence over the constructor setting; when omitted, the configured passphrase is used.

Returns No returned value.

Example

// Run only against a disposable database.
await subscrio.dropSchema(process.env.ADMIN_PASSPHRASE);
Errors (1)
  • ValidationError: A stored passphrase hash exists and the supplied passphrase is missing or incorrect.
Task DropSchemaAsync(string? adminPassphrase)

Parameters

  • adminPassphrase: Optional passphrase. The argument takes precedence over the constructor setting; when omitted, the configured passphrase is used.

Returns No returned value.

Example

// Run only against a disposable database.
await subscrio.DropSchemaAsync(
    Environment.GetEnvironmentVariable("ADMIN_PASSPHRASE"));
Errors (1)
  • ValidationException: A stored passphrase hash exists and the supplied passphrase is missing or incorrect.

close

Release database resources when the application finishes using Subscrio. TypeScript closes the shared PostgreSQL pool. In .NET, using and dependency-injection scopes can dispose the instance automatically.

close(): Promise<void>

Returns No returned value.

Example

await subscrio.close();
void Dispose()

Returns No returned value.

Example

subscrio.Dispose();

Data types

For input types, Required means the caller must supply the property. Defaults apply when an optional property is omitted.

SubscrioConfig

Constructor configuration. Only the database connection is required.

Field Type Required Default Meaning
database DatabaseConfig Yes None Database connection and provider settings.
adminPassphrase string No None Default passphrase for schema installation and deletion.
stripe StripeConfig No None Stripe API and webhook credentials.
logging LoggingConfig No None Reserved logging configuration; currently does not control emitted diagnostics.
initialConfig InitialConfigSync No None Catalog configuration applied by the initial-config method.
hooks HooksConfig No None Hook handlers registered during construction. See Hooks.
clock Clock No System clock Clock used for usage periods, credits, and time-based decisions.
Property Type Required Default Meaning
Database DatabaseConfig Yes None Database connection and provider settings.
AdminPassphrase string? No null Default passphrase for schema installation and deletion.
Stripe StripeConfig? No null Stripe API and webhook credentials.
Logging LoggingConfig? No null Reserved logging configuration; currently does not control emitted diagnostics.
InitialConfig InitialConfigOptions? No null Catalog configuration applied by the initial-config method.
Hooks SubscrioHooksOptions? No null Hook handlers registered during construction. See Hooks.
Clock IClock? No System clock Clock used for usage periods, credits, and time-based decisions.

DatabaseConfig

Database connection settings. In TypeScript, this is the nested SubscrioConfig["database"] object.

Field Type Required Default Meaning
connectionString string Yes None PostgreSQL connection URI.
ssl boolean No Unset When true, enables TLS and certificate verification.
poolSize number No 10 Maximum PostgreSQL pool size.
databaseType 'postgres' | 'sqlserver' No Detected Dialect hint; selecting SQL Server throws at construction.
Property Type Required Default Meaning
ConnectionString string Yes None PostgreSQL or SQL Server provider connection string.
Ssl bool No false Enables the provider SSL settings.
PoolSize int No 10 Configuration hint; currently not applied by the .NET initializer. Configure pooling in the connection string.
DatabaseType DatabaseType No PostgreSQL Provider: PostgreSQL or SqlServer, from Subscrio.Core.Domain.ValueObjects.

StripeConfig

Optional Stripe configuration. See Stripe Integration for event verification and checkout.

Field Type Required Default Meaning
secretKey string Yes None Secret API key.
webhookSecret string No None Endpoint signing secret required to verify incoming webhooks.
Property Type Required Default Meaning
SecretKey string Yes None Secret API key.
WebhookSecret string? No null Endpoint signing secret required by ConstructStripeEvent.

LoggingConfig

Reserved logging settings. The current library does not emit or filter diagnostics using this configuration.

Field Type Required Default Meaning
level 'debug' | 'info' | 'warn' | 'error' Yes None Reserved level value.
Property Type Required Default Meaning
Level LogLevel No Info Debug, Info, Warn, or Error.

InitialConfigSync

Configuration applied by the initial-config method after schema setup. In TypeScript, supply either the file variant or the JSON variant.

Field Type Required Default Meaning
type 'file' | 'json' Yes None Selects a local file or an in-memory catalog.
filePath string When file None JSON file to read.
config ConfigSyncDto When json None Catalog to synchronize.
Property Type Required Default Meaning
FilePath string? No null JSON file to read; takes precedence when nonblank.
Config ConfigSyncDto No null Catalog to synchronize when no file path is supplied.

Clock

Optional time provider for deterministic application behavior and tests.

Field Type Required Default Meaning
now() () => Date Yes None Returns the current time.
Property Type Required Default Meaning
UtcNow DateTime Yes None Read-only current UTC time, from Subscrio.Core.Application.DTOs.IClock.

Subscrio objects

The instance exposes the following objects. Use these public access paths rather than constructing their implementation classes.

Property Purpose
features Define reusable features.
addons Define optional subscription packages.
products Group features and plans.
plans Define subscription offerings and feature values.
billingCycles Define billing cadence.
customers Manage customer records.
subscriptions Manage subscriptions, overrides, and add-on attachments.
featureChecker Resolve feature access.
metering Record usage against feature limits.
credits Manage credit wallets and spending.
hooks Register operation callbacks.
configSync Synchronize catalog configuration.
stripe Process Stripe events and create checkout sessions.
Property Purpose
Features Define reusable features.
Addons Define optional subscription packages.
Products Group features and plans.
Plans Define subscription offerings and feature values.
BillingCycles Define billing cadence.
Customers Manage customer records.
Subscriptions Manage subscriptions, overrides, and add-on attachments.
FeatureChecker Resolve feature access.
Metering Record usage against feature limits.
Credits Manage credit wallets and spending.
Hooks Register operation callbacks.
ConfigSync Synchronize catalog configuration.
Stripe Process Stripe events and create checkout sessions.

The supported application surface includes these objects, their configuration and DTO types, public errors, hooks, and related enums. Lower-level exports such as repositories and persistence records are not stable application contracts. The supported TypeScript conversion helper is documented under Feature Checker.