@via-profit/ability - Type generator
The package contains the AbilityTypeGenerator module for automatically generating TypeScript types from described policies. This provides strict typing and autocomplete when working with the DSL and resolver.
📚 Related documents:
What generated types provide
The type generator parses policies and creates types that should be passed to class generics so that your IDE and linter can catch errors and typos. This is optional: if you do not need generated types, you can skip it.
The resulting types can be used for strict resource typing when calling resolver.resolve() and resolver.enforce().
What is generated
| Type | Purpose | Usage example |
|---|---|---|
Resources | Type of all resources (subjects) available in the DSL | document.*, order.*, user.* |
Environment | Type of environment data in the DSL | env.time.*, env.ip.*, env.user.* |
PolicyTags | Union type of all policy tags | "admin" | "user" | "moderator" |
Generating types from policies
import { AbilityTypeGenerator } from '@via-profit/ability';
import { policies } from './policies';
// Create a generator and generate types
const generator = new AbilityTypeGenerator(policies);
const typeDefs = generator.generateTypeDefs();
// Save to a file
fs.writeFileSync('ability.types.ts', typeDefs, { encoding: 'utf-8' });Generated file contents
// Automatically generated by via-profit/ability
// Do not edit manually
export type Resources = {
/**
* Permission: *
* Effects: permit
* Policies:
* - permit p_c2cc4b23c2 "Everything is available to the developer"
*/
['*']: {
readonly accessToken: {
readonly roles: readonly string[] | null | undefined
} | null | undefined;
} | null | undefined;
/**
* Permission: account.login
* Effects: permit
* Policies:
* - permit p_c2cc4b23c2 "Everything is available to the developer"
* - permit p_d49e4bbf14 "Only the administrator and the account owner can see the account login"
*/
['account.login']: {
readonly accessToken: {
readonly roles: readonly string[] | null | undefined
} | null | undefined;
readonly account: {
readonly entity: {
readonly id: null | unknown
} | null | undefined;
} | null | undefined;
} | null | undefined;
}
// Environment data types
export type Environment = {
['order.read']: {
time: {
hour: number;
minute: number;
dayOfWeek: number;
};
ip: {
address: string;
country: string;
};
}
};
// Policy tag types
export type PolicyTags = "admin" | "moderator" | "user";Using generated types
After generating types, you can use them with AbilityDSLParser and AbilityResolver, as well as with any class that has the corresponding generic:
import { AbilityDSLParser, AbilityResolver, DenyOverridesStrategy } from '@via-profit/ability';
import type { Resources, Environment, PolicyTags } from './ability.types';
// DSL
const dsl = `
@name "Reading documents"
permit permission.document.read if all:
document.ownerId equals user.id
document.status in ["published", "archived"]
document.views greater than 10
env.time.hour less than 18
`;
// Parse typed DSL
const policies = new AbilityDSLParser<Resources, Environment, PolicyTags>(dsl).parse();
// Create a typed resolver
const resolver = new AbilityResolver(policies, DenyOverridesStrategy);
// Use autocomplete and type checking
resolver.enforce('document.read', {
document: {
ownerId: 'user-123', // ✅ unknown (the right side is a path, so the type is not derived)
status: 'published', // ✅ string
views: 42, // ✅ number
},
user: { id: 'user-123' },
}, {
time: { hour: 14 }, // ✅ number
});
// ❌ Compilation error: views must be a number
resolver.enforce('document.read', {
document: {
status: 'archived',
views: '42', // ❌ Type error: string is not assignable to number
},
user: { id: 'user-123' },
}, {
time: { hour: 14 },
});How types are derived:
| Rule | Field type |
|---|---|
equals / not equals with a literal | the literal type (string, number…) |
in / not in with an array | the type of the array items |
>, <, >=, <= | number |
contains, contains all, contains any | an array of the value type |
length …, is empty, is not empty | string | readonly unknown[] |
starts with, ends with | string |
a path on the right side (user.id, env.ip) | unknown for both sides |
Fields from policies with a wildcard key (order.*, *.create) are added to the types of all matching concrete keys (order.update, order.create), because the resolver checks these policies together.
DSL integration
For convenient DSL usage, the package provides the ability tagged template function:
import { ability } from '@via-profit/ability';
import type { Resources, Environment, PolicyTags } from './ability.types';
// Fully typed DSL with autocomplete
const policies = ability<Resources, Environment, PolicyTags>`
@name "Order management"
permit permission.orders.read if any:
order.author.id equals user.id
env.time.hour less than 18
@name "Administration"
@tags admin
permit permission.orders.* if all:
user.role equals "admin"
`;
const resolver = new AbilityResolver(policies, DenyOverridesStrategy);TipTIP The
abilityfunction is a tagged template that automatically parses the DSL and returns an array of correctly typed policies.
Automating generation
Add this to package.json:
{
"scripts": {
"generate:ability": "node scripts/generate-ability-types.js"
}
}// scripts/generate-ability-types.js
const fs = require('node:fs');
const path = require('node:path');
const { AbilityDSLParser, AbilityTypeGenerator } = require('@via-profit/ability');
const dslPath = path.resolve(__dirname, '../src/ability');
const outputFile = path.resolve(__dirname, '../src/ability/ability.types.ts');
// Collect all DSL files
const dslFiles = fs.readdirSync(dslPath).filter(f => f.endsWith('.dsl'));
let dsl = '';
for (const file of dslFiles) {
dsl += fs.readFileSync(path.join(dslPath, file), 'utf-8') + '\n';
}
// Parse and generate types
const policies = new AbilityDSLParser(dsl).parse();
const typeDefs = new AbilityTypeGenerator(policies).generateTypeDefs();
fs.writeFileSync(outputFile, typeDefs, 'utf-8');
console.log('✅ Types generated successfully!');Frequently asked questions
Do I need to generate types every time policies change?
Yes. Types should stay synchronized with policies. It is recommended to add automatic generation to pre-commit hooks or watch mode.
How do I update types on the client?
If you use an artifact HTTP server, the client can download fresh types on request. Alternatively, copy the generated file into the client project.