@graphql-codegen/flutter-freezed
Version:
GraphQL Code Generator plugin to generate Freezed models from your GraphQL schema
229 lines (228 loc) • 11.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultFreezedConfig = exports.DefaultFreezedPluginConfig = exports.FreezedFactoryBlockRepository = exports.FreezedConfigValue = exports.addFreezedImportStatements = exports.transformCustomDecorators = exports.getCustomDecorators = exports.getFreezedConfigValue = exports.transformDefinition = void 0;
const index_js_1 = require("./freezed-declaration-blocks/index.js");
function transformDefinition(config, freezedFactoryBlockRepository, node) {
var _a;
// ignore these...
if (['Query', 'Mutation', 'Subscription', ...((_a = config === null || config === void 0 ? void 0 : config.ignoreTypes) !== null && _a !== void 0 ? _a : [])].includes(node.name.value)) {
return '';
}
return new index_js_1.FreezedDeclarationBlock(config, freezedFactoryBlockRepository, node).init();
}
exports.transformDefinition = transformDefinition;
/**
* returns the value of the FreezedConfig option
* for a specific type if given typeName
* or else fallback to the global FreezedConfig value
*/
function getFreezedConfigValue(option, config, typeName) {
var _a, _b, _c, _d, _e;
if (typeName) {
return (_d = (_c = (_b = (_a = config === null || config === void 0 ? void 0 : config.typeSpecificFreezedConfig) === null || _a === void 0 ? void 0 : _a[typeName]) === null || _b === void 0 ? void 0 : _b.config) === null || _c === void 0 ? void 0 : _c[option]) !== null && _d !== void 0 ? _d : getFreezedConfigValue(option, config);
}
return (_e = config === null || config === void 0 ? void 0 : config.globalFreezedConfig) === null || _e === void 0 ? void 0 : _e[option];
}
exports.getFreezedConfigValue = getFreezedConfigValue;
/**
* @description filters the customDirectives to return those that are applied on a list of blocks
*/
function getCustomDecorators(config, appliesOn, nodeName, fieldName) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const filteredCustomDecorators = {};
const globalCustomDecorators = (_b = (_a = config === null || config === void 0 ? void 0 : config.globalFreezedConfig) === null || _a === void 0 ? void 0 : _a.customDecorators) !== null && _b !== void 0 ? _b : {};
let customDecorators = { ...globalCustomDecorators };
if (nodeName) {
const typeConfig = (_c = config === null || config === void 0 ? void 0 : config.typeSpecificFreezedConfig) === null || _c === void 0 ? void 0 : _c[nodeName];
const typeSpecificCustomDecorators = (_e = (_d = typeConfig === null || typeConfig === void 0 ? void 0 : typeConfig.config) === null || _d === void 0 ? void 0 : _d.customDecorators) !== null && _e !== void 0 ? _e : {};
customDecorators = { ...customDecorators, ...typeSpecificCustomDecorators };
if (fieldName) {
const fieldSpecificCustomDecorators = (_h = (_g = (_f = typeConfig === null || typeConfig === void 0 ? void 0 : typeConfig.fields) === null || _f === void 0 ? void 0 : _f[fieldName]) === null || _g === void 0 ? void 0 : _g.customDecorators) !== null && _h !== void 0 ? _h : {};
customDecorators = { ...customDecorators, ...fieldSpecificCustomDecorators };
}
}
Object.entries(customDecorators).forEach(([key, value]) => {
var _a;
return (_a = value === null || value === void 0 ? void 0 : value.applyOn) === null || _a === void 0 ? void 0 : _a.forEach(a => {
if (appliesOn.includes(a)) {
filteredCustomDecorators[key] = value;
}
});
});
return filteredCustomDecorators;
}
exports.getCustomDecorators = getCustomDecorators;
function transformCustomDecorators(customDecorators, node, field) {
var _a, _b;
let result = [];
result = [
...result,
...((_a = node === null || node === void 0 ? void 0 : node.directives) !== null && _a !== void 0 ? _a : [])
.concat((_b = field === null || field === void 0 ? void 0 : field.directives) !== null && _b !== void 0 ? _b : [])
// extract only the directives whose names were specified as keys
// and have values that not undefined or null in the customDecorator record
.filter(d => {
var _a;
const key = d.name.value;
const value = (_a = customDecorators[key]) !== null && _a !== void 0 ? _a : customDecorators[`@${key}`];
if (value && value.mapsToFreezedAs !== 'custom') {
return true;
}
return false;
})
// transform each directive to string
.map(d => directiveToString(d, customDecorators)),
];
// for decorators that mapsToFreezedAs === 'custom'
Object.entries(customDecorators).forEach(([key, value]) => {
if (value.mapsToFreezedAs === 'custom') {
const args = value === null || value === void 0 ? void 0 : value.arguments;
// if the custom directives have arguments,
if (args && args !== []) {
// join them with a comma in the parenthesis
result = [...result, `${key}(${args.join(', ')})\n`];
}
else {
// else return the customDecorator key just as it is
result = [...result, key + '\n'];
}
}
});
return result;
}
exports.transformCustomDecorators = transformCustomDecorators;
/**
* transforms the directive into a decorator array
* this decorator array might contain a `final` string which would be filtered out
* and used to mark the parameter block as final
*/
function directiveToString(directive, customDecorators) {
var _a, _b, _c, _d, _e;
const key = directive.name.value;
const value = customDecorators[key];
if (value.mapsToFreezedAs === 'directive') {
// get the directive's arguments
const directiveArgs = (_a = directive === null || directive === void 0 ? void 0 : directive.arguments) !== null && _a !== void 0 ? _a : [];
// extract the directive's argument using the template index: ["$0", "$1", ...]
// specified in the customDecorator.arguments array
const args = (_b = value === null || value === void 0 ? void 0 : value.arguments) === null || _b === void 0 ? void 0 : _b.filter(a => directiveArgs[argToInt(a)]).map(a => directiveArgs[argToInt(a)]).map(a => `${a.name}: ${a.value}`);
// if the args is not empty
if (args !== []) {
// returns "@directiveName(argName: argValue, argName: argValue ...)"
return `@${directive.name.value}(${args === null || args === void 0 ? void 0 : args.join(', ')})\n`;
}
}
else if (value.mapsToFreezedAs === '@Default') {
const defaultValue = (_c = directive === null || directive === void 0 ? void 0 : directive.arguments) === null || _c === void 0 ? void 0 : _c[argToInt((_e = (_d = value === null || value === void 0 ? void 0 : value.arguments) === null || _d === void 0 ? void 0 : _d[0]) !== null && _e !== void 0 ? _e : '0')];
if (defaultValue) {
return `@Default(value: ${defaultValue})\n`;
}
}
// returns either "@deprecated" || "final".
// `final` to be filtered from the decorators array when applying the decorators
return value.mapsToFreezedAs + '\n';
}
/** transforms string template: "$0" into an integer: 1 */
function argToInt(arg) {
var _a;
const parsedIndex = Number.parseInt((_a = arg.replace('$', '').trim()) !== null && _a !== void 0 ? _a : '0'); // '$1 => 1
return parsedIndex ? parsedIndex : 0;
}
/** returns freezed import statements */
function addFreezedImportStatements(fileName) {
return [
"import 'package:freezed_annotation/freezed_annotation.dart';\n",
"import 'package:flutter/foundation.dart';\n\n",
`part ${fileName.replace(/\.dart/g, '')}.dart;\n`,
`part '${fileName.replace(/\.dart/g, '')}.g.dart';\n\n`,
].join('');
}
exports.addFreezedImportStatements = addFreezedImportStatements;
/** a class variant of the getFreezedConfigValue helper function
*
* returns the value of the FreezedConfig option
* for a specific type if given typeName
* or else fallback to the global FreezedConfig value
*/
class FreezedConfigValue {
constructor(_config, _typeName) {
this._config = _config;
this._typeName = _typeName;
this._config = _config;
this._typeName = _typeName;
}
/**
* returns the value of the FreezedConfig option
* for a specific type if given typeName
* or else fallback to the global FreezedConfig value
*/
get(option) {
return getFreezedConfigValue(option, this._config, this._typeName);
}
}
exports.FreezedConfigValue = FreezedConfigValue;
/**
* stores an instance of FreezedFactoryBlock using the node names as the key
* and returns that instance when replacing tokens
* */
class FreezedFactoryBlockRepository {
constructor() {
this._store = {};
}
get(key) {
return this._store[key];
}
register(key, value) {
this._store[key] = value;
return value;
}
retrieve(key, appliesOn, name, typeName) {
if (this._store[key]) {
return (this._store[key]
.setDecorators(appliesOn, key)
.setKey(key)
.setName(name)
.setNamedConstructor(typeName)
.init()
.toString() + '\n');
}
return '';
}
}
exports.FreezedFactoryBlockRepository = FreezedFactoryBlockRepository;
/** initializes a FreezedPluginConfig with the defaults values */
class DefaultFreezedPluginConfig {
constructor(config = {}) {
var _a, _b, _c, _d, _e, _f;
Object.assign(this, {
camelCasedEnums: (_a = config.camelCasedEnums) !== null && _a !== void 0 ? _a : true,
customScalars: (_b = config.customScalars) !== null && _b !== void 0 ? _b : {},
fileName: (_c = config.fileName) !== null && _c !== void 0 ? _c : 'app_models',
globalFreezedConfig: { ...new DefaultFreezedConfig(), ...((_d = config.globalFreezedConfig) !== null && _d !== void 0 ? _d : {}) },
typeSpecificFreezedConfig: (_e = config.typeSpecificFreezedConfig) !== null && _e !== void 0 ? _e : {},
ignoreTypes: (_f = config.ignoreTypes) !== null && _f !== void 0 ? _f : [],
});
}
}
exports.DefaultFreezedPluginConfig = DefaultFreezedPluginConfig;
/** initializes a FreezedConfig with the defaults values */
class DefaultFreezedConfig {
constructor() {
Object.assign(this, {
alwaysUseJsonKeyName: false,
copyWith: undefined,
customDecorators: {},
defaultUnionConstructor: true,
equal: undefined,
fromJsonToJson: true,
immutable: true,
makeCollectionsUnmodifiable: undefined,
mergeInputs: [],
mutableInputs: true,
privateEmptyConstructor: true,
unionKey: undefined,
unionValueCase: undefined,
});
}
}
exports.DefaultFreezedConfig = DefaultFreezedConfig;