@adonis-agora/media
Version:
Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a
152 lines • 6.95 kB
JavaScript
/**
* Zero-config `topology: 'tenant'`: when `@adonis-agora/authkit-client` is booted in the app with its
* `service` configured, its `'authkit.client'` binding answers `tenantOf(resource)` with this app's
* control-plane URL (discovered from the issuer), a service token for the resource (cached, with
* `reset()`) and its partition. Detected by shape, never imported: no dependency on authkit-client.
*
* Merge rule: `{ ...auto, ...config.tenant }`, field by field. Anything set explicitly wins, and
* `tenant: { auto: false }` turns the detection off.
*/
/**
* `@adonis-agora/authkit-client`'s `'authkit.client'` binding when it is booted here AND has
* `tenantOf` (1.1+); an older authkit-client, or none, is `undefined`. A binding that is registered
* but fails to build comes back as `error`.
*/
export async function authkitTenantClientOf(container) {
if (!container || typeof container.hasBinding !== 'function')
return {};
if (!container.hasBinding('authkit.client'))
return {};
let client;
try {
client = await container.make('authkit.client');
}
catch (error) {
return { error: `resolving 'authkit.client' failed: ${messageOf(error)}` };
}
const candidate = client;
return candidate && typeof candidate.tenantOf === 'function'
? { client: candidate }
: {};
}
const messageOf = (error) => error instanceof Error ? error.message : String(error);
const present = (value) => value !== undefined && value !== null && value !== '';
/**
* Fills the missing `fields` of `explicit` from `authkit.client.tenantOf(resource)`. `tenantOf` is
* only called when a field is missing, so an app with every field explicit (or with authkit-client
* for login only, and no `service`) is unaffected.
*/
export async function resolveTenantIdentity(explicit, options) {
const base = { ...(explicit ?? {}) };
const sources = {};
const wanted = options.fields.filter((field) => {
if (present(base[field])) {
sources[field] = 'explicit';
return false;
}
return true;
});
const found = wanted.length > 0 && base.auto !== false ? await authkitTenantClientOf(options.container) : {};
const client = found.client;
let authkitError = found.error;
if (client && wanted.length > 0) {
let auto;
try {
// authkit-client 1.1 answers synchronously and throws `TenantOfConfigError`
// (`E_AUTHKIT_SERVICE_NOT_CONFIGURED`) without `service`: authkit then counts as absent, and
// its message joins the boot error. Awaited so an async `tenantOf` works too.
auto = await client.tenantOf(options.resource);
}
catch (error) {
authkitError = messageOf(error);
}
if (auto) {
for (const field of wanted) {
const value = auto[field];
if (present(value)) {
base[field] = value;
sources[field] = 'authkit-client (auto)';
}
}
}
}
const missing = wanted.filter((field) => sources[field] === undefined);
for (const field of missing)
sources[field] = 'missing';
return {
tenant: base,
sources,
missing,
authkit: client !== undefined,
...(authkitError !== undefined ? { authkitError } : {}),
};
}
/**
* The boot error for a tenant with fields nothing supplied: names them, and both fixes.
*/
export function missingTenantFieldsMessage(input) {
const fields = input.missing.map((field) => `tenant.${field}`).join(', ');
const cause = input.authkitError
? ` authkit-client could not supply them (${input.authkitError}).`
: input.autoDisabled
? ' `tenant.auto` is false, so authkit-client does not supply them.'
: '';
return `[@adonis-agora/${input.lib}] topology 'tenant' needs ${fields}.${cause} Fix: configure @adonis-agora/authkit-client's \`service: { name, clientId, clientSecret }\` (config/authkit_client.ts), which supplies them for ${input.resource}, or set \`${input.explicitForm}\` in ${input.configFile}.`;
}
/** The marker between a boot error's problem and its fix (see {@link missingTenantFieldsMessage}). */
const FIX_MARKER = ' Fix: configure @adonis-agora/authkit-client';
/** A boot error split for a doctor result: the problem, and the fix when the message carries one. */
export function splitTenantError(text) {
const at = text.lastIndexOf(FIX_MARKER);
if (at === -1)
return { message: text };
return { message: text.slice(0, at), fix: text.slice(at + ' Fix: '.length) };
}
/**
* One doctor line of where each field came from, grouped by source:
* `tenant url/token/partition: authkit-client (auto)`, or
* `tenant url: explicit; token/partition: authkit-client (auto)`.
*/
export function describeTenantSources(sources, order = ['url', 'token', 'partition']) {
const groups = new Map();
for (const field of order) {
const source = sources[field];
if (source === undefined)
continue;
groups.set(source, [...(groups.get(source) ?? []), field]);
}
return `tenant ${[...groups.entries()].map(([source, fields]) => `${fields.join('/')}: ${source}`).join('; ')}`;
}
/* -------------------------------------------------------------------------------------------- */
/* media */
/* -------------------------------------------------------------------------------------------- */
/** The resource media's tenant tokens and control-plane URL are for. */
export const MEDIA_TENANT_RESOURCE = 'urn:agora:media';
const MEDIA_TENANT_FIELDS = ['url', 'token', 'partition'];
/**
* `config` with `tenant.url`/`token`/`partition` filled in from `authkit.client.tenantOf` where
* they are missing (explicit fields win). Anything else than a tenant comes back unchanged. Throws
* the boot error when a field resolves from neither.
*/
export async function resolveMediaTenant(config, container) {
if (config.topology !== 'tenant')
return { config };
const resolved = await resolveTenantIdentity(config.tenant, {
container,
resource: MEDIA_TENANT_RESOURCE,
fields: MEDIA_TENANT_FIELDS,
});
if (resolved.missing.length > 0) {
throw new Error(missingTenantFieldsMessage({
lib: 'media',
configFile: 'config/media.ts',
resource: MEDIA_TENANT_RESOURCE,
missing: resolved.missing,
explicitForm: 'tenant: { url, token, partition }',
authkitError: resolved.authkitError,
autoDisabled: config.tenant?.auto === false,
}));
}
return { config: { ...config, tenant: resolved.tenant }, sources: resolved.sources };
}
//# sourceMappingURL=authkit_tenant.js.map