arri 0.0.5 → 0.0.6

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.
@@ -1,16 +1,14 @@
1
- import { u as unflattenObject, p as pascalCase, i as isProcedureDefinition, a as isJsonSchemaScalarType, b as isJsonSchemaNullType, c as isJsonSchemaObject, d as isJsonSchemaEnum, e as isJsonSchemaArray, f as camelCase } from '../shared/arri.215ad025.mjs';
2
1
  import { createRequire, builtinModules } from 'module';
3
2
  import { fileURLToPath, pathToFileURL, URL } from 'url';
4
- import path6, { dirname } from 'path';
3
+ import require$$0, { dirname } from 'path';
5
4
  import process4 from 'process';
6
- import os from 'os';
5
+ import require$$0$1 from 'os';
7
6
  import tty from 'tty';
8
- import fs$1, { realpathSync, statSync, Stats, writeFileSync } from 'fs';
7
+ import fs$1, { realpathSync, statSync, Stats } from 'fs';
9
8
  import assert4 from 'assert';
10
9
  import fs from 'fs/promises';
11
10
  import v8 from 'v8';
12
11
  import { format, inspect } from 'util';
13
- import { execSync } from 'child_process';
14
12
 
15
13
  const require$1 = createRequire(import.meta.url);
16
14
  const __filename$1 = fileURLToPath(import.meta.url);
@@ -21403,7 +21401,7 @@ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
21403
21401
  return min;
21404
21402
  }
21405
21403
  if (process4.platform === "win32") {
21406
- const osRelease = os.release().split(".");
21404
+ const osRelease = require$$0$1.release().split(".");
21407
21405
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
21408
21406
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
21409
21407
  }
@@ -25999,10 +25997,10 @@ var partition_default = partition2;
25999
25997
  var import_editorconfig = __toESM(require_src(), 1);
26000
25998
  var import_editorconfig_to_prettier = __toESM(require_editorconfig_to_prettier(), 1);
26001
25999
  var MARKERS = [".git", ".hg"];
26002
- var markerExists = (directory) => MARKERS.some((mark) => fs$1.existsSync(path6.join(directory, mark)));
26000
+ var markerExists = (directory) => MARKERS.some((mark) => fs$1.existsSync(require$$0.join(directory, mark)));
26003
26001
  function findProjectRoot(directory) {
26004
26002
  while (!markerExists(directory)) {
26005
- const parentDirectory = path6.resolve(directory, "..");
26003
+ const parentDirectory = require$$0.resolve(directory, "..");
26006
26004
  if (parentDirectory === directory) {
26007
26005
  break;
26008
26006
  }
@@ -26015,7 +26013,7 @@ var find_project_root_default = findProjectRoot;
26015
26013
  // src/config/resolve-editorconfig.js
26016
26014
  async function loadEditorConfig(filePath) {
26017
26015
  const editorConfig = await import_editorconfig.default.parse(filePath, {
26018
- root: find_project_root_default(path6.dirname(path6.resolve(filePath)))
26016
+ root: find_project_root_default(require$$0.dirname(require$$0.resolve(filePath)))
26019
26017
  });
26020
26018
  const config = (0, import_editorconfig_to_prettier.default)(editorConfig);
26021
26019
  if (config) {
@@ -26392,7 +26390,7 @@ var package_json_reader_default = reader;
26392
26390
  function read(jsonPath) {
26393
26391
  try {
26394
26392
  const string = fs$1.readFileSync(
26395
- path6.toNamespacedPath(path6.join(path6.dirname(jsonPath), "package.json")),
26393
+ require$$0.toNamespacedPath(require$$0.join(require$$0.dirname(jsonPath), "package.json")),
26396
26394
  "utf8"
26397
26395
  );
26398
26396
  return { string };
@@ -26735,7 +26733,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
26735
26733
  if (!preserveSymlinks) {
26736
26734
  const real = realpathSync(filePath);
26737
26735
  const { search, hash } = resolved;
26738
- resolved = pathToFileURL(real + (filePath.endsWith(path6.sep) ? "/" : ""));
26736
+ resolved = pathToFileURL(real + (filePath.endsWith(require$$0.sep) ? "/" : ""));
26739
26737
  resolved.search = search;
26740
26738
  resolved.hash = hash;
26741
26739
  }
@@ -27534,7 +27532,7 @@ async function resolveConfig(filePath, options8) {
27534
27532
  };
27535
27533
  if (Array.isArray(merged.plugins)) {
27536
27534
  merged.plugins = merged.plugins.map(
27537
- (value) => typeof value === "string" && value.startsWith(".") ? path6.resolve(path6.dirname(result.filepath), value) : value
27535
+ (value) => typeof value === "string" && value.startsWith(".") ? require$$0.resolve(require$$0.dirname(result.filepath), value) : value
27538
27536
  );
27539
27537
  }
27540
27538
  return merged;
@@ -27548,7 +27546,7 @@ function mergeOverrides(configResult, filePath) {
27548
27546
  const { config, filepath: configPath } = configResult || {};
27549
27547
  const { overrides, ...options8 } = config || {};
27550
27548
  if (filePath && overrides) {
27551
- const relativeFilePath = path6.relative(path6.dirname(configPath), filePath);
27549
+ const relativeFilePath = require$$0.relative(require$$0.dirname(configPath), filePath);
27552
27550
  for (const override of overrides) {
27553
27551
  if (pathMatchesGlobs(
27554
27552
  relativeFilePath,
@@ -27594,7 +27592,7 @@ var read_file_default = readFile;
27594
27592
 
27595
27593
  // src/utils/ignore.js
27596
27594
  var createIgnore = import_ignore.default.default;
27597
- var slash = path6.sep === "\\" ? (filepath) => string_replace_all_default(
27595
+ var slash = require$$0.sep === "\\" ? (filepath) => string_replace_all_default(
27598
27596
  /* isOptionalObject*/
27599
27597
  false,
27600
27598
  filepath,
@@ -27616,8 +27614,8 @@ async function createSingleIsIgnoredFunction(ignoreFilePath, withNodeModules) {
27616
27614
  allowRelativePaths: true
27617
27615
  }).add(content);
27618
27616
  return (filepath) => {
27619
- filepath = path6.resolve(filepath);
27620
- const relativePath = ignoreFilePath ? path6.relative(path6.dirname(ignoreFilePath), filepath) : path6.relative(process.cwd(), filepath);
27617
+ filepath = require$$0.resolve(filepath);
27618
+ const relativePath = ignoreFilePath ? require$$0.relative(require$$0.dirname(ignoreFilePath), filepath) : require$$0.relative(process.cwd(), filepath);
27621
27619
  return ignore.ignores(slash(relativePath));
27622
27620
  };
27623
27621
  }
@@ -27667,7 +27665,7 @@ async function getParser(filePath, options8) {
27667
27665
  }
27668
27666
  var get_file_info_default = getFileInfo;
27669
27667
  function importFromDirectory(specifier, directory) {
27670
- return import_from_file_default(specifier, path6.join(directory, "noop.js"));
27668
+ return import_from_file_default(specifier, require$$0.join(directory, "noop.js"));
27671
27669
  }
27672
27670
  var import_from_directory_default = importFromDirectory;
27673
27671
 
@@ -27682,7 +27680,7 @@ var loadPluginFromDirectory = mem(
27682
27680
  );
27683
27681
  var importPlugin = mem(async (name) => {
27684
27682
  try {
27685
- return await import(pathToFileURL(path6.resolve(name)).href);
27683
+ return await import(pathToFileURL(require$$0.resolve(name)).href);
27686
27684
  } catch {
27687
27685
  return import_from_directory_default(name, process.cwd());
27688
27686
  }
@@ -29029,809 +29027,4 @@ var debugApis = {
29029
29027
  printDocToString: withPlugins(printDocToString2)
29030
29028
  };
29031
29029
 
29032
- function defineClientGeneratorPlugin(plugin) {
29033
- return plugin;
29034
- }
29035
-
29036
- let createdModels = [];
29037
- const typescriptClientGenerator = defineClientGeneratorPlugin(
29038
- (options) => ({
29039
- generator: async (def) => {
29040
- if (!options.name) {
29041
- throw new Error("Name is requires");
29042
- }
29043
- if (!options.outputFile) {
29044
- throw new Error("No output file specified");
29045
- }
29046
- const result = await createTypescriptClient(def, options.name);
29047
- writeFileSync(options.outputFile, result);
29048
- },
29049
- options
29050
- })
29051
- );
29052
- async function createTypescriptClient(def, prefix = "Client") {
29053
- createdModels = [];
29054
- const services = unflattenObject(def.procedures);
29055
- const serviceParts = [];
29056
- const modelParts = [];
29057
- Object.keys(services).forEach((key) => {
29058
- const serviceName = pascalCase(`${prefix}_${key}_service`);
29059
- serviceParts.push({
29060
- name: serviceName,
29061
- key,
29062
- content: tsServiceFromServiceDefinition(serviceName, services[key])
29063
- });
29064
- });
29065
- Object.keys(def.models).forEach((key) => {
29066
- const modelName = pascalCase(`${key}`);
29067
- if (!createdModels.includes(modelName)) {
29068
- modelParts.push(tsModelFromDefinition(modelName, def.models[key]));
29069
- createdModels.push(modelName);
29070
- }
29071
- });
29072
- return format2(
29073
- `/* eslint-disable */
29074
- import { arriRequest, ArriRequestError } from 'arri-client';
29075
-
29076
- export class ${prefix} {
29077
- ${serviceParts.map((service) => `${service.key}: ${service.name}`).join("\n")}
29078
- constructor(opts: { baseUrl?: string; headers?: Record<string, string> }) {
29079
- ${serviceParts.map(
29080
- (service) => `this.${service.key} = new ${service.name}(opts);`
29081
- ).join("\n")}
29082
- }
29083
- }
29084
-
29085
- ${serviceParts.map((service) => service.content).join("\n")}
29086
- ${modelParts.join("\n")}`,
29087
- {
29088
- parser: "typescript"
29089
- }
29090
- );
29091
- }
29092
- function tsServiceFromServiceDefinition(name, def) {
29093
- const rpcParts = [];
29094
- const subServiceParts = [];
29095
- Object.keys(def).forEach((key) => {
29096
- const val = def[key];
29097
- if (isProcedureDefinition(val)) {
29098
- rpcParts.push(tsRpcFromProcedureDefinition(key, val));
29099
- return;
29100
- }
29101
- const subServiceName = pascalCase(
29102
- `${name.split("Service").join("")}_${key}_service`
29103
- );
29104
- subServiceParts.push({
29105
- name: subServiceName,
29106
- key,
29107
- content: tsServiceFromServiceDefinition(subServiceName, val)
29108
- });
29109
- });
29110
- return `export class ${name} {
29111
- baseUrl: string;
29112
- headers: Record<string, string>;
29113
- ${subServiceParts.map((service) => `${service.key}: ${service.name};`).join("\n")}
29114
- constructor(opts: { baseUrl?: string; headers?: Record<string, string> }) {
29115
- this.baseUrl = opts.baseUrl ?? "";
29116
- this.headers = opts.headers ?? {};
29117
- ${subServiceParts.map(
29118
- (service) => `this.${service.key} = new ${service.name}(opts);`
29119
- ).join("\n")}
29120
- }
29121
- ${rpcParts.join("\n")}
29122
- }
29123
- ${subServiceParts.map((service) => service.content).join("\n")}`;
29124
- }
29125
- function tsRpcFromProcedureDefinition(name, def) {
29126
- let paramStr = "";
29127
- let responseName = "";
29128
- if (def.params) {
29129
- paramStr = `params: ${def.params}`;
29130
- }
29131
- if (def.response) {
29132
- responseName = def.response;
29133
- }
29134
- return `async ${name}(${paramStr}) {
29135
- return arriRequest<${responseName || "undefined"}>({
29136
- url: \`\${this.baseUrl}${def.path}\`,
29137
- method: '${def.method}',
29138
- ${paramStr.length ? `params,` : ""}
29139
- headers: this.headers,
29140
- });
29141
- }`;
29142
- }
29143
- function tsModelFromDefinition(name, def) {
29144
- const fieldParts = [];
29145
- const subModelParts = [];
29146
- Object.keys(def.properties ?? {}).forEach((key) => {
29147
- const isOptional = !def.required?.includes(key);
29148
- const prop = def.properties?.[key];
29149
- const keyPart = isOptional ? `${key}?` : key;
29150
- if (isJsonSchemaScalarType(prop)) {
29151
- fieldParts.push(
29152
- tsInterfaceScalarField(key, prop, isOptional) ?? ""
29153
- );
29154
- return;
29155
- }
29156
- if (isJsonSchemaNullType(prop)) {
29157
- switch (prop.type) {
29158
- case "null":
29159
- fieldParts.push(`${keyPart}: null;`);
29160
- break;
29161
- case "undefined":
29162
- fieldParts.push(`${keyPart}: undefined`);
29163
- break;
29164
- }
29165
- return;
29166
- }
29167
- if (isJsonSchemaObject(prop)) {
29168
- const subModelName = prop.$id ?? pascalCase(`${name}_${key}`);
29169
- if (!createdModels.includes(subModelName)) {
29170
- const content = tsModelFromDefinition(
29171
- subModelName,
29172
- prop
29173
- );
29174
- subModelParts.push(content);
29175
- }
29176
- fieldParts.push(`${keyPart}: ${subModelName};`);
29177
- return;
29178
- }
29179
- if (isJsonSchemaEnum(prop)) {
29180
- const vals = prop.anyOf.map(
29181
- (opt) => opt.type === "string" ? `'${opt.const}'` : `${opt.const}`
29182
- );
29183
- fieldParts.push(`${keyPart}: ${vals.join(" | ")};`);
29184
- return;
29185
- }
29186
- if (isJsonSchemaArray(prop)) {
29187
- if (isJsonSchemaScalarType(prop.items)) {
29188
- const part = tsInterfaceScalarField(
29189
- key,
29190
- prop.items,
29191
- isOptional
29192
- ).replace(";", "[];");
29193
- fieldParts.push(part);
29194
- return;
29195
- }
29196
- if (isJsonSchemaNullType(prop.items)) {
29197
- if (prop.items.type === "null") {
29198
- fieldParts.push(`${keyPart}: null[]`);
29199
- return;
29200
- }
29201
- fieldParts.push(`${keyPart}: undefined[]`);
29202
- return;
29203
- }
29204
- if (isJsonSchemaObject(prop.items)) {
29205
- const subModelName = prop.items.$id ?? pascalCase(`${name}_${key}_item`);
29206
- if (!createdModels.includes(subModelName)) {
29207
- subModelParts.push(
29208
- tsModelFromDefinition(subModelName, prop.items)
29209
- );
29210
- }
29211
- fieldParts.push(`${keyPart}: ${subModelName}[];`);
29212
- }
29213
- }
29214
- });
29215
- return `export interface ${name} {
29216
- ${fieldParts.join("\n")}
29217
- }
29218
- ${subModelParts.join("\n")}`;
29219
- }
29220
- function tsInterfaceScalarField(key, prop, isOptional = false) {
29221
- const keyPart = isOptional ? `${key}?` : key;
29222
- switch (prop.type) {
29223
- case "string":
29224
- return `${keyPart}: string;`;
29225
- case "bigint":
29226
- return `${keyPart}: bigint;`;
29227
- case "Date":
29228
- return `${keyPart}: Date;`;
29229
- case "boolean":
29230
- return `${keyPart}: boolean;`;
29231
- case "integer":
29232
- return `/**
29233
- * must be an integer
29234
- */
29235
- ${keyPart}: number;`;
29236
- case "number":
29237
- return `${keyPart}: number;`;
29238
- }
29239
- }
29240
-
29241
- const dartClientGenerator = defineClientGeneratorPlugin(
29242
- (options) => {
29243
- return {
29244
- generator: async (def) => {
29245
- if (!options.clientName) {
29246
- throw new Error(
29247
- 'Missing "clientName" cannot generate dart client'
29248
- );
29249
- }
29250
- if (!options.outputFile) {
29251
- throw new Error(
29252
- 'Missing "outputFile" cannot generate dart client'
29253
- );
29254
- }
29255
- const result = createDartClient(def, options.clientName);
29256
- writeFileSync(options.outputFile, result);
29257
- execSync(`dart format ${options.outputFile}`);
29258
- },
29259
- options
29260
- };
29261
- }
29262
- );
29263
- const generatedModels = [];
29264
- function createDartClient(appDef, prefix = "Client") {
29265
- const { models, procedures } = appDef;
29266
- const serviceParts = [];
29267
- const services = unflattenObject(procedures);
29268
- Object.keys(services).forEach((k) => {
29269
- const service = services[k];
29270
- const serviceName = pascalCase(`$_${prefix}_${k}_service`);
29271
- serviceParts.push({
29272
- name: serviceName,
29273
- key: k,
29274
- content: dartServiceFromServiceDefinition(
29275
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
29276
- serviceName,
29277
- service,
29278
- prefix
29279
- )
29280
- });
29281
- });
29282
- const endpoints = {};
29283
- Object.keys(procedures).forEach((key) => {
29284
- const rpc = procedures[key];
29285
- endpoints[rpc.path] = rpc.method;
29286
- });
29287
- const modelParts = [];
29288
- Object.keys(models).forEach((key) => {
29289
- const model = models[key];
29290
- const typeName = `${prefix}${pascalCase(key)}`;
29291
- const objModel = model;
29292
- if (!generatedModels.includes(typeName)) {
29293
- modelParts.push(
29294
- dartModelFromJsonSchema(
29295
- `${prefix}${pascalCase(key)}`,
29296
- objModel
29297
- )
29298
- );
29299
- generatedModels.push(typeName);
29300
- }
29301
- });
29302
- return `// This code was autogenerated by arri. Do not modify directly.
29303
- import "dart:convert";
29304
- import "package:http/http.dart" as http;
29305
- import "package:arri_client/arri_client.dart";
29306
-
29307
- class ${prefix} {
29308
- final String baseUrl;
29309
- final Map<String, String> headers;
29310
- const ${prefix}({
29311
- this.baseUrl = "",
29312
- this.headers = const {},
29313
- });
29314
- ${prefix} withHeaders(Map<String, String> headers) {
29315
- return ${prefix}(
29316
- baseUrl: baseUrl,
29317
- headers: headers,
29318
- );
29319
- }
29320
- ${serviceParts.map(
29321
- (service) => `${service.name} get ${service.key} {
29322
- return ${service.name}(
29323
- baseUrl: baseUrl, headers: headers,
29324
- );
29325
- }`
29326
- ).join("\n ")}
29327
- Future<http.Response> rawRequest(
29328
- ${prefix}Endpoints endpoint, {
29329
- Map<String, String>? query,
29330
- dynamic body,
29331
- Map<String, String>? headers,
29332
- Encoding? encoding,
29333
- }) async {
29334
- return arriRequest(
29335
- "$baseUrl\${endpoint.path}",
29336
- method: endpoint.method,
29337
- headers: headers ?? this.headers,
29338
- body: body,
29339
- query: query,
29340
- encoding: encoding,
29341
- );
29342
- }
29343
- }
29344
- ${serviceParts.map((item) => item.content).join("\n")}
29345
- ${modelParts.join("\n")}
29346
-
29347
- enum ${prefix}Endpoints implements Comparable<${prefix}Endpoints>, ArriEndpoint {
29348
- ${Object.keys(endpoints).map(
29349
- (key) => `${camelCase(key.split("/").join("_"))}(
29350
- path: "${key}",
29351
- method: HttpMethod.${endpoints[key]},
29352
- )`
29353
- ).join(",\n ")};
29354
-
29355
- const ${prefix}Endpoints({
29356
- required this.path, required this.method,
29357
- });
29358
- @override
29359
- final String path;
29360
- @override
29361
- final HttpMethod method;
29362
-
29363
- @override
29364
- compareTo(BackendEndpoints other) => name.compareTo(other.name);
29365
- }`;
29366
- }
29367
- function dartServiceFromServiceDefinition(name, def, prefix = "") {
29368
- const rpcParts = [];
29369
- const subServiceParts = [];
29370
- const serviceName = `${name}`;
29371
- Object.keys(def).forEach((key) => {
29372
- const item = def[key];
29373
- if (isProcedureDefinition(item)) {
29374
- let returnType = `Future<String>`;
29375
- let returnTypeName = "String";
29376
- if (item.response) {
29377
- returnType = `Future<${prefix}${item.response}>`;
29378
- returnTypeName = `${prefix}${item.response}`;
29379
- } else {
29380
- returnType = "Future<void>";
29381
- }
29382
- let paramsInput = "";
29383
- if (item.params) {
29384
- paramsInput = `${prefix}${item.params} params`;
29385
- }
29386
- let responseParser = "(body) => body;";
29387
- switch (returnType) {
29388
- case "Future<String>":
29389
- break;
29390
- case "Future<int>":
29391
- responseParser = `(body) => Int.parse(body)`;
29392
- break;
29393
- case "Future<double>":
29394
- responseParser = `(body) => Double.parse(body)`;
29395
- break;
29396
- case "Future<void>":
29397
- responseParser = `(body) {}`;
29398
- break;
29399
- case "Future<bool>":
29400
- responseParser = `(body) {
29401
- switch(body) {
29402
- case "true":
29403
- case "1":
29404
- return true;
29405
- case "false":
29406
- case "0":
29407
- default:
29408
- return false;
29409
- }
29410
- }`;
29411
- break;
29412
- default:
29413
- responseParser = `(body) => ${returnTypeName}.fromJson(json.decode(body))`;
29414
- break;
29415
- }
29416
- rpcParts.push(`${returnType} ${key}(${paramsInput}) {
29417
- return parsedArriRequest(
29418
- "$baseUrl${item.path}",
29419
- method: HttpMethod.${item.method},
29420
- headers: headers,
29421
- params: ${paramsInput.length ? `params.toJson()` : "null"},
29422
- parser: ${responseParser},
29423
- );
29424
- }`);
29425
- return;
29426
- }
29427
- const subServiceName = pascalCase(`${name}_${key}_Service`);
29428
- const subService = dartServiceFromServiceDefinition(
29429
- pascalCase(`${name}_${key}_Service`),
29430
- item,
29431
- prefix
29432
- );
29433
- subServiceParts.push({
29434
- name: subServiceName,
29435
- key,
29436
- content: subService
29437
- });
29438
- });
29439
- return `class ${serviceName} {
29440
- final String baseUrl;
29441
- final Map<String, String> headers;
29442
- const ${serviceName}({
29443
- this.baseUrl = "",
29444
- this.headers = const {},
29445
- });
29446
- ${subServiceParts.map(
29447
- (sub) => `${sub.name} get ${sub.key} {
29448
- return ${sub.name}(
29449
- baseUrl: baseUrl,
29450
- headers: headers,
29451
- );
29452
- }`
29453
- ).join("\n")}
29454
- ${rpcParts.join("\n ")}
29455
- }
29456
- ${subServiceParts.map((sub) => sub.content).join("\n")}
29457
- `;
29458
- }
29459
- function dartModelFromJsonSchema(name, schema) {
29460
- const fields = [];
29461
- const subModelParts = [];
29462
- Object.entries(schema.properties ?? {}).forEach(([key, val]) => {
29463
- if (typeof val !== "object") {
29464
- return;
29465
- }
29466
- const [dartType, subTypes] = dartPropertyTypeFromSchema(
29467
- name,
29468
- key,
29469
- schema
29470
- );
29471
- if (subTypes?.length) {
29472
- for (const sub of subTypes) {
29473
- subModelParts.push(sub);
29474
- }
29475
- }
29476
- fields.push({ type: dartType, name: key });
29477
- if (!isDartType(dartType) && "type" in val && val.type === "object") {
29478
- subModelParts.push(
29479
- dartModelFromJsonSchema(dartType.replace("?", ""), val)
29480
- );
29481
- }
29482
- });
29483
- return `class ${name} {
29484
- ${fields.map((field) => `final ${field.type} ${field.name};`).join("\n ")}
29485
- const ${name}({
29486
- ${fields.map(
29487
- (field) => field.type.includes("?") ? `this.${field.name},` : `required this.${field.name},`
29488
- ).join("\n ")}
29489
- });
29490
- factory ${name}.fromJson(Map<String, dynamic> json) {
29491
- return ${name}(
29492
- ${fields.map((field) => `${dartParsedJsonField(field.name, field.type)},`).join("\n ")}
29493
- );
29494
- }
29495
- Map<String, dynamic> toJson() {
29496
- return {
29497
- ${fields.map((field) => {
29498
- const isNullable = field.type.endsWith("?");
29499
- const typeName = field.type.replace("?", "");
29500
- if (isDartTypeWithNullables(field.type)) {
29501
- const transformer = transformers[typeName];
29502
- return transformer.toJsonBody(field.name, isNullable);
29503
- }
29504
- if (field.type.includes("List<")) {
29505
- return classListTransformer(typeName).toJsonBody(
29506
- field.name,
29507
- isNullable
29508
- );
29509
- }
29510
- return classTransformer(typeName, isNullable).toJsonBody(
29511
- field.name,
29512
- isNullable
29513
- );
29514
- }).join(",\n ")},
29515
- };
29516
- }
29517
- ${name} copyWith({
29518
- ${fields.map((field) => `${field.type.replace("?", "")}? ${field.name},`).join("\n ")}
29519
- }) {
29520
- return ${name}(
29521
- ${fields.map((field) => `${field.name}: ${field.name} ?? this.${field.name},`).join("\n ")}
29522
- );
29523
- }
29524
- }
29525
-
29526
- ${subModelParts.join("\n")}`;
29527
- }
29528
- function dartPropertyTypeFromSchema(objectName, propertyName, schema) {
29529
- const prop = schema.properties?.[propertyName];
29530
- const isOptional = !schema.required?.includes(propertyName);
29531
- let finalType = "";
29532
- const subTypes = [];
29533
- if (isJsonSchemaEnum(prop)) {
29534
- const enumName = pascalCase(`${objectName}_${propertyName}`);
29535
- finalType = isOptional ? `${enumName}?` : enumName;
29536
- const options = [];
29537
- for (const opt of prop.anyOf) {
29538
- if (opt.type === "string") {
29539
- options.push({
29540
- name: opt.const.toString(),
29541
- type: "String",
29542
- value: opt.const
29543
- });
29544
- }
29545
- if (opt.type === "number" || opt.type === "integer") {
29546
- options.push({
29547
- name: camelCase(
29548
- `num_${opt.const}`.split(".").join("Point")
29549
- ),
29550
- type: opt.type === "number" ? "double" : "int",
29551
- value: opt.const
29552
- });
29553
- }
29554
- }
29555
- subTypes.push(`enum ${enumName} implements Comparable<${enumName}> {
29556
- ${options.map(
29557
- (opt) => `${opt.name}(${opt.type === "String" ? `"${opt.value}"` : opt.value})`
29558
- ).join(",\n ")};
29559
- const ${enumName}(this.value);
29560
- final dynamic value;
29561
-
29562
- @override
29563
- compareTo(${enumName} other) => name.compareTo(other.name);
29564
-
29565
- factory ${enumName}.fromJson(dynamic input) {
29566
- for(final val in values) {
29567
- if(val.value == input) {
29568
- return val;
29569
- }
29570
- }
29571
- return ${options[0].name};
29572
- }
29573
-
29574
- dynamic toJson() {
29575
- return value;
29576
- }
29577
- }`);
29578
- return [finalType, subTypes];
29579
- }
29580
- if (isJsonSchemaNullType(prop)) {
29581
- finalType = "null";
29582
- return [finalType, subTypes];
29583
- }
29584
- if (isJsonSchemaScalarType(prop)) {
29585
- switch (prop.type) {
29586
- case "string":
29587
- finalType = isOptional ? "String?" : "String";
29588
- break;
29589
- case "integer":
29590
- finalType = isOptional ? "int?" : "int";
29591
- break;
29592
- case "number":
29593
- finalType = isOptional ? "double?" : "double";
29594
- break;
29595
- case "Date":
29596
- finalType = isOptional ? "DateTime?" : "DateTime";
29597
- break;
29598
- case "boolean":
29599
- finalType = isOptional ? "bool?" : "bool";
29600
- break;
29601
- }
29602
- }
29603
- if (isJsonSchemaObject(prop)) {
29604
- const joinedPropName = pascalCase(
29605
- `${objectName}_${propertyName}`
29606
- );
29607
- finalType = isOptional ? `${joinedPropName}?` : joinedPropName;
29608
- }
29609
- if (isJsonSchemaArray(prop)) {
29610
- const item = prop.items;
29611
- const type = item.type;
29612
- if (typeof type !== "string") {
29613
- throw new Error(
29614
- "Union types are not supported in arrays at this time"
29615
- );
29616
- }
29617
- switch (type) {
29618
- case "string":
29619
- finalType = isOptional ? "List<String>?" : "List<String>";
29620
- break;
29621
- case "integer":
29622
- finalType = isOptional ? "List<int>?" : "List<int>";
29623
- break;
29624
- case "number":
29625
- finalType = isOptional ? "List<double>?" : "List<double>";
29626
- break;
29627
- case "null":
29628
- finalType = isOptional ? "List<null>?" : "List<null>";
29629
- break;
29630
- case "boolean":
29631
- finalType = isOptional ? "List<bool>?" : "List<bool>";
29632
- break;
29633
- case "Date":
29634
- finalType = isOptional ? "List<DateTime>?" : "List<DateTime>";
29635
- break;
29636
- case "object": {
29637
- const subTypeName = item.$id ?? pascalCase(`${objectName}_${propertyName}_item`);
29638
- const model = dartModelFromJsonSchema(subTypeName, item);
29639
- if (!generatedModels.includes(subTypeName)) {
29640
- subTypes.push(model);
29641
- generatedModels.push(subTypeName);
29642
- }
29643
- finalType = isOptional ? `List<${subTypeName}>?` : `List<${subTypeName}>`;
29644
- break;
29645
- }
29646
- }
29647
- }
29648
- return [finalType, subTypes.length ? subTypes : void 0];
29649
- }
29650
- function dartParsedJsonField(fieldName, dartType) {
29651
- if (isDartTypeWithNullables(dartType)) {
29652
- switch (dartType) {
29653
- case "String":
29654
- return transformers.String.fromJsonBody(fieldName, '""');
29655
- case "String?":
29656
- return transformers.String.fromJsonBody(fieldName, "null");
29657
- case "bool":
29658
- return transformers.bool.fromJsonBody(fieldName, "false");
29659
- case "double":
29660
- return transformers.double.fromJsonBody(fieldName, "0.0");
29661
- case "int":
29662
- return transformers.int.fromJsonBody(fieldName, "0");
29663
- case "null":
29664
- return transformers.null.fromJsonBody(fieldName, "");
29665
- case "DateTime":
29666
- return transformers.DateTime.fromJsonBody(
29667
- fieldName,
29668
- "DateTime(0)"
29669
- );
29670
- case "DateTime?":
29671
- return transformers.DateTime.fromJsonBody(fieldName, "null");
29672
- case "List<String>":
29673
- case "List<bool>":
29674
- case "List<double>":
29675
- case "List<int>":
29676
- case "List<null>":
29677
- return defaultListFromJsonBody(
29678
- fieldName,
29679
- dartType.replace("List<", "").replace(">", ""),
29680
- "[]"
29681
- );
29682
- default:
29683
- return `${fieldName}: json["${fieldName}"] is ${dartType.replace(
29684
- "?",
29685
- ""
29686
- )} ? json["${fieldName}"] : null`;
29687
- }
29688
- }
29689
- if (dartType.includes("List<")) {
29690
- const innerType = dartType.replace("List<", "").replace(">", "").replace("?", "");
29691
- return classListTransformer(innerType).fromJsonBody(
29692
- fieldName,
29693
- dartType.endsWith("?") ? "null" : "[]"
29694
- );
29695
- }
29696
- const classType = dartType.split("?").join("").trim();
29697
- return classTransformer(classType, dartType.endsWith("?")).fromJsonBody(
29698
- fieldName,
29699
- classType
29700
- );
29701
- }
29702
- const dartTypeMap = {
29703
- integer: "int",
29704
- bigint: "int",
29705
- number: "double",
29706
- string: "String",
29707
- boolean: "bool",
29708
- null: "null",
29709
- Date: "DateTime",
29710
- object: void 0,
29711
- list: void 0,
29712
- // eslint-disable-next-line object-shorthand
29713
- undefined: void 0,
29714
- array: void 0,
29715
- Uint8Array: "Uint8List"
29716
- };
29717
- const transformers = {
29718
- null: {
29719
- fromJsonBody: (_) => `null`,
29720
- toJsonBody: defaultToJsonBody
29721
- },
29722
- int: {
29723
- fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "int", fallback),
29724
- toJsonBody: defaultToJsonBody
29725
- },
29726
- double: {
29727
- fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "double", fallback),
29728
- toJsonBody: defaultToJsonBody
29729
- },
29730
- String: {
29731
- fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "String", fallback),
29732
- toJsonBody: defaultToJsonBody
29733
- },
29734
- bool: {
29735
- fromJsonBody: (key, fallback) => defaultFromJsonBody(key, "bool", fallback),
29736
- toJsonBody: defaultToJsonBody
29737
- },
29738
- DateTime: {
29739
- fromJsonBody: (key, fallback) => `${key}: json["${key}"] is String ? DateTime.parse(json["${key}"]) : ${fallback}`,
29740
- toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.toIso8601String()`
29741
- },
29742
- "List<null>": {
29743
- fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "null", fallback),
29744
- toJsonBody: defaultToJsonBody
29745
- },
29746
- "List<int>": {
29747
- fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "int", fallback),
29748
- toJsonBody: defaultToJsonBody
29749
- },
29750
- "List<double>": {
29751
- fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "double", fallback),
29752
- toJsonBody: defaultToJsonBody
29753
- },
29754
- "List<String>": {
29755
- fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "String", fallback),
29756
- toJsonBody: defaultToJsonBody
29757
- },
29758
- "List<bool>": {
29759
- fromJsonBody: (key, fallback) => defaultListFromJsonBody(key, "bool", fallback),
29760
- toJsonBody: defaultToJsonBody
29761
- },
29762
- "List<DateTime>": {
29763
- fromJsonBody: (key, fallback) => `${key}: json["${key}"] is List<String> ?
29764
- (json["${key}"] as List<String>)
29765
- .map((item) => DateTime.parse(item)).toList() : ${fallback}`,
29766
- toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.map((val) => val.toIso8601String()).toList()`
29767
- },
29768
- Uint8List: {
29769
- fromJsonBody: (key, fallback) => `${key}: json["${key}"] is List ? Uint8List.fromList(json["${key}"]) : ${fallback}`,
29770
- toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.toList()`
29771
- },
29772
- "List<Uint8List>": {
29773
- fromJsonBody: (key, fallback) => `${key}: json["${key}"] is List && (json["${key}"] as List).isNotEmpty && (json["${key}"] as List).first is List ? json["${key}"] : ${fallback}`,
29774
- toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.map((val) => val.toList()).toList()`
29775
- }
29776
- };
29777
- function defaultFromJsonBody(key, typename, fallback) {
29778
- return `${key}: json["${key}"] is ${typename} ? json["${key}"] : ${fallback}`;
29779
- }
29780
- function defaultListFromJsonBody(key, typename, fallback) {
29781
- return `${key}: json["${key}"] is List<${typename}> ? json["${key}"] : ${fallback}`;
29782
- }
29783
- function defaultToJsonBody(key) {
29784
- return `"${key}": ${key}`;
29785
- }
29786
- const classTransformer = (typename, nullable) => {
29787
- return {
29788
- fromJsonBody: (key, fallback) => {
29789
- if (nullable) {
29790
- return `${key}: json["${key}"] is Map<String, dynamic> ?
29791
- ${typename}.fromJson(json["${key}"]) : null`;
29792
- }
29793
- return `${key}: ${typename}.fromJson(json["${key}"])`;
29794
- },
29795
- toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.toJson()`
29796
- };
29797
- };
29798
- const classListTransformer = (typename) => {
29799
- return {
29800
- fromJsonBody: (key, fallback) => {
29801
- return `${key}: json["${key}"] is List<Map<String, dynamic>> ?
29802
- (json["${key}"] as List<Map<String, dynamic>>)
29803
- .map((val) => ${typename}.fromJson(val)).toList() : ${fallback}`;
29804
- },
29805
- toJsonBody: (key, isNullable) => `"${key}": ${key}${isNullable ? "?" : ""}.map((val) => val.toJson()).toList()`
29806
- };
29807
- };
29808
- function isDartType(input) {
29809
- if (typeof input !== "string") {
29810
- return false;
29811
- }
29812
- for (const val of Object.values(dartTypeMap)) {
29813
- if (input === val) {
29814
- return true;
29815
- }
29816
- if (input.replace("List<", "").replace(">", "") === val) {
29817
- return true;
29818
- }
29819
- }
29820
- return false;
29821
- }
29822
- function isDartTypeWithNullables(input) {
29823
- if (typeof input !== "string") {
29824
- return false;
29825
- }
29826
- for (const val of Object.values(dartTypeMap)) {
29827
- if (input.replace("?", "") === val) {
29828
- return true;
29829
- }
29830
- if (input.replace("?", "").replace("List<", "").replace(">", "") === val) {
29831
- return true;
29832
- }
29833
- }
29834
- return false;
29835
- }
29836
-
29837
- export { classListTransformer, classTransformer, createDartClient, createTypescriptClient, dartClientGenerator, dartModelFromJsonSchema, dartParsedJsonField, dartPropertyTypeFromSchema, dartServiceFromServiceDefinition, defineClientGeneratorPlugin, isDartType, isDartTypeWithNullables, transformers, tsModelFromDefinition, tsRpcFromProcedureDefinition, tsServiceFromServiceDefinition, typescriptClientGenerator };
29030
+ export { format2 as f };