resora 0.2.2 → 0.2.4

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.
package/dist/index.mjs CHANGED
@@ -1,878 +1,10 @@
1
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
2
- import path, { dirname, join } from "path";
3
- import { createRequire } from "module";
4
- import { pathToFileURL } from "url";
5
- import { Command } from "@h3ravel/musket";
6
-
7
- //#region src/ApiResource.ts
8
- /**
9
- * ApiResource function to return the Resource instance
10
- *
11
- * @param instance Resource instance
12
- * @returns Resource instance
13
- */
14
- function ApiResource(instance) {
15
- return instance;
16
- }
17
-
18
- //#endregion
19
- //#region src/utilities/state.ts
20
- let globalPreferredCase;
21
- let globalResponseStructure;
22
- let globalPaginatedExtras = ["meta", "links"];
23
- let globalPaginatedLinks = {
24
- first: "first",
25
- last: "last",
26
- prev: "prev",
27
- next: "next"
28
- };
29
- let globalBaseUrl = "https://localhost";
30
- let globalPageName = "page";
31
- let globalPaginatedMeta = {
32
- to: "to",
33
- from: "from",
34
- links: "links",
35
- path: "path",
36
- total: "total",
37
- per_page: "per_page",
38
- last_page: "last_page",
39
- current_page: "current_page"
40
- };
41
- let globalCursorMeta = {
42
- previous: "previous",
43
- next: "next"
44
- };
45
- /**
46
- * Sets the global case style for response keys, which will be applied
47
- * to all responses unless overridden by individual resource configurations.
48
- *
49
- * @param style The case style to set as the global default for response keys.
50
- */
51
- const setGlobalCase = (style) => {
52
- globalPreferredCase = style;
53
- };
54
- /**
55
- * Retrieves the global case style for response keys, which is used
56
- * to determine how keys in responses should be formatted.
57
- *
58
- * @returns
59
- */
60
- const getGlobalCase = () => {
61
- return globalPreferredCase;
62
- };
63
- /**
64
- * Sets the global response structure configuration, which defines how
65
- * responses should be structured across the application.
66
- *
67
- * @param config The response structure configuration object.
68
- */
69
- const setGlobalResponseStructure = (config) => {
70
- globalResponseStructure = config;
71
- };
72
- /**
73
- * Retrieves the global response structure configuration, which
74
- * defines how responses should be structured across the application.
75
- *
76
- * @returns
77
- */
78
- const getGlobalResponseStructure = () => {
79
- return globalResponseStructure;
80
- };
81
- /**
82
- * Sets the global response root key, which is the key under which
83
- * the main data will be nested in responses if wrapping is enabled.
84
- *
85
- * @param rootKey The root key to set for response data.
86
- */
87
- const setGlobalResponseRootKey = (rootKey) => {
88
- globalResponseStructure = {
89
- ...globalResponseStructure || {},
90
- rootKey
91
- };
92
- };
93
- /**
94
- * Sets the global response wrap option, which determines whether responses
95
- * should be wrapped in a root key or returned unwrapped when possible.
96
- *
97
- * @param wrap The wrap option to set for responses.
98
- */
99
- const setGlobalResponseWrap = (wrap) => {
100
- globalResponseStructure = {
101
- ...globalResponseStructure || {},
102
- wrap
103
- };
104
- };
105
- /**
106
- * Retrieves the global response wrap option, which indicates whether responses
107
- * should be wrapped in a root key or returned unwrapped when possible.
108
- *
109
- * @returns
110
- */
111
- const getGlobalResponseWrap = () => {
112
- return globalResponseStructure?.wrap;
113
- };
114
- /**
115
- * Retrieves the global response root key, which is the key under which the main
116
- * data will be nested in responses if wrapping is enabled.
117
- *
118
- * @returns
119
- */
120
- const getGlobalResponseRootKey = () => {
121
- return globalResponseStructure?.rootKey;
122
- };
123
- /**
124
- * Sets the global response factory, which is a custom function that can be used
125
- * to produce a completely custom response structure based on the provided
126
- * payload and context.
127
- *
128
- * @param factory The response factory function to set as the global default for response construction.
129
- */
130
- const setGlobalResponseFactory = (factory) => {
131
- globalResponseStructure = {
132
- ...globalResponseStructure || {},
133
- factory
134
- };
135
- };
136
- /**
137
- * Retrieves the global response factory, which is a custom function that
138
- * can be used to produce a completely custom response structure based on
139
- * the provided payload and context.
140
- *
141
- * @returns
142
- */
143
- const getGlobalResponseFactory = () => {
144
- return globalResponseStructure?.factory;
145
- };
146
- /**
147
- * Sets the global paginated extras configuration, which defines the keys
148
- * to use for pagination metadata, links, and cursor information in paginated responses.
149
- *
150
- * @param extras The paginated extras configuration object.
151
- */
152
- const setGlobalPaginatedExtras = (extras) => {
153
- globalPaginatedExtras = extras;
154
- };
155
- /**
156
- * Retrieves the global paginated extras configuration, which defines the keys to use for pagination metadata, links, and cursor information in paginated responses.
157
- *
158
- * @returns
159
- */
160
- const getGlobalPaginatedExtras = () => {
161
- return globalPaginatedExtras;
162
- };
163
- /**
164
- * Sets the global paginated links configuration, which defines the keys to
165
- * use for pagination links (first, last, prev, next) in paginated responses.
166
- *
167
- * @param links The paginated links configuration object.
168
- */
169
- const setGlobalPaginatedLinks = (links) => {
170
- globalPaginatedLinks = {
171
- ...globalPaginatedLinks,
172
- ...links
173
- };
174
- };
175
- /**
176
- * Retrieves the global paginated links configuration, which defines the keys to use for pagination links (first, last, prev, next) in paginated responses.
177
- *
178
- * @returns
179
- */
180
- const getGlobalPaginatedLinks = () => {
181
- return globalPaginatedLinks;
182
- };
183
- /**
184
- * Sets the global base URL, which is used for generating pagination links in responses.
185
- *
186
- * @param baseUrl The base URL to set for pagination link generation.
187
- */
188
- const setGlobalBaseUrl = (baseUrl) => {
189
- globalBaseUrl = baseUrl;
190
- };
191
- /**
192
- * Retrieves the global base URL, which is used for generating pagination links in responses.
193
- *
194
- * @returns
195
- */
196
- const getGlobalBaseUrl = () => {
197
- return globalBaseUrl;
198
- };
199
- /**
200
- * Sets the global page name, which is the query parameter name used for the page number in paginated requests and link generation.
201
- *
202
- * @param pageName
203
- */
204
- const setGlobalPageName = (pageName) => {
205
- globalPageName = pageName;
206
- };
207
- /**
208
- * Retrieves the global page name, which is the query parameter name
209
- * used for the page number in paginated requests and link generation.
210
- *
211
- * @returns
212
- */
213
- const getGlobalPageName = () => {
214
- return globalPageName;
215
- };
216
- /**
217
- * Retrieves the keys to use for pagination extras (meta, links, cursor) based
218
- * on the global configuration.
219
- *
220
- * @param meta Whether to include pagination metadata in the response.
221
- */
222
- const setGlobalPaginatedMeta = (meta) => {
223
- globalPaginatedMeta = {
224
- ...globalPaginatedMeta,
225
- ...meta
226
- };
227
- };
228
- /**
229
- * Retrieves the keys to use for pagination extras (meta, links, cursor) based
230
- * on the global configuration.
231
- *
232
- * @returns The global pagination metadata configuration.
233
- */
234
- const getGlobalPaginatedMeta = () => {
235
- return globalPaginatedMeta;
236
- };
237
- /**
238
- * Sets the global cursor meta configuration, which defines the keys to use
239
- * for cursor pagination metadata (previous, next) in responses.
240
- *
241
- * @param meta The cursor meta configuration object.
242
- */
243
- const setGlobalCursorMeta = (meta) => {
244
- globalCursorMeta = {
245
- ...globalCursorMeta,
246
- ...meta
247
- };
248
- };
249
- /**
250
- * Retrieves the keys to use for cursor pagination metadata (previous, next) in
251
- * responses based on the global configuration.
252
- *
253
- * @returns The global cursor pagination metadata configuration.
254
- */
255
- const getGlobalCursorMeta = () => {
256
- return globalCursorMeta;
257
- };
258
-
259
- //#endregion
260
- //#region src/utilities/pagination.ts
261
- /**
262
- * Retrieves the configured keys for pagination extras (meta, links, cursor) based on the application's configuration.
263
- *
264
- * @returns An object containing the keys for meta, links, and cursor extras, or `undefined` if not configured.
265
- */
266
- const getPaginationExtraKeys = () => {
267
- const extras = getGlobalPaginatedExtras();
268
- if (Array.isArray(extras)) return {
269
- metaKey: extras.includes("meta") ? "meta" : void 0,
270
- linksKey: extras.includes("links") ? "links" : void 0,
271
- cursorKey: extras.includes("cursor") ? "cursor" : void 0
272
- };
273
- return {
274
- metaKey: extras.meta,
275
- linksKey: extras.links,
276
- cursorKey: extras.cursor
277
- };
278
- };
279
- /**
280
- * Builds a pagination URL for a given page number and path, using the global base URL and page name configuration.
281
- *
282
- * @param page The page number for which to build the URL. If `undefined`, the function will return `undefined`.
283
- * @param pathName The path to use for the URL. If not provided, it will default to an empty string.
284
- * @returns
285
- */
286
- const buildPageUrl = (page, pathName) => {
287
- if (typeof page === "undefined") return;
288
- const rawPath = pathName || "";
289
- const base = getGlobalBaseUrl() || "";
290
- const isAbsolutePath = /^https?:\/\//i.test(rawPath);
291
- const normalizedBase = base.replace(/\/$/, "");
292
- const normalizedPath = rawPath.replace(/^\//, "");
293
- const root = isAbsolutePath ? rawPath : normalizedBase ? normalizedPath ? `${normalizedBase}/${normalizedPath}` : normalizedBase : "";
294
- if (!root) return;
295
- const url = new URL(root);
296
- url.searchParams.set(getGlobalPageName() || "page", String(page));
297
- return url.toString();
298
- };
299
- /**
300
- * Builds pagination extras (meta, links, cursor) for a given resource based on
301
- * its pagination and cursor properties, using the configured keys for each type of extra.
302
- *
303
- * @param resource The resource for which to build pagination extras.
304
- * @returns An object containing the pagination extras (meta, links, cursor) for the resource.
305
- */
306
- const buildPaginationExtras = (resource) => {
307
- const { metaKey, linksKey, cursorKey } = getPaginationExtraKeys();
308
- const extra = {};
309
- const pagination = resource?.pagination;
310
- const cursor = resource?.cursor;
311
- const metaBlock = {};
312
- const linksBlock = {};
313
- if (pagination) {
314
- const metaSource = {
315
- to: pagination.to,
316
- from: pagination.from,
317
- links: pagination.links,
318
- path: pagination.path,
319
- total: pagination.total,
320
- per_page: pagination.perPage,
321
- last_page: pagination.lastPage,
322
- current_page: pagination.currentPage
323
- };
324
- for (const [sourceKey, outputKey] of Object.entries(getGlobalPaginatedMeta())) {
325
- if (!outputKey) continue;
326
- const value = metaSource[sourceKey];
327
- if (typeof value !== "undefined") metaBlock[outputKey] = value;
328
- }
329
- const linksSource = {
330
- first: buildPageUrl(pagination.firstPage, pagination.path),
331
- last: buildPageUrl(pagination.lastPage, pagination.path),
332
- prev: buildPageUrl(pagination.prevPage, pagination.path),
333
- next: buildPageUrl(pagination.nextPage, pagination.path)
334
- };
335
- for (const [sourceKey, outputKey] of Object.entries(getGlobalPaginatedLinks())) {
336
- if (!outputKey) continue;
337
- const value = linksSource[sourceKey];
338
- if (typeof value !== "undefined") linksBlock[outputKey] = value;
339
- }
340
- }
341
- if (cursor) {
342
- const cursorBlock = {};
343
- const cursorSource = {
344
- previous: cursor.previous,
345
- next: cursor.next
346
- };
347
- for (const [sourceKey, outputKey] of Object.entries(getGlobalCursorMeta())) {
348
- if (!outputKey) continue;
349
- const value = cursorSource[sourceKey];
350
- if (typeof value !== "undefined") cursorBlock[outputKey] = value;
351
- }
352
- if (cursorKey && Object.keys(cursorBlock).length > 0) extra[cursorKey] = cursorBlock;
353
- else if (Object.keys(cursorBlock).length > 0) metaBlock.cursor = cursorBlock;
354
- }
355
- if (metaKey && Object.keys(metaBlock).length > 0) extra[metaKey] = metaBlock;
356
- if (linksKey && Object.keys(linksBlock).length > 0) extra[linksKey] = linksBlock;
357
- return extra;
358
- };
359
-
360
- //#endregion
361
- //#region src/utilities/objects.ts
362
- /**
363
- * Utility functions for working with objects, including type checking, merging, and property manipulation.
364
- *
365
- * @param value The value to check.
366
- * @returns `true` if the value is a plain object, `false` otherwise.
367
- */
368
- const isPlainObject = (value) => {
369
- if (typeof value !== "object" || value === null) return false;
370
- if (Array.isArray(value) || value instanceof Date || value instanceof RegExp) return false;
371
- const proto = Object.getPrototypeOf(value);
372
- return proto === Object.prototype || proto === null;
373
- };
374
- /**
375
- * Appends extra properties to a response body, ensuring that the main data is wrapped under a specified root key if necessary.
376
- *
377
- * @param body The original response body, which can be an object, array, or primitive value.
378
- * @param extra Extra properties to append to the response body.
379
- * @param rootKey The root key under which to wrap the main data if necessary.
380
- * @returns The response body with the extra properties appended.
381
- */
382
- const appendRootProperties = (body, extra, rootKey = "data") => {
383
- if (!extra || Object.keys(extra).length === 0) return body;
384
- if (Array.isArray(body)) return {
385
- [rootKey]: body,
386
- ...extra
387
- };
388
- if (isPlainObject(body)) return {
389
- ...body,
390
- ...extra
391
- };
392
- return {
393
- [rootKey]: body,
394
- ...extra
395
- };
396
- };
397
- /**
398
- * Deeply merges two metadata objects, combining nested objects recursively.
399
- *
400
- * @param base The base metadata object to merge into.
401
- * @param incoming The incoming metadata object to merge from.
402
- * @returns
403
- */
404
- const mergeMetadata = (base, incoming) => {
405
- if (!incoming) return base;
406
- if (!base) return incoming;
407
- const merged = { ...base };
408
- for (const [key, value] of Object.entries(incoming)) {
409
- const existing = merged[key];
410
- if (isPlainObject(existing) && isPlainObject(value)) merged[key] = mergeMetadata(existing, value);
411
- else merged[key] = value;
412
- }
413
- return merged;
414
- };
415
-
416
- //#endregion
417
- //#region src/utilities/response.ts
418
- /**
419
- * Builds a response envelope based on the provided payload,
420
- * metadata, and configuration options.
421
- *
422
- * @param config The configuration object containing payload, metadata, and other options for building the response.
423
- */
424
- const buildResponseEnvelope = ({ payload, meta, metaKey = "meta", wrap = true, rootKey = "data", factory, context }) => {
425
- if (factory) return factory(payload, {
426
- ...context,
427
- rootKey,
428
- meta
429
- });
430
- if (!wrap) {
431
- if (typeof meta === "undefined") return payload;
432
- if (isPlainObject(payload)) return {
433
- ...payload,
434
- [metaKey]: meta
435
- };
436
- return {
437
- [rootKey]: payload,
438
- [metaKey]: meta
439
- };
440
- }
441
- const body = { [rootKey]: payload };
442
- if (typeof meta !== "undefined") body[metaKey] = meta;
443
- return body;
444
- };
445
-
446
- //#endregion
447
- //#region src/utilities/metadata.ts
448
- /**
449
- * Resolves metadata from a resource instance by checking for a custom `with` method.
450
- * If the method exists and is different from the base method, it calls it to retrieve metadata.
451
- * This allows resources to provide additional metadata for response construction.
452
- *
453
- * @param instance The resource instance to check for a custom `with` method.
454
- * @param baseWithMethod The base `with` method to compare against.
455
- * @returns The resolved metadata or `undefined` if no custom metadata is provided.
456
- */
457
- const resolveWithHookMetadata = (instance, baseWithMethod) => {
458
- const candidate = instance?.with;
459
- if (typeof candidate !== "function" || candidate === baseWithMethod) return;
460
- if (candidate.length > 0) return;
461
- const result = candidate.call(instance);
462
- return isPlainObject(result) ? result : void 0;
463
- };
464
-
465
- //#endregion
466
- //#region src/utilities/conditional.ts
467
- const CONDITIONAL_ATTRIBUTE_MISSING = Symbol("resora.conditional.missing");
468
- /**
469
- * Resolves a value based on a condition. If the condition is falsy, it returns a special symbol indicating that the attribute is missing.
470
- *
471
- *
472
- * @param condition The condition to evaluate.
473
- * @param value The value or function to resolve if the condition is truthy.
474
- * @returns The resolved value or a symbol indicating the attribute is missing.
475
- */
476
- const resolveWhen = (condition, value) => {
477
- if (!condition) return CONDITIONAL_ATTRIBUTE_MISSING;
478
- return typeof value === "function" ? value() : value;
479
- };
480
- /**
481
- * Resolves a value only if it is not null or undefined.
482
- *
483
- * @param value The value to resolve.
484
- * @returns The resolved value or a symbol indicating the attribute is missing.
485
- */
486
- const resolveWhenNotNull = (value) => {
487
- return value === null || typeof value === "undefined" ? CONDITIONAL_ATTRIBUTE_MISSING : value;
488
- };
489
- /**
490
- * Conditionally merges object attributes based on a condition.
491
- *
492
- * @param condition
493
- * @param value
494
- * @returns
495
- */
496
- const resolveMergeWhen = (condition, value) => {
497
- if (!condition) return {};
498
- const resolved = typeof value === "function" ? value() : value;
499
- return isPlainObject(resolved) ? resolved : {};
500
- };
501
- /**
502
- * Recursively sanitizes an object or array by removing any attributes that are marked as missing using the special symbol.
503
- *
504
- * @param value The value to sanitize.
505
- * @returns The sanitized value.
506
- */
507
- const sanitizeConditionalAttributes = (value) => {
508
- if (value === CONDITIONAL_ATTRIBUTE_MISSING) return CONDITIONAL_ATTRIBUTE_MISSING;
509
- if (Array.isArray(value)) return value.map((item) => sanitizeConditionalAttributes(item)).filter((item) => item !== CONDITIONAL_ATTRIBUTE_MISSING);
510
- if (isPlainObject(value)) {
511
- const result = {};
512
- for (const [key, nestedValue] of Object.entries(value)) {
513
- const sanitizedValue = sanitizeConditionalAttributes(nestedValue);
514
- if (sanitizedValue === CONDITIONAL_ATTRIBUTE_MISSING) continue;
515
- result[key] = sanitizedValue;
516
- }
517
- return result;
518
- }
519
- return value;
520
- };
521
-
522
- //#endregion
523
- //#region src/utilities/case.ts
524
- /**
525
- * Splits a string into words based on common delimiters and capitalization patterns.
526
- * Handles camelCase, PascalCase, snake_case, kebab-case, and space-separated words.
527
- *
528
- * @param str
529
- * @returns
530
- */
531
- const splitWords = (str) => {
532
- return str.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[-_\s]+/g, " ").trim().toLowerCase().split(" ").filter(Boolean);
533
- };
534
- /**
535
- * Transforms a string to camelCase.
536
- *
537
- * @param str
538
- * @returns
539
- */
540
- const toCamelCase = (str) => {
541
- return splitWords(str).map((w, i) => i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)).join("");
542
- };
543
- /**
544
- * Transforms a string to snake_case.
545
- *
546
- * @param str
547
- * @returns
548
- */
549
- const toSnakeCase = (str) => {
550
- return splitWords(str).join("_");
551
- };
552
- /**
553
- * Transforms a string to PascalCase.
554
- *
555
- * @param str
556
- * @returns
557
- */
558
- const toPascalCase = (str) => {
559
- return splitWords(str).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
560
- };
561
- /**
562
- * Transforms a string to kebab-case.
563
- *
564
- * @param str
565
- * @returns
566
- */
567
- const toKebabCase = (str) => {
568
- return splitWords(str).join("-");
569
- };
570
- /**
571
- * Retrieves the appropriate case transformation function based on the provided style.
572
- *
573
- * @param style
574
- * @returns
575
- */
576
- const getCaseTransformer = (style) => {
577
- if (typeof style === "function") return style;
578
- switch (style) {
579
- case "camel": return toCamelCase;
580
- case "snake": return toSnakeCase;
581
- case "pascal": return toPascalCase;
582
- case "kebab": return toKebabCase;
583
- }
584
- };
585
- /**
586
- * Transforms the keys of an object (including nested objects and arrays) using
587
- * the provided transformer function.
588
- *
589
- * @param obj
590
- * @param transformer
591
- * @returns
592
- */
593
- const transformKeys = (obj, transformer) => {
594
- if (obj === null || obj === void 0) return obj;
595
- if (Array.isArray(obj)) return obj.map((item) => transformKeys(item, transformer));
596
- if (obj instanceof Date || obj instanceof RegExp) return obj;
597
- if (typeof obj === "object") return Object.fromEntries(Object.entries(obj).map(([key, value]) => [transformer(key), transformKeys(value, transformer)]));
598
- return obj;
599
- };
600
-
601
- //#endregion
602
- //#region src/utilities/config.ts
603
- let stubsDir = path.resolve(process.cwd(), "node_modules/resora/stubs");
604
- if (!existsSync(stubsDir)) stubsDir = path.resolve(process.cwd(), "stubs");
605
- const getDefaultConfig = () => {
606
- return {
607
- stubsDir,
608
- preferredCase: "camel",
609
- responseStructure: {
610
- wrap: true,
611
- rootKey: "data"
612
- },
613
- paginatedExtras: ["meta", "links"],
614
- baseUrl: "https://localhost",
615
- pageName: "page",
616
- paginatedLinks: {
617
- first: "first",
618
- last: "last",
619
- prev: "prev",
620
- next: "next"
621
- },
622
- paginatedMeta: {
623
- to: "to",
624
- from: "from",
625
- links: "links",
626
- path: "path",
627
- total: "total",
628
- per_page: "per_page",
629
- last_page: "last_page",
630
- current_page: "current_page"
631
- },
632
- cursorMeta: {
633
- previous: "previous",
634
- next: "next"
635
- },
636
- resourcesDir: "src/resources",
637
- stubs: {
638
- config: "resora.config.stub",
639
- resource: "resource.stub",
640
- collection: "resource.collection.stub"
641
- }
642
- };
643
- };
644
- /**
645
- * Defines the configuration for the application by merging the provided configuration with the default configuration. This function takes a partial configuration object as input and returns a complete configuration object that includes all required properties, using default values for any properties that are not specified in the input.
646
- *
647
- * @param config
648
- * @returns
649
- */
650
- const defineConfig = (config) => {
651
- const defConf = getDefaultConfig();
652
- return Object.assign(defConf, config, { stubs: Object.assign(defConf.stubs, config.stubs || {}) }, { cursorMeta: Object.assign(defConf.cursorMeta, config.cursorMeta || {}) }, { paginatedMeta: Object.assign(defConf.paginatedMeta, config.paginatedMeta || {}) }, { paginatedLinks: Object.assign(defConf.paginatedLinks, config.paginatedLinks || {}) }, { responseStructure: Object.assign(defConf.responseStructure, config.responseStructure || {}) });
653
- };
654
-
655
- //#endregion
656
- //#region src/utilities/runtime-config.ts
657
- let runtimeConfigLoaded = false;
658
- let runtimeConfigLoadingPromise;
659
- /**
660
- * Resets the runtime configuration state for testing purposes.
661
- *
662
- * @returns
663
- */
664
- const resetRuntimeConfigForTests = () => {
665
- runtimeConfigLoaded = false;
666
- runtimeConfigLoadingPromise = void 0;
667
- };
668
- /**
669
- * Applies the provided configuration to the global state of the application.
670
- *
671
- * @param config The complete configuration object to apply.
672
- */
673
- const applyRuntimeConfig = (config) => {
674
- if (config.preferredCase !== "camel") setGlobalCase(config.preferredCase);
675
- setGlobalResponseStructure(config.responseStructure);
676
- setGlobalPaginatedExtras(config.paginatedExtras);
677
- setGlobalPaginatedLinks(config.paginatedLinks);
678
- setGlobalPaginatedMeta(config.paginatedMeta);
679
- setGlobalCursorMeta(config.cursorMeta);
680
- setGlobalBaseUrl(config.baseUrl);
681
- setGlobalPageName(config.pageName);
682
- };
683
- /**
684
- * Loads the runtime configuration by searching for configuration files in the current working directory.
685
- * @param configPath The path to the configuration file to load.
686
- * @returns
687
- */
688
- const importConfigFile = async (configPath) => {
689
- return await import(`${pathToFileURL(configPath).href}?resora_runtime=${Date.now()}`);
690
- };
691
- /**
692
- * Resolves the imported configuration and applies it to the global state.
693
- *
694
- * @param imported
695
- */
696
- const resolveAndApply = (imported) => {
697
- applyRuntimeConfig(defineConfig((imported?.default ?? imported) || {}));
698
- runtimeConfigLoaded = true;
699
- };
700
- /**
701
- * Loads the runtime configuration synchronously by searching for CommonJS configuration files in the current working directory.
702
- *
703
- * @returns
704
- */
705
- const loadRuntimeConfigSync = () => {
706
- const require = createRequire(import.meta.url);
707
- const syncConfigPaths = [path.join(process.cwd(), "resora.config.cjs")];
708
- for (const configPath of syncConfigPaths) {
709
- if (!existsSync(configPath)) continue;
710
- try {
711
- resolveAndApply(require(configPath));
712
- return true;
713
- } catch {
714
- continue;
715
- }
716
- }
717
- return false;
718
- };
719
- /**
720
- * Loads the runtime configuration by searching for configuration files in the current working directory.
721
- *
722
- * @returns
723
- */
724
- const loadRuntimeConfig = async () => {
725
- if (runtimeConfigLoaded) return;
726
- if (runtimeConfigLoadingPromise) return await runtimeConfigLoadingPromise;
727
- if (loadRuntimeConfigSync()) return;
728
- runtimeConfigLoadingPromise = (async () => {
729
- const possibleConfigPaths = [path.join(process.cwd(), "resora.config.js"), path.join(process.cwd(), "resora.config.ts")];
730
- for (const configPath of possibleConfigPaths) {
731
- if (!existsSync(configPath)) continue;
732
- try {
733
- resolveAndApply(await importConfigFile(configPath));
734
- return;
735
- } catch {
736
- continue;
737
- }
738
- }
739
- runtimeConfigLoaded = true;
740
- })();
741
- await runtimeConfigLoadingPromise;
742
- };
743
- loadRuntimeConfig();
744
-
745
- //#endregion
746
- //#region src/cli/CliApp.ts
747
- var CliApp = class {
748
- command;
749
- config = {};
750
- constructor(config = {}) {
751
- this.config = defineConfig(config);
752
- }
753
- async loadConfig(config = {}) {
754
- this.config = defineConfig(config);
755
- const possibleConfigPaths = [
756
- join(process.cwd(), "resora.config.ts"),
757
- join(process.cwd(), "resora.config.js"),
758
- join(process.cwd(), "resora.config.cjs")
759
- ];
760
- for (const configPath of possibleConfigPaths) if (existsSync(configPath)) try {
761
- const { default: userConfig } = await import(configPath);
762
- Object.assign(this.config, userConfig);
763
- break;
764
- } catch (e) {
765
- console.error(`Error loading config file at ${configPath}:`, e);
766
- }
767
- return this;
768
- }
769
- /**
770
- * Get the current configuration object
771
- * @returns
772
- */
773
- getConfig() {
774
- return this.config;
775
- }
776
- /**
777
- * Initialize Resora by creating a default config file in the current directory
778
- *
779
- * @returns
780
- */
781
- init() {
782
- const outputPath = join(process.cwd(), "resora.config.js");
783
- const stubPath = join(this.config.stubsDir, this.config.stubs.config);
784
- if (existsSync(outputPath) && !this.command.option("force")) {
785
- this.command.error(`Error: ${outputPath} already exists.`);
786
- process.exit(1);
787
- }
788
- this.ensureDirectory(outputPath);
789
- if (existsSync(outputPath) && this.command.option("force")) copyFileSync(outputPath, outputPath.replace(/\.js$/, `.backup.${Date.now()}.js`));
790
- writeFileSync(outputPath, readFileSync(stubPath, "utf-8"));
791
- return { path: outputPath };
792
- }
793
- /**
794
- * Utility to ensure directory exists
795
- *
796
- * @param filePath
797
- */
798
- ensureDirectory(filePath) {
799
- const dir = dirname(filePath);
800
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
801
- }
802
- /**
803
- * Utility to generate file from stub
804
- *
805
- * @param stubPath
806
- * @param outputPath
807
- * @param replacements
808
- */
809
- generateFile(stubPath, outputPath, replacements, options) {
810
- if (existsSync(outputPath) && !options?.force) {
811
- this.command.error(`Error: ${outputPath} already exists.`);
812
- process.exit(1);
813
- } else if (existsSync(outputPath) && options?.force) rmSync(outputPath);
814
- let content = readFileSync(stubPath, "utf-8");
815
- for (const [key, value] of Object.entries(replacements)) content = content.replace(new RegExp(`{{${key}}}`, "g"), value);
816
- this.ensureDirectory(outputPath);
817
- writeFileSync(outputPath, content);
818
- return outputPath;
819
- }
820
- /**
821
- * Command to create a new resource or resource collection file
822
- *
823
- * @param name
824
- * @param options
825
- */
826
- makeResource(name, options) {
827
- let resourceName = name;
828
- if (options?.collection && !name.endsWith("Collection") && !name.endsWith("Resource")) resourceName += "Collection";
829
- else if (!options?.collection && !name.endsWith("Resource") && !name.endsWith("Collection")) resourceName += "Resource";
830
- const fileName = `${resourceName}.ts`;
831
- const outputPath = join(this.config.resourcesDir, fileName);
832
- const stubPath = join(this.config.stubsDir, options?.collection || name.endsWith("Collection") ? this.config.stubs.collection : this.config.stubs.resource);
833
- if (!existsSync(stubPath)) {
834
- this.command.error(`Error: Stub file ${stubPath} not found.`);
835
- process.exit(1);
836
- }
837
- const collectsName = resourceName.replace(/(Resource|Collection)$/, "") + "Resource";
838
- const collects = `/**
1
+ import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,rmSync as i,writeFileSync as a}from"fs";import o,{dirname as s,join as c}from"path";import{createRequire as l}from"module";import{pathToFileURL as u}from"url";import{Command as d}from"@h3ravel/musket";function f(e){return e}let p,m,h=[`meta`,`links`],g={first:`first`,last:`last`,prev:`prev`,next:`next`},_=`https://localhost`,ee=`page`,v={to:`to`,from:`from`,links:`links`,path:`path`,total:`total`,per_page:`per_page`,last_page:`last_page`,current_page:`current_page`},y={previous:`previous`,next:`next`};const b=e=>{p=e},x=()=>p,S=e=>{m=e},C=()=>m,te=e=>{m={...m||{},rootKey:e}},ne=e=>{m={...m||{},wrap:e}},re=()=>m?.wrap,ie=()=>m?.rootKey,ae=e=>{m={...m||{},factory:e}},oe=()=>m?.factory,w=e=>{h=e},T=()=>h,E=e=>{g={...g,...e}},se=()=>g,ce=e=>{_=e},le=()=>_,ue=e=>{ee=e},de=()=>ee,fe=e=>{v={...v,...e}},pe=()=>v,D=e=>{y={...y,...e}},O=()=>y,k=()=>{let e=T();return Array.isArray(e)?{metaKey:e.includes(`meta`)?`meta`:void 0,linksKey:e.includes(`links`)?`links`:void 0,cursorKey:e.includes(`cursor`)?`cursor`:void 0}:{metaKey:e.meta,linksKey:e.links,cursorKey:e.cursor}},A=(e,t)=>{if(e===void 0)return;let n=t||``,r=le()||``,i=/^https?:\/\//i.test(n),a=r.replace(/\/$/,``),o=n.replace(/^\//,``),s=i?n:a?o?`${a}/${o}`:a:``;if(!s)return;let c=new URL(s);return c.searchParams.set(de()||`page`,String(e)),c.toString()},j=e=>{let{metaKey:t,linksKey:n,cursorKey:r}=k(),i={},a=e?.pagination,o=e?.cursor,s={},c={};if(a){let e={to:a.to,from:a.from,links:a.links,path:a.path,total:a.total,per_page:a.perPage,last_page:a.lastPage,current_page:a.currentPage};for(let[t,n]of Object.entries(pe())){if(!n)continue;let r=e[t];r!==void 0&&(s[n]=r)}let t={first:A(a.firstPage,a.path),last:A(a.lastPage,a.path),prev:A(a.prevPage,a.path),next:A(a.nextPage,a.path)};for(let[e,n]of Object.entries(se())){if(!n)continue;let r=t[e];r!==void 0&&(c[n]=r)}}if(o){let e={},t={previous:o.previous,next:o.next};for(let[n,r]of Object.entries(O())){if(!r)continue;let i=t[n];i!==void 0&&(e[r]=i)}r&&Object.keys(e).length>0?i[r]=e:Object.keys(e).length>0&&(s.cursor=e)}return t&&Object.keys(s).length>0&&(i[t]=s),n&&Object.keys(c).length>0&&(i[n]=c),i},M=e=>{if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Date||e instanceof RegExp)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},N=(e,t,n=`data`)=>!t||Object.keys(t).length===0?e:Array.isArray(e)?{[n]:e,...t}:M(e)?{...e,...t}:{[n]:e,...t},P=(e,t)=>{if(!t)return e;if(!e)return t;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];M(t)&&M(r)?n[e]=P(t,r):n[e]=r}return n},F=({payload:e,meta:t,metaKey:n=`meta`,wrap:r=!0,rootKey:i=`data`,factory:a,context:o})=>{if(a)return a(e,{...o,rootKey:i,meta:t});if(!r)return t===void 0?e:M(e)?{...e,[n]:t}:{[i]:e,[n]:t};let s={[i]:e};return t!==void 0&&(s[n]=t),s},I=(e,t)=>{let n=e?.with;if(typeof n!=`function`||n===t||n.length>0)return;let r=n.call(e);return M(r)?r:void 0},L=Symbol(`resora.conditional.missing`),R=(e,t)=>e?typeof t==`function`?t():t:L,z=e=>e??L,B=(e,t)=>{if(!e)return{};let n=typeof t==`function`?t():t;return M(n)?n:{}},V=e=>{if(e===L)return L;if(Array.isArray(e))return e.map(e=>V(e)).filter(e=>e!==L);if(M(e)){let t={};for(let[n,r]of Object.entries(e)){let e=V(r);e!==L&&(t[n]=e)}return t}return e},H=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/[-_\s]+/g,` `).trim().toLowerCase().split(` `).filter(Boolean),U=e=>H(e).map((e,t)=>t===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(``),W=e=>H(e).join(`_`),G=e=>H(e).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``),K=e=>H(e).join(`-`),q=e=>{if(typeof e==`function`)return e;switch(e){case`camel`:return U;case`snake`:return W;case`pascal`:return G;case`kebab`:return K}},J=(e,t)=>e==null?e:Array.isArray(e)?e.map(e=>J(e,t)):e instanceof Date||e instanceof RegExp?e:typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[t(e),J(n,t)])):e;let Y=o.resolve(process.cwd(),`node_modules/resora/stubs`);t(Y)||(Y=o.resolve(process.cwd(),`stubs`));const me=()=>({stubsDir:Y,preferredCase:`camel`,responseStructure:{wrap:!0,rootKey:`data`},paginatedExtras:[`meta`,`links`],baseUrl:`https://localhost`,pageName:`page`,paginatedLinks:{first:`first`,last:`last`,prev:`prev`,next:`next`},paginatedMeta:{to:`to`,from:`from`,links:`links`,path:`path`,total:`total`,per_page:`per_page`,last_page:`last_page`,current_page:`current_page`},cursorMeta:{previous:`previous`,next:`next`},resourcesDir:`src/resources`,stubs:{config:`resora.config.stub`,resource:`resource.stub`,collection:`resource.collection.stub`}}),X=e=>{let t=me();return Object.assign(t,e,{stubs:Object.assign(t.stubs,e.stubs||{})},{cursorMeta:Object.assign(t.cursorMeta,e.cursorMeta||{})},{paginatedMeta:Object.assign(t.paginatedMeta,e.paginatedMeta||{})},{paginatedLinks:Object.assign(t.paginatedLinks,e.paginatedLinks||{})},{responseStructure:Object.assign(t.responseStructure,e.responseStructure||{})})};let Z=!1,Q;const he=()=>{Z=!1,Q=void 0},ge=e=>{e.preferredCase!==`camel`&&b(e.preferredCase),S(e.responseStructure),w(e.paginatedExtras),E(e.paginatedLinks),fe(e.paginatedMeta),D(e.cursorMeta),ce(e.baseUrl),ue(e.pageName)},_e=async e=>await import(`${u(e).href}?resora_runtime=${Date.now()}`),ve=e=>{ge(X((e?.default??e)||{})),Z=!0},ye=()=>{let e=l(import.meta.url),n=[o.join(process.cwd(),`resora.config.cjs`)];for(let r of n)if(t(r))try{return ve(e(r)),!0}catch{continue}return!1},be=async()=>{if(!Z){if(Q)return await Q;ye()||(Q=(async()=>{let e=[o.join(process.cwd(),`resora.config.js`),o.join(process.cwd(),`resora.config.ts`)];for(let n of e)if(t(n))try{ve(await _e(n));return}catch{continue}Z=!0})(),await Q)}};be();var xe=class{command;config={};constructor(e={}){this.config=X(e)}async loadConfig(e={}){this.config=X(e);let n=[c(process.cwd(),`resora.config.ts`),c(process.cwd(),`resora.config.js`),c(process.cwd(),`resora.config.cjs`)];for(let e of n)if(t(e))try{let{default:t}=await import(e);Object.assign(this.config,t);break}catch(t){console.error(`Error loading config file at ${e}:`,t)}return this}getConfig(){return this.config}init(){let n=c(process.cwd(),`resora.config.js`),i=c(this.config.stubsDir,this.config.stubs.config);return t(n)&&!this.command.option(`force`)&&(this.command.error(`Error: ${n} already exists.`),process.exit(1)),this.ensureDirectory(n),t(n)&&this.command.option(`force`)&&e(n,n.replace(/\.js$/,`.backup.${Date.now()}.js`)),a(n,r(i,`utf-8`)),{path:n}}ensureDirectory(e){let r=s(e);t(r)||n(r,{recursive:!0})}generateFile(e,n,o,s){t(n)&&!s?.force?(this.command.error(`Error: ${n} already exists.`),process.exit(1)):t(n)&&s?.force&&i(n);let c=r(e,`utf-8`);for(let[e,t]of Object.entries(o))c=c.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(n),a(n,c),n}makeResource(e,n){let r=e;n?.collection&&!e.endsWith(`Collection`)&&!e.endsWith(`Resource`)?r+=`Collection`:!n?.collection&&!e.endsWith(`Resource`)&&!e.endsWith(`Collection`)&&(r+=`Resource`);let i=`${r}.ts`,a=c(this.config.resourcesDir,i),o=c(this.config.stubsDir,n?.collection||e.endsWith(`Collection`)?this.config.stubs.collection:this.config.stubs.resource);t(o)||(this.command.error(`Error: Stub file ${o} not found.`),process.exit(1));let s=r.replace(/(Resource|Collection)$/,``)+`Resource`,l=`/**
839
2
  * The resource that this collection collects.
840
3
  */
841
- collects = ${collectsName}
842
- `;
843
- const collectsImport = `import ${collectsName} from './${collectsName}'\n`;
844
- const hasCollects = (!!options?.collection || name.endsWith("Collection")) && existsSync(join(this.config.resourcesDir, `${collectsName}.ts`));
845
- const path = this.generateFile(stubPath, outputPath, {
846
- ResourceName: resourceName,
847
- CollectionResourceName: resourceName.replace(/(Resource|Collection)$/, "") + "Resource",
848
- "collects = Resource": hasCollects ? collects : "",
849
- "import = Resource": hasCollects ? collectsImport : ""
850
- }, options);
851
- return {
852
- name: resourceName,
853
- path
854
- };
855
- }
856
- };
857
-
858
- //#endregion
859
- //#region src/cli/commands/InitCommand.ts
860
- var InitCommand = class extends Command {
861
- signature = `init
4
+ collects = ${s}
5
+ `,u=`import ${s} from './${s}'\n`,d=(!!n?.collection||e.endsWith(`Collection`))&&t(c(this.config.resourcesDir,`${s}.ts`)),f=this.generateFile(o,a,{ResourceName:r,CollectionResourceName:r.replace(/(Resource|Collection)$/,``)+`Resource`,"collects = Resource":d?l:``,"import = Resource":d?u:``},n);return{name:r,path:f}}},Se=class extends d{signature=`init
862
6
  {--force : Force overwrite if config file already exists (existing file will be backed up) }
863
- `;
864
- description = "Initialize Resora";
865
- async handle() {
866
- this.app.command = this;
867
- this.app.init();
868
- this.success("Resora initialized");
869
- }
870
- };
871
-
872
- //#endregion
873
- //#region src/cli/commands/MakeResource.ts
874
- var MakeResource = class extends Command {
875
- signature = `#create:
7
+ `;description=`Initialize Resora`;async handle(){this.app.command=this,this.app.init(),this.success(`Resora initialized`)}},Ce=class extends d{signature=`#create:
876
8
  {resource : Generates a new resource file.
877
9
  | {name : Name of the resource to create}
878
10
  | {--c|collection : Make a resource collection}
@@ -886,916 +18,11 @@ var MakeResource = class extends Command {
886
18
  | {prefix : prefix of the resources to create, "Admin" will create AdminResource, AdminCollection}
887
19
  | {--force : Create the resource or collection file even if it already exists.}
888
20
  }
889
- `;
890
- description = "Create a new resource or resource collection file";
891
- async handle() {
892
- this.app.command = this;
893
- let path = "";
894
- const action = this.dictionary.name || this.dictionary.baseCommand;
895
- if (["resource", "collection"].includes(action) && !this.argument("name")) return void this.error("Error: Name argument is required.");
896
- if (action === "all" && !this.argument("prefix")) return void this.error("Error: Prefix argument is required.");
897
- switch (action) {
898
- case "resource":
899
- ({path} = this.app.makeResource(this.argument("name"), this.options()));
900
- break;
901
- case "collection":
902
- ({path} = this.app.makeResource(this.argument("name") + "Collection", this.options()));
903
- break;
904
- case "all": {
905
- const o1 = this.app.makeResource(this.argument("prefix"), { force: this.option("force") });
906
- const o2 = this.app.makeResource(this.argument("prefix") + "Collection", {
907
- collection: true,
908
- force: this.option("force")
909
- });
910
- path = `${o1.path}, ${o2.path}`;
911
- break;
912
- }
913
- default: this.fail(`Unknown action: ${action}`);
914
- }
915
- this.success(`Created: ${path}`);
916
- }
917
- };
918
-
919
- //#endregion
920
- //#region src/cli/logo.ts
921
- var logo_default = String.raw`
21
+ `;description=`Create a new resource or resource collection file`;async handle(){this.app.command=this;let e=``,t=this.dictionary.name||this.dictionary.baseCommand;if([`resource`,`collection`].includes(t)&&!this.argument(`name`))return void this.error(`Error: Name argument is required.`);if(t===`all`&&!this.argument(`prefix`))return void this.error(`Error: Prefix argument is required.`);switch(t){case`resource`:({path:e}=this.app.makeResource(this.argument(`name`),this.options()));break;case`collection`:({path:e}=this.app.makeResource(this.argument(`name`)+`Collection`,this.options()));break;case`all`:{let t=this.app.makeResource(this.argument(`prefix`),{force:this.option(`force`)}),n=this.app.makeResource(this.argument(`prefix`)+`Collection`,{collection:!0,force:this.option(`force`)});e=`${t.path}, ${n.path}`;break}default:this.fail(`Unknown action: ${t}`)}this.success(`Created: ${e}`)}};String.raw`
922
22
  _____
923
23
  | __ \
924
24
  | |__) |___ ___ ___ _ __ __ _
925
25
  | _ // _ \/ __|/ _ \| '__/ _, |
926
26
  | | \ \ __/\__ \ (_) | | | (_| |
927
27
  |_| \_\___||___/\___/|_| \__,_|
928
- `;
929
-
930
- //#endregion
931
- //#region src/ServerResponse.ts
932
- var ServerResponse = class {
933
- _status = 200;
934
- headers = {};
935
- constructor(response, body) {
936
- this.response = response;
937
- this.body = body;
938
- }
939
- /**
940
- * Set the HTTP status code for the response
941
- *
942
- * @param status
943
- * @returns The current ServerResponse instance
944
- */
945
- setStatusCode(status) {
946
- this._status = status;
947
- if ("status" in this.response && typeof this.response.status === "function") this.response.status(status);
948
- else if ("status" in this.response) this.response.status = status;
949
- return this;
950
- }
951
- /**
952
- * Get the current HTTP status code for the response
953
- *
954
- * @returns
955
- */
956
- status() {
957
- return this._status;
958
- }
959
- /**
960
- * Get the current HTTP status text for the response
961
- *
962
- * @returns
963
- */
964
- statusText() {
965
- if ("statusMessage" in this.response) return this.response.statusMessage;
966
- else if ("statusText" in this.response) return this.response.statusText;
967
- }
968
- /**
969
- * Set a cookie in the response header
970
- *
971
- * @param name The name of the cookie
972
- * @param value The value of the cookie
973
- * @param options Optional cookie attributes (e.g., path, domain, maxAge)
974
- * @returns The current ServerResponse instance
975
- */
976
- setCookie(name, value, options) {
977
- this.#addHeader("Set-Cookie", `${name}=${value}; ${Object.entries(options || {}).map(([key, val]) => `${key}=${val}`).join("; ")}`);
978
- return this;
979
- }
980
- /**
981
- * Convert the resource to a JSON response body
982
- *
983
- * @param headers Optional headers to add to the response
984
- * @returns The current ServerResponse instance
985
- */
986
- setHeaders(headers) {
987
- for (const [key, value] of Object.entries(headers)) this.#addHeader(key, value);
988
- return this;
989
- }
990
- /**
991
- * Add a single header to the response
992
- *
993
- * @param key The name of the header
994
- * @param value The value of the header
995
- * @returns The current ServerResponse instance
996
- */
997
- header(key, value) {
998
- this.#addHeader(key, value);
999
- return this;
1000
- }
1001
- /**
1002
- * Add a single header to the response
1003
- *
1004
- * @param key The name of the header
1005
- * @param value The value of the header
1006
- */
1007
- #addHeader(key, value) {
1008
- this.headers[key] = value;
1009
- if ("headers" in this.response) this.response.headers.set(key, value);
1010
- else if ("setHeader" in this.response) this.response.setHeader(key, value);
1011
- }
1012
- /**
1013
- * Promise-like then method to allow chaining with async/await or .then() syntax
1014
- *
1015
- * @param onfulfilled Callback to handle the fulfilled state of the promise, receiving the response body
1016
- * @param onrejected Callback to handle the rejected state of the promise, receiving the error reason
1017
- * @returns A promise that resolves to the result of the onfulfilled or onrejected callback
1018
- */
1019
- then(onfulfilled, onrejected) {
1020
- const resolved = Promise.resolve(this.body).then(onfulfilled, onrejected);
1021
- if ("send" in this.response) this.response.send(this.body);
1022
- return resolved;
1023
- }
1024
- /**
1025
- * Promise-like catch method to handle rejected state of the promise
1026
- *
1027
- * @param onrejected
1028
- * @returns
1029
- */
1030
- catch(onrejected) {
1031
- return this.then(void 0, onrejected);
1032
- }
1033
- /**
1034
- * Promise-like finally method to handle cleanup after promise is settled
1035
- *
1036
- * @param onfinally
1037
- * @returns
1038
- */
1039
- finally(onfinally) {
1040
- return this.then(onfinally, onfinally);
1041
- }
1042
- };
1043
-
1044
- //#endregion
1045
- //#region src/GenericResource.ts
1046
- /**
1047
- * GenericResource class to handle API resource transformation and response building
1048
- */
1049
- var GenericResource = class GenericResource {
1050
- body = { data: {} };
1051
- resource;
1052
- collects;
1053
- additionalMeta;
1054
- withResponseContext;
1055
- /**
1056
- * Preferred case style for this resource's output keys.
1057
- * Set on a subclass to override the global default.
1058
- */
1059
- static preferredCase;
1060
- /**
1061
- * Response structure override for this generic resource class.
1062
- */
1063
- static responseStructure;
1064
- called = {};
1065
- constructor(rsc, res) {
1066
- this.res = res;
1067
- this.resource = rsc;
1068
- /**
1069
- * Copy properties from rsc to this instance for easy
1070
- * access, but only if data is not an array
1071
- */
1072
- if (!Array.isArray(this.resource.data ?? this.resource)) {
1073
- for (const key of Object.keys(this.resource.data ?? this.resource)) if (!(key in this)) Object.defineProperty(this, key, {
1074
- enumerable: true,
1075
- configurable: true,
1076
- get: () => {
1077
- return this.resource.data?.[key] ?? this.resource[key];
1078
- },
1079
- set: (value) => {
1080
- if (this.resource.data && this.resource.data[key]) this.resource.data[key] = value;
1081
- else this.resource[key] = value;
1082
- }
1083
- });
1084
- }
1085
- }
1086
- /**
1087
- * Get the original resource data
1088
- */
1089
- data() {
1090
- return this.resource;
1091
- }
1092
- /**
1093
- * Get the current serialized output body.
1094
- */
1095
- getBody() {
1096
- this.json();
1097
- return this.body;
1098
- }
1099
- /**
1100
- * Replace the current serialized output body.
1101
- */
1102
- setBody(body) {
1103
- this.body = body;
1104
- return this;
1105
- }
1106
- /**
1107
- * Conditionally include a value in serialized output.
1108
- */
1109
- when(condition, value) {
1110
- return resolveWhen(condition, value);
1111
- }
1112
- /**
1113
- * Include a value only when it is not null/undefined.
1114
- */
1115
- whenNotNull(value) {
1116
- return resolveWhenNotNull(value);
1117
- }
1118
- /**
1119
- * Conditionally merge object attributes into serialized output.
1120
- */
1121
- mergeWhen(condition, value) {
1122
- return resolveMergeWhen(condition, value);
1123
- }
1124
- resolveResponseStructure() {
1125
- const local = this.constructor.responseStructure;
1126
- const collectsLocal = this.collects?.responseStructure;
1127
- const global = getGlobalResponseStructure();
1128
- return {
1129
- wrap: local?.wrap ?? collectsLocal?.wrap ?? global?.wrap ?? true,
1130
- rootKey: local?.rootKey ?? collectsLocal?.rootKey ?? global?.rootKey ?? "data",
1131
- factory: local?.factory ?? collectsLocal?.factory ?? global?.factory
1132
- };
1133
- }
1134
- getPayloadKey() {
1135
- const { wrap, rootKey, factory } = this.resolveResponseStructure();
1136
- return factory || !wrap ? void 0 : rootKey;
1137
- }
1138
- /**
1139
- * Convert resource to JSON response format
1140
- *
1141
- * @returns
1142
- */
1143
- json() {
1144
- if (!this.called.json) {
1145
- this.called.json = true;
1146
- const resource = this.data();
1147
- let data = Array.isArray(resource) ? [...resource] : { ...resource };
1148
- if (Array.isArray(data) && this.collects) {
1149
- data = data.map((item) => new this.collects(item).data());
1150
- this.resource = data;
1151
- }
1152
- if (typeof data.data !== "undefined") data = data.data;
1153
- data = sanitizeConditionalAttributes(data);
1154
- const paginationExtras = buildPaginationExtras(this.resource);
1155
- const { metaKey } = getPaginationExtraKeys();
1156
- const configuredMeta = metaKey ? paginationExtras[metaKey] : void 0;
1157
- if (metaKey) delete paginationExtras[metaKey];
1158
- const caseStyle = this.constructor.preferredCase ?? getGlobalCase();
1159
- if (caseStyle) {
1160
- const transformer = getCaseTransformer(caseStyle);
1161
- data = transformKeys(data, transformer);
1162
- }
1163
- const customMeta = mergeMetadata(resolveWithHookMetadata(this, GenericResource.prototype.with), this.additionalMeta);
1164
- const { wrap, rootKey, factory } = this.resolveResponseStructure();
1165
- this.body = buildResponseEnvelope({
1166
- payload: data,
1167
- meta: configuredMeta,
1168
- metaKey,
1169
- wrap,
1170
- rootKey,
1171
- factory,
1172
- context: {
1173
- type: "generic",
1174
- resource: this.resource
1175
- }
1176
- });
1177
- this.body = appendRootProperties(this.body, {
1178
- ...paginationExtras,
1179
- ...customMeta || {}
1180
- }, rootKey);
1181
- }
1182
- return this;
1183
- }
1184
- /**
1185
- * Append structured metadata to the response body.
1186
- *
1187
- * @param meta Metadata object or metadata factory
1188
- * @returns
1189
- */
1190
- with(meta) {
1191
- this.called.with = true;
1192
- if (typeof meta === "undefined") return this.additionalMeta || {};
1193
- const resolvedMeta = typeof meta === "function" ? meta(this.resource) : meta;
1194
- this.additionalMeta = mergeMetadata(this.additionalMeta, resolvedMeta);
1195
- if (this.called.json) {
1196
- const { rootKey } = this.resolveResponseStructure();
1197
- this.body = appendRootProperties(this.body, resolvedMeta, rootKey);
1198
- }
1199
- return this;
1200
- }
1201
- /**
1202
- * Typed fluent metadata helper.
1203
- *
1204
- * @param meta Metadata object or metadata factory
1205
- * @returns
1206
- */
1207
- withMeta(meta) {
1208
- this.with(meta);
1209
- return this;
1210
- }
1211
- /**
1212
- * Convert resource to array format (for collections)
1213
- *
1214
- * @returns
1215
- */
1216
- toArray() {
1217
- this.called.toArray = true;
1218
- this.json();
1219
- let data = Array.isArray(this.resource) ? [...this.resource] : { ...this.resource };
1220
- if (typeof data.data !== "undefined") data = data.data;
1221
- return data;
1222
- }
1223
- /**
1224
- * Add additional properties to the response body
1225
- *
1226
- * @param extra Additional properties to merge into the response body
1227
- * @returns
1228
- */
1229
- additional(extra) {
1230
- this.called.additional = true;
1231
- this.json();
1232
- const extraData = extra.data;
1233
- delete extra.data;
1234
- delete extra.pagination;
1235
- const payloadKey = this.getPayloadKey();
1236
- if (extraData && payloadKey && typeof this.body[payloadKey] !== "undefined") this.body[payloadKey] = Array.isArray(this.body[payloadKey]) ? [...this.body[payloadKey], ...extraData] : {
1237
- ...this.body[payloadKey],
1238
- ...extraData
1239
- };
1240
- this.body = {
1241
- ...this.body,
1242
- ...extra
1243
- };
1244
- return this;
1245
- }
1246
- response(res) {
1247
- this.called.toResponse = true;
1248
- this.json();
1249
- const rawResponse = res ?? this.res;
1250
- const response = new ServerResponse(rawResponse, this.body);
1251
- this.withResponseContext = {
1252
- response,
1253
- raw: rawResponse
1254
- };
1255
- this.called.withResponse = true;
1256
- this.withResponse(response, rawResponse);
1257
- return response;
1258
- }
1259
- /**
1260
- * Customize the outgoing transport response right before dispatch.
1261
- *
1262
- * Override in custom classes to mutate headers/status/body.
1263
- */
1264
- withResponse(_response, _rawResponse) {
1265
- return this;
1266
- }
1267
- /**
1268
- * Promise-like then method to allow chaining with async/await or .then() syntax
1269
- *
1270
- * @param onfulfilled Callback to handle the fulfilled state of the promise, receiving the response body
1271
- * @param onrejected Callback to handle the rejected state of the promise, receiving the error reason
1272
- * @returns A promise that resolves to the result of the onfulfilled or onrejected callback
1273
- */
1274
- then(onfulfilled, onrejected) {
1275
- this.called.then = true;
1276
- this.json();
1277
- if (this.res) {
1278
- const response = new ServerResponse(this.res, this.body);
1279
- this.withResponseContext = {
1280
- response,
1281
- raw: this.res
1282
- };
1283
- this.called.withResponse = true;
1284
- this.withResponse(response, this.res);
1285
- } else {
1286
- this.called.withResponse = true;
1287
- this.withResponse();
1288
- }
1289
- const resolved = Promise.resolve(this.body).then(onfulfilled, onrejected);
1290
- if (this.res) this.res.send(this.body);
1291
- return resolved;
1292
- }
1293
- };
1294
-
1295
- //#endregion
1296
- //#region src/ResourceCollection.ts
1297
- /**
1298
- * ResourceCollection class to handle API resource transformation and response building for collections
1299
- */
1300
- var ResourceCollection = class ResourceCollection {
1301
- body = { data: [] };
1302
- resource;
1303
- collects;
1304
- additionalMeta;
1305
- withResponseContext;
1306
- /**
1307
- * Preferred case style for this collection's output keys.
1308
- * Set on a subclass to override the global default.
1309
- */
1310
- static preferredCase;
1311
- /**
1312
- * Response structure override for this collection class.
1313
- */
1314
- static responseStructure;
1315
- called = {};
1316
- constructor(rsc, res) {
1317
- this.res = res;
1318
- this.resource = rsc;
1319
- }
1320
- /**
1321
- * Get the original resource data
1322
- */
1323
- data() {
1324
- return this.toArray();
1325
- }
1326
- /**
1327
- * Get the current serialized output body.
1328
- */
1329
- getBody() {
1330
- this.json();
1331
- return this.body;
1332
- }
1333
- /**
1334
- * Replace the current serialized output body.
1335
- */
1336
- setBody(body) {
1337
- this.body = body;
1338
- return this;
1339
- }
1340
- /**
1341
- * Conditionally include a value in serialized output.
1342
- */
1343
- when(condition, value) {
1344
- return resolveWhen(condition, value);
1345
- }
1346
- /**
1347
- * Include a value only when it is not null/undefined.
1348
- */
1349
- whenNotNull(value) {
1350
- return resolveWhenNotNull(value);
1351
- }
1352
- /**
1353
- * Conditionally merge object attributes into serialized output.
1354
- */
1355
- mergeWhen(condition, value) {
1356
- return resolveMergeWhen(condition, value);
1357
- }
1358
- resolveResponseStructure() {
1359
- const local = this.constructor.responseStructure;
1360
- const collectsLocal = this.collects?.responseStructure;
1361
- const global = getGlobalResponseStructure();
1362
- return {
1363
- wrap: local?.wrap ?? collectsLocal?.wrap ?? global?.wrap ?? true,
1364
- rootKey: local?.rootKey ?? collectsLocal?.rootKey ?? global?.rootKey ?? "data",
1365
- factory: local?.factory ?? collectsLocal?.factory ?? global?.factory
1366
- };
1367
- }
1368
- getPayloadKey() {
1369
- const { wrap, rootKey, factory } = this.resolveResponseStructure();
1370
- return factory || !wrap ? void 0 : rootKey;
1371
- }
1372
- /**
1373
- * Convert resource to JSON response format
1374
- *
1375
- * @returns
1376
- */
1377
- json() {
1378
- if (!this.called.json) {
1379
- this.called.json = true;
1380
- let data = this.data();
1381
- if (this.collects) data = data.map((item) => new this.collects(item).data());
1382
- data = sanitizeConditionalAttributes(data);
1383
- const paginationExtras = !Array.isArray(this.resource) ? buildPaginationExtras(this.resource) : {};
1384
- const { metaKey } = getPaginationExtraKeys();
1385
- const configuredMeta = metaKey ? paginationExtras[metaKey] : void 0;
1386
- if (metaKey) delete paginationExtras[metaKey];
1387
- const caseStyle = this.constructor.preferredCase ?? this.collects?.preferredCase ?? getGlobalCase();
1388
- if (caseStyle) {
1389
- const transformer = getCaseTransformer(caseStyle);
1390
- data = transformKeys(data, transformer);
1391
- }
1392
- const customMeta = mergeMetadata(resolveWithHookMetadata(this, ResourceCollection.prototype.with), this.additionalMeta);
1393
- const { wrap, rootKey, factory } = this.resolveResponseStructure();
1394
- this.body = buildResponseEnvelope({
1395
- payload: data,
1396
- meta: configuredMeta,
1397
- metaKey,
1398
- wrap,
1399
- rootKey,
1400
- factory,
1401
- context: {
1402
- type: "collection",
1403
- resource: this.resource
1404
- }
1405
- });
1406
- this.body = appendRootProperties(this.body, {
1407
- ...paginationExtras,
1408
- ...customMeta || {}
1409
- }, rootKey);
1410
- }
1411
- return this;
1412
- }
1413
- /**
1414
- * Append structured metadata to the response body.
1415
- *
1416
- * @param meta Metadata object or metadata factory
1417
- * @returns
1418
- */
1419
- with(meta) {
1420
- this.called.with = true;
1421
- if (typeof meta === "undefined") return this.additionalMeta || {};
1422
- const resolvedMeta = typeof meta === "function" ? meta(this.resource) : meta;
1423
- this.additionalMeta = mergeMetadata(this.additionalMeta, resolvedMeta);
1424
- if (this.called.json) {
1425
- const { rootKey } = this.resolveResponseStructure();
1426
- this.body = appendRootProperties(this.body, resolvedMeta, rootKey);
1427
- }
1428
- return this;
1429
- }
1430
- /**
1431
- * Typed fluent metadata helper.
1432
- *
1433
- * @param meta Metadata object or metadata factory
1434
- * @returns
1435
- */
1436
- withMeta(meta) {
1437
- this.with(meta);
1438
- return this;
1439
- }
1440
- /**
1441
- * Flatten resource to return original data
1442
- *
1443
- * @returns
1444
- */
1445
- toArray() {
1446
- this.called.toArray = true;
1447
- this.json();
1448
- return Array.isArray(this.resource) ? [...this.resource] : [...this.resource.data];
1449
- }
1450
- /**
1451
- * Add additional properties to the response body
1452
- *
1453
- * @param extra Additional properties to merge into the response body
1454
- * @returns
1455
- */
1456
- additional(extra) {
1457
- this.called.additional = true;
1458
- this.json();
1459
- delete extra.cursor;
1460
- delete extra.pagination;
1461
- const payloadKey = this.getPayloadKey();
1462
- if (extra.data && payloadKey && Array.isArray(this.body[payloadKey])) this.body[payloadKey] = [...this.body[payloadKey], ...extra.data];
1463
- this.body = {
1464
- ...this.body,
1465
- ...extra
1466
- };
1467
- return this;
1468
- }
1469
- response(res) {
1470
- this.called.toResponse = true;
1471
- this.json();
1472
- const rawResponse = res ?? this.res;
1473
- const response = new ServerResponse(rawResponse, this.body);
1474
- this.withResponseContext = {
1475
- response,
1476
- raw: rawResponse
1477
- };
1478
- this.called.withResponse = true;
1479
- this.withResponse(response, rawResponse);
1480
- return response;
1481
- }
1482
- /**
1483
- * Customize the outgoing transport response right before dispatch.
1484
- *
1485
- * Override in custom classes to mutate headers/status/body.
1486
- */
1487
- withResponse(_response, _rawResponse) {
1488
- return this;
1489
- }
1490
- setCollects(collects) {
1491
- this.collects = collects;
1492
- return this;
1493
- }
1494
- /**
1495
- * Promise-like then method to allow chaining with async/await or .then() syntax
1496
- *
1497
- * @param onfulfilled Callback to handle the fulfilled state of the promise, receiving the response body
1498
- * @param onrejected Callback to handle the rejected state of the promise, receiving the error reason
1499
- * @returns A promise that resolves to the result of the onfulfilled or onrejected callback
1500
- */
1501
- then(onfulfilled, onrejected) {
1502
- this.called.then = true;
1503
- this.json();
1504
- if (this.res) {
1505
- const response = new ServerResponse(this.res, this.body);
1506
- this.withResponseContext = {
1507
- response,
1508
- raw: this.res
1509
- };
1510
- this.called.withResponse = true;
1511
- this.withResponse(response, this.res);
1512
- } else {
1513
- this.called.withResponse = true;
1514
- this.withResponse();
1515
- }
1516
- const resolved = Promise.resolve(this.body).then(onfulfilled, onrejected);
1517
- if (this.res) this.res.send(this.body);
1518
- return resolved;
1519
- }
1520
- /**
1521
- * Promise-like catch method to handle rejected state of the promise
1522
- *
1523
- * @param onrejected
1524
- * @returns
1525
- */
1526
- catch(onrejected) {
1527
- return this.then(void 0, onrejected);
1528
- }
1529
- /**
1530
- * Promise-like finally method to handle cleanup after promise is settled
1531
- *
1532
- * @param onfinally
1533
- * @returns
1534
- */
1535
- finally(onfinally) {
1536
- return this.then(onfinally, onfinally);
1537
- }
1538
- };
1539
-
1540
- //#endregion
1541
- //#region src/Resource.ts
1542
- /**
1543
- * Resource class to handle API resource transformation and response building
1544
- */
1545
- var Resource = class Resource {
1546
- body = { data: {} };
1547
- resource;
1548
- additionalMeta;
1549
- withResponseContext;
1550
- /**
1551
- * Preferred case style for this resource's output keys.
1552
- * Set on a subclass to override the global default.
1553
- */
1554
- static preferredCase;
1555
- /**
1556
- * Response structure override for this resource class.
1557
- */
1558
- static responseStructure;
1559
- called = {};
1560
- constructor(rsc, res) {
1561
- this.res = res;
1562
- this.resource = rsc;
1563
- /**
1564
- * Copy properties from rsc to this instance for easy
1565
- * access, but only if data is not an array
1566
- */
1567
- if (!Array.isArray(this.resource.data ?? this.resource)) {
1568
- for (const key of Object.keys(this.resource.data ?? this.resource)) if (!(key in this)) Object.defineProperty(this, key, {
1569
- enumerable: true,
1570
- configurable: true,
1571
- get: () => {
1572
- return this.resource.data?.[key] ?? this.resource[key];
1573
- },
1574
- set: (value) => {
1575
- if (this.resource.data && this.resource.data[key]) this.resource.data[key] = value;
1576
- else this.resource[key] = value;
1577
- }
1578
- });
1579
- }
1580
- }
1581
- /**
1582
- * Create a ResourceCollection from an array of resource data or a Collectible instance
1583
- *
1584
- * @param data
1585
- * @returns
1586
- */
1587
- static collection(data) {
1588
- return new ResourceCollection(data).setCollects(this);
1589
- }
1590
- /**
1591
- * Get the original resource data
1592
- */
1593
- data() {
1594
- return this.toArray();
1595
- }
1596
- /**
1597
- * Get the current serialized output body.
1598
- */
1599
- getBody() {
1600
- this.json();
1601
- return this.body;
1602
- }
1603
- /**
1604
- * Replace the current serialized output body.
1605
- */
1606
- setBody(body) {
1607
- this.body = body;
1608
- return this;
1609
- }
1610
- /**
1611
- * Conditionally include a value in serialized output.
1612
- */
1613
- when(condition, value) {
1614
- return resolveWhen(condition, value);
1615
- }
1616
- /**
1617
- * Include a value only when it is not null/undefined.
1618
- */
1619
- whenNotNull(value) {
1620
- return resolveWhenNotNull(value);
1621
- }
1622
- /**
1623
- * Conditionally merge object attributes into serialized output.
1624
- */
1625
- mergeWhen(condition, value) {
1626
- return resolveMergeWhen(condition, value);
1627
- }
1628
- resolveResponseStructure() {
1629
- const local = this.constructor.responseStructure;
1630
- const global = getGlobalResponseStructure();
1631
- return {
1632
- wrap: local?.wrap ?? global?.wrap ?? true,
1633
- rootKey: local?.rootKey ?? global?.rootKey ?? "data",
1634
- factory: local?.factory ?? global?.factory
1635
- };
1636
- }
1637
- getPayloadKey() {
1638
- const { wrap, rootKey, factory } = this.resolveResponseStructure();
1639
- return factory || !wrap ? void 0 : rootKey;
1640
- }
1641
- /**
1642
- * Convert resource to JSON response format
1643
- *
1644
- * @returns
1645
- */
1646
- json() {
1647
- if (!this.called.json) {
1648
- this.called.json = true;
1649
- const resource = this.data();
1650
- let data = Array.isArray(resource) ? [...resource] : { ...resource };
1651
- if (typeof data.data !== "undefined") data = data.data;
1652
- data = sanitizeConditionalAttributes(data);
1653
- const caseStyle = this.constructor.preferredCase ?? getGlobalCase();
1654
- if (caseStyle) {
1655
- const transformer = getCaseTransformer(caseStyle);
1656
- data = transformKeys(data, transformer);
1657
- }
1658
- const customMeta = mergeMetadata(resolveWithHookMetadata(this, Resource.prototype.with), this.additionalMeta);
1659
- const { wrap, rootKey, factory } = this.resolveResponseStructure();
1660
- this.body = buildResponseEnvelope({
1661
- payload: data,
1662
- wrap,
1663
- rootKey,
1664
- factory,
1665
- context: {
1666
- type: "resource",
1667
- resource: this.resource
1668
- }
1669
- });
1670
- this.body = appendRootProperties(this.body, customMeta, rootKey);
1671
- }
1672
- return this;
1673
- }
1674
- /**
1675
- * Append structured metadata to the response body.
1676
- *
1677
- * @param meta Metadata object or metadata factory
1678
- * @returns
1679
- */
1680
- with(meta) {
1681
- this.called.with = true;
1682
- if (typeof meta === "undefined") return this.additionalMeta || {};
1683
- const resolvedMeta = typeof meta === "function" ? meta(this.resource) : meta;
1684
- this.additionalMeta = mergeMetadata(this.additionalMeta, resolvedMeta);
1685
- if (this.called.json) {
1686
- const { rootKey } = this.resolveResponseStructure();
1687
- this.body = appendRootProperties(this.body, resolvedMeta, rootKey);
1688
- }
1689
- return this;
1690
- }
1691
- /**
1692
- * Typed fluent metadata helper.
1693
- *
1694
- * @param meta Metadata object or metadata factory
1695
- * @returns
1696
- */
1697
- withMeta(meta) {
1698
- this.with(meta);
1699
- return this;
1700
- }
1701
- /**
1702
- * Flatten resource to array format (for collections) or return original data for single resources
1703
- *
1704
- * @returns
1705
- */
1706
- toArray() {
1707
- this.called.toArray = true;
1708
- this.json();
1709
- let data = Array.isArray(this.resource) ? [...this.resource] : { ...this.resource };
1710
- if (!Array.isArray(data) && typeof data.data !== "undefined") data = data.data;
1711
- return data;
1712
- }
1713
- /**
1714
- * Add additional properties to the response body
1715
- *
1716
- * @param extra Additional properties to merge into the response body
1717
- * @returns
1718
- */
1719
- additional(extra) {
1720
- this.called.additional = true;
1721
- this.json();
1722
- const payloadKey = this.getPayloadKey();
1723
- if (extra.data && payloadKey && typeof this.body[payloadKey] !== "undefined") this.body[payloadKey] = Array.isArray(this.body[payloadKey]) ? [...this.body[payloadKey], ...extra.data] : {
1724
- ...this.body[payloadKey],
1725
- ...extra.data
1726
- };
1727
- this.body = {
1728
- ...this.body,
1729
- ...extra
1730
- };
1731
- return this;
1732
- }
1733
- response(res) {
1734
- this.called.toResponse = true;
1735
- this.json();
1736
- const rawResponse = res ?? this.res;
1737
- const response = new ServerResponse(rawResponse, this.body);
1738
- this.withResponseContext = {
1739
- response,
1740
- raw: rawResponse
1741
- };
1742
- this.called.withResponse = true;
1743
- this.withResponse(response, rawResponse);
1744
- return response;
1745
- }
1746
- /**
1747
- * Customize the outgoing transport response right before dispatch.
1748
- *
1749
- * Override in custom classes to mutate headers/status/body.
1750
- */
1751
- withResponse(_response, _rawResponse) {
1752
- return this;
1753
- }
1754
- /**
1755
- * Promise-like then method to allow chaining with async/await or .then() syntax
1756
- *
1757
- * @param onfulfilled Callback to handle the fulfilled state of the promise, receiving the response body
1758
- * @param onrejected Callback to handle the rejected state of the promise, receiving the error reason
1759
- * @returns A promise that resolves to the result of the onfulfilled or onrejected callback
1760
- */
1761
- then(onfulfilled, onrejected) {
1762
- this.called.then = true;
1763
- this.json();
1764
- if (this.res) {
1765
- const response = new ServerResponse(this.res, this.body);
1766
- this.withResponseContext = {
1767
- response,
1768
- raw: this.res
1769
- };
1770
- this.called.withResponse = true;
1771
- this.withResponse(response, this.res);
1772
- } else {
1773
- this.called.withResponse = true;
1774
- this.withResponse();
1775
- }
1776
- const resolved = Promise.resolve(this.body).then(onfulfilled, onrejected);
1777
- if (this.res) this.res.send(this.body);
1778
- return resolved;
1779
- }
1780
- /**
1781
- * Promise-like catch method to handle rejected state of the promise
1782
- *
1783
- * @param onrejected
1784
- * @returns
1785
- */
1786
- catch(onrejected) {
1787
- return this.then(void 0, onrejected);
1788
- }
1789
- /**
1790
- * Promise-like finally method to handle cleanup after promise is settled
1791
- *
1792
- * @param onfinally
1793
- * @returns
1794
- */
1795
- finally(onfinally) {
1796
- return this.then(onfinally, onfinally);
1797
- }
1798
- };
1799
-
1800
- //#endregion
1801
- export { ApiResource, CONDITIONAL_ATTRIBUTE_MISSING, CliApp, GenericResource, InitCommand, MakeResource, Resource, ResourceCollection, ServerResponse, appendRootProperties, applyRuntimeConfig, buildPaginationExtras, buildResponseEnvelope, defineConfig, getCaseTransformer, getDefaultConfig, getGlobalBaseUrl, getGlobalCase, getGlobalCursorMeta, getGlobalPageName, getGlobalPaginatedExtras, getGlobalPaginatedLinks, getGlobalPaginatedMeta, getGlobalResponseFactory, getGlobalResponseRootKey, getGlobalResponseStructure, getGlobalResponseWrap, getPaginationExtraKeys, isPlainObject, loadRuntimeConfig, mergeMetadata, resetRuntimeConfigForTests, resolveMergeWhen, resolveWhen, resolveWhenNotNull, resolveWithHookMetadata, sanitizeConditionalAttributes, setGlobalBaseUrl, setGlobalCase, setGlobalCursorMeta, setGlobalPageName, setGlobalPaginatedExtras, setGlobalPaginatedLinks, setGlobalPaginatedMeta, setGlobalResponseFactory, setGlobalResponseRootKey, setGlobalResponseStructure, setGlobalResponseWrap, splitWords, toCamelCase, toKebabCase, toPascalCase, toSnakeCase, transformKeys };
28
+ `;var $=class{_status=200;headers={};constructor(e,t){this.response=e,this.body=t}setStatusCode(e){return this._status=e,`status`in this.response&&typeof this.response.status==`function`?this.response.status(e):`status`in this.response&&(this.response.status=e),this}status(){return this._status}statusText(){if(`statusMessage`in this.response)return this.response.statusMessage;if(`statusText`in this.response)return this.response.statusText}setCookie(e,t,n){return this.#e(`Set-Cookie`,`${e}=${t}; ${Object.entries(n||{}).map(([e,t])=>`${e}=${t}`).join(`; `)}`),this}setHeaders(e){for(let[t,n]of Object.entries(e))this.#e(t,n);return this}header(e,t){return this.#e(e,t),this}#e(e,t){this.headers[e]=t,`headers`in this.response?this.response.headers.set(e,t):`setHeader`in this.response&&this.response.setHeader(e,t)}then(e,t){let n=Promise.resolve(this.body).then(e,t);return`send`in this.response&&this.response.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},we=class e{body={data:{}};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){if(this.res=t,this.resource=e,!Array.isArray(this.resource.data??this.resource))for(let e of Object.keys(this.resource.data??this.resource))e in this||Object.defineProperty(this,e,{enumerable:!0,configurable:!0,get:()=>this.resource.data?.[e]??this.resource[e],set:t=>{this.resource.data&&this.resource.data[e]?this.resource.data[e]=t:this.resource[e]=t}})}data(){return this.resource}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data(),n=Array.isArray(t)?[...t]:{...t};Array.isArray(n)&&this.collects&&(n=n.map(e=>new this.collects(e).data()),this.resource=n),n.data!==void 0&&(n=n.data),n=V(n);let r=j(this.resource),{metaKey:i}=k(),a=i?r[i]:void 0;i&&delete r[i];let o=this.constructor.preferredCase??x();if(o){let e=q(o);n=J(n,e)}let s=P(I(this,e.prototype.with),this.additionalMeta),{wrap:c,rootKey:l,factory:u}=this.resolveResponseStructure();this.body=F({payload:n,meta:a,metaKey:i,wrap:c,rootKey:l,factory:u,context:{type:`generic`,resource:this.resource}}),this.body=N(this.body,{...r,...s||{}},l)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=Array.isArray(this.resource)?[...this.resource]:{...this.resource};return e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=e.data;delete e.data,delete e.pagination;let n=this.getPayloadKey();return t&&n&&this.body[n]!==void 0&&(this.body[n]=Array.isArray(this.body[n])?[...this.body[n],...t]:{...this.body[n],...t}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}},Te=class e{body={data:[]};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data();this.collects&&(t=t.map(e=>new this.collects(e).data())),t=V(t);let n=Array.isArray(this.resource)?{}:j(this.resource),{metaKey:r}=k(),i=r?n[r]:void 0;r&&delete n[r];let a=this.constructor.preferredCase??this.collects?.preferredCase??x();if(a){let e=q(a);t=J(t,e)}let o=P(I(this,e.prototype.with),this.additionalMeta),{wrap:s,rootKey:c,factory:l}=this.resolveResponseStructure();this.body=F({payload:t,meta:i,metaKey:r,wrap:s,rootKey:c,factory:l,context:{type:`collection`,resource:this.resource}}),this.body=N(this.body,{...n,...o||{}},c)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){return this.called.toArray=!0,this.json(),Array.isArray(this.resource)?[...this.resource]:[...this.resource.data]}additional(e){this.called.additional=!0,this.json(),delete e.cursor,delete e.pagination;let t=this.getPayloadKey();return e.data&&t&&Array.isArray(this.body[t])&&(this.body[t]=[...this.body[t],...e.data]),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}setCollects(e){return this.collects=e,this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},Ee=class e{body={data:{}};resource;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){if(this.res=t,this.resource=e,!Array.isArray(this.resource.data??this.resource))for(let e of Object.keys(this.resource.data??this.resource))e in this||Object.defineProperty(this,e,{enumerable:!0,configurable:!0,get:()=>this.resource.data?.[e]??this.resource[e],set:t=>{this.resource.data&&this.resource.data[e]?this.resource.data[e]=t:this.resource[e]=t}})}static collection(e){return new Te(e).setCollects(this)}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=C();return{wrap:e?.wrap??t?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??`data`,factory:e?.factory??t?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data(),n=Array.isArray(t)?[...t]:{...t};n.data!==void 0&&(n=n.data),n=V(n);let r=this.constructor.preferredCase??x();if(r){let e=q(r);n=J(n,e)}let i=P(I(this,e.prototype.with),this.additionalMeta),{wrap:a,rootKey:o,factory:s}=this.resolveResponseStructure();this.body=F({payload:n,wrap:a,rootKey:o,factory:s,context:{type:`resource`,resource:this.resource}}),this.body=N(this.body,i,o)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=Array.isArray(this.resource)?[...this.resource]:{...this.resource};return!Array.isArray(e)&&e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=this.getPayloadKey();return e.data&&t&&this.body[t]!==void 0&&(this.body[t]=Array.isArray(this.body[t])?[...this.body[t],...e.data]:{...this.body[t],...e.data}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}};export{f as ApiResource,L as CONDITIONAL_ATTRIBUTE_MISSING,xe as CliApp,we as GenericResource,Se as InitCommand,Ce as MakeResource,Ee as Resource,Te as ResourceCollection,$ as ServerResponse,N as appendRootProperties,ge as applyRuntimeConfig,j as buildPaginationExtras,F as buildResponseEnvelope,X as defineConfig,q as getCaseTransformer,me as getDefaultConfig,le as getGlobalBaseUrl,x as getGlobalCase,O as getGlobalCursorMeta,de as getGlobalPageName,T as getGlobalPaginatedExtras,se as getGlobalPaginatedLinks,pe as getGlobalPaginatedMeta,oe as getGlobalResponseFactory,ie as getGlobalResponseRootKey,C as getGlobalResponseStructure,re as getGlobalResponseWrap,k as getPaginationExtraKeys,M as isPlainObject,be as loadRuntimeConfig,P as mergeMetadata,he as resetRuntimeConfigForTests,B as resolveMergeWhen,R as resolveWhen,z as resolveWhenNotNull,I as resolveWithHookMetadata,V as sanitizeConditionalAttributes,ce as setGlobalBaseUrl,b as setGlobalCase,D as setGlobalCursorMeta,ue as setGlobalPageName,w as setGlobalPaginatedExtras,E as setGlobalPaginatedLinks,fe as setGlobalPaginatedMeta,ae as setGlobalResponseFactory,te as setGlobalResponseRootKey,S as setGlobalResponseStructure,ne as setGlobalResponseWrap,H as splitWords,U as toCamelCase,K as toKebabCase,G as toPascalCase,W as toSnakeCase,J as transformKeys};