@contello/client 2.0.0 → 2.1.1

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/cli.js CHANGED
@@ -4,7 +4,7 @@
4
4
  var command = process.argv[2];
5
5
  switch (command) {
6
6
  case "generate":
7
- await import("./generate-KWWYQGKR.js");
7
+ await import("./generate-FPYYN7UV.js");
8
8
  break;
9
9
  default:
10
10
  console.error(command ? `unknown command: ${command}` : "usage: contello-client <command>");
@@ -4,7 +4,7 @@
4
4
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
5
5
  import { glob } from "fs/promises";
6
6
  import { dirname, relative, resolve as resolve2 } from "path";
7
- import { Kind as Kind4, Source, parse as parse2, visit } from "graphql";
7
+ import { Kind as Kind5, Source, parse as parse2, visit } from "graphql";
8
8
 
9
9
  // src/generate/config.ts
10
10
  import { resolve } from "path";
@@ -222,8 +222,11 @@ var SCALAR_MAP = {
222
222
  Float: "number",
223
223
  Boolean: "boolean",
224
224
  ID: "string",
225
- DateTime: "string"
225
+ DateTime: "string",
226
+ LocalDateTime: "LocalDateTime",
227
+ LocalDate: "LocalDate"
226
228
  };
229
+ var MANAGED_SCALARS = ["LocalDateTime", "LocalDate"];
227
230
  var DEFAULT_CUSTOM_SCALAR = "unknown";
228
231
  function resolveScalarType(name) {
229
232
  return SCALAR_MAP[name] ?? DEFAULT_CUSTOM_SCALAR;
@@ -858,8 +861,8 @@ function transformSelectionSet(schema, selectionSet, parentTypeName, fragments,
858
861
  newSelections.push(selection);
859
862
  continue;
860
863
  }
861
- const namedTypeName = getNamedTypeName(schemaField.type);
862
- if (namedTypeName && isComponentUnion(schema, namedTypeName) && selection.selectionSet) {
864
+ const namedTypeName2 = getNamedTypeName(schemaField.type);
865
+ if (namedTypeName2 && isComponentUnion(schema, namedTypeName2) && selection.selectionSet) {
863
866
  const flatFieldName = `${FLAT_PREFIX}${fieldName}`;
864
867
  if (!parentFields[flatFieldName]) {
865
868
  newSelections.push(selection);
@@ -874,8 +877,8 @@ function transformSelectionSet(schema, selectionSet, parentTypeName, fragments,
874
877
  selectionSet: addFlatRefSelections(selection.selectionSet)
875
878
  });
876
879
  }
877
- } else if (namedTypeName) {
878
- recurse(selection, namedTypeName);
880
+ } else if (namedTypeName2) {
881
+ recurse(selection, namedTypeName2);
879
882
  } else {
880
883
  newSelections.push(selection);
881
884
  }
@@ -942,6 +945,125 @@ function transformFragment(schema, fragment, fragments) {
942
945
  return { ...fragment, selectionSet };
943
946
  }
944
947
 
948
+ // src/generate/transform-scalars.ts
949
+ import {
950
+ Kind as Kind4,
951
+ isCompositeType as isCompositeType3,
952
+ isInterfaceType as isInterfaceType3,
953
+ isListType as isListType5,
954
+ isNonNullType as isNonNullType5,
955
+ isObjectType as isObjectType5,
956
+ isScalarType as isScalarType3
957
+ } from "graphql";
958
+ var SCALAR_PREFIX = {
959
+ LocalDateTime: "_ldt_",
960
+ LocalDate: "_ld_"
961
+ };
962
+ function namedTypeName(type) {
963
+ let current = type;
964
+ while (isNonNullType5(current) || isListType5(current)) {
965
+ current = current.ofType;
966
+ }
967
+ return isScalarType3(current) ? current.name : void 0;
968
+ }
969
+ function prefixFor(typeName) {
970
+ return SCALAR_PREFIX[typeName];
971
+ }
972
+ function transformSelectionSet2(schema, selectionSet, parentTypeName) {
973
+ const parentType = schema.getType(parentTypeName);
974
+ if (!parentType || !isObjectType5(parentType) && !isInterfaceType3(parentType)) {
975
+ return selectionSet;
976
+ }
977
+ const parentFields = parentType.getFields();
978
+ const newSelections = [];
979
+ let changed = false;
980
+ for (const selection of selectionSet.selections) {
981
+ if (selection.kind === Kind4.FIELD) {
982
+ const schemaField = parentFields[selection.name.value];
983
+ if (!schemaField) {
984
+ newSelections.push(selection);
985
+ continue;
986
+ }
987
+ const scalarName = namedTypeName(schemaField.type);
988
+ const prefix = scalarName ? prefixFor(scalarName) : void 0;
989
+ if (prefix) {
990
+ const aliasValue = selection.alias?.value ?? selection.name.value;
991
+ if (aliasValue.startsWith(prefix)) {
992
+ newSelections.push(selection);
993
+ } else {
994
+ changed = true;
995
+ newSelections.push({
996
+ ...selection,
997
+ alias: { kind: Kind4.NAME, value: `${prefix}${aliasValue}` }
998
+ });
999
+ }
1000
+ continue;
1001
+ }
1002
+ if (selection.selectionSet) {
1003
+ const nestedTypeName = namedCompositeName(schemaField.type);
1004
+ if (nestedTypeName) {
1005
+ const transformed = transformSelectionSet2(schema, selection.selectionSet, nestedTypeName);
1006
+ if (transformed !== selection.selectionSet) {
1007
+ changed = true;
1008
+ newSelections.push({ ...selection, selectionSet: transformed });
1009
+ continue;
1010
+ }
1011
+ }
1012
+ }
1013
+ newSelections.push(selection);
1014
+ } else if (selection.kind === Kind4.INLINE_FRAGMENT) {
1015
+ const typeName = selection.typeCondition?.name.value;
1016
+ if (typeName && selection.selectionSet) {
1017
+ const type = schema.getType(typeName);
1018
+ if (type && isCompositeType3(type)) {
1019
+ const transformed = transformSelectionSet2(schema, selection.selectionSet, typeName);
1020
+ if (transformed !== selection.selectionSet) {
1021
+ changed = true;
1022
+ newSelections.push({ ...selection, selectionSet: transformed });
1023
+ continue;
1024
+ }
1025
+ }
1026
+ }
1027
+ newSelections.push(selection);
1028
+ } else {
1029
+ newSelections.push(selection);
1030
+ }
1031
+ }
1032
+ if (!changed) {
1033
+ return selectionSet;
1034
+ }
1035
+ return { ...selectionSet, selections: newSelections };
1036
+ }
1037
+ function namedCompositeName(type) {
1038
+ let current = type;
1039
+ while (isNonNullType5(current) || isListType5(current)) {
1040
+ current = current.ofType;
1041
+ }
1042
+ return isCompositeType3(current) ? current.name : void 0;
1043
+ }
1044
+ function transformScalarOperation(schema, operation) {
1045
+ const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
1046
+ if (!rootType || !operation.selectionSet) {
1047
+ return operation;
1048
+ }
1049
+ const transformed = transformSelectionSet2(schema, operation.selectionSet, rootType.name);
1050
+ if (transformed === operation.selectionSet) {
1051
+ return operation;
1052
+ }
1053
+ return { ...operation, selectionSet: transformed };
1054
+ }
1055
+ function transformScalarFragment(schema, fragment) {
1056
+ const type = schema.getType(fragment.typeCondition.name.value);
1057
+ if (!type || !isCompositeType3(type)) {
1058
+ return fragment;
1059
+ }
1060
+ const transformed = transformSelectionSet2(schema, fragment.selectionSet, type.name);
1061
+ if (transformed === fragment.selectionSet) {
1062
+ return fragment;
1063
+ }
1064
+ return { ...fragment, selectionSet: transformed };
1065
+ }
1066
+
945
1067
  // src/generate/index.ts
946
1068
  var ctrlSeq = "\x1B[";
947
1069
  var styled = (s, pre, post) => `${ctrlSeq}${pre}${s}${ctrlSeq}${post}`;
@@ -953,7 +1075,7 @@ var cyan = (s) => styled(s, "36m", "39m");
953
1075
  function collectFragmentSpreads(fragment) {
954
1076
  const refs = /* @__PURE__ */ new Set();
955
1077
  visit(fragment, {
956
- [Kind4.FRAGMENT_SPREAD](node) {
1078
+ [Kind5.FRAGMENT_SPREAD](node) {
957
1079
  refs.add(node.name.value);
958
1080
  }
959
1081
  });
@@ -984,6 +1106,12 @@ async function main() {
984
1106
  [...fragments].map(([name, frag]) => [name, transformFragment(schema, frag, fragments)])
985
1107
  );
986
1108
  const transformedOperations = operations.map((op) => transformOperation(schema, op, transformedFragments));
1109
+ for (const [name, frag] of transformedFragments) {
1110
+ transformedFragments.set(name, transformScalarFragment(schema, frag));
1111
+ }
1112
+ for (let i = 0; i < transformedOperations.length; i++) {
1113
+ transformedOperations[i] = transformScalarOperation(schema, transformedOperations[i]);
1114
+ }
987
1115
  const entityBindings = indexEntitySources(schema);
988
1116
  const builtInBindings = indexBuiltInSources(schema);
989
1117
  const sourceEntries = [];
@@ -1052,7 +1180,15 @@ async function main() {
1052
1180
  parts.push("// @ts-nocheck");
1053
1181
  parts.push("/* this file is generated by contello-client \u2014 do not edit */");
1054
1182
  parts.push("");
1055
- parts.push(`import type { SourceDef } from '@contello/client';`);
1183
+ const typeMap = schema.getTypeMap();
1184
+ const clientImports = ["SourceDef"];
1185
+ for (const scalar of MANAGED_SCALARS) {
1186
+ if (typeMap[scalar]) {
1187
+ clientImports.push(scalar);
1188
+ }
1189
+ }
1190
+ clientImports.sort();
1191
+ parts.push(`import type { ${clientImports.join(", ")} } from '@contello/client';`);
1056
1192
  parts.push("");
1057
1193
  parts.push(generateSchemaTypes(schema));
1058
1194
  parts.push(generateFragmentTypes(schema, fragments));
package/dist/index.cjs CHANGED
@@ -375,9 +375,92 @@ var ConnectionPool = class {
375
375
  }
376
376
  };
377
377
 
378
+ // src/scalars.ts
379
+ var LOCAL_DATE_TIME_KEYS = ["year", "month", "day", "hour", "minute", "second"];
380
+ var LOCAL_DATE_KEYS = ["year", "month", "day"];
381
+ var DATE_TIME_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
382
+ var DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})/;
383
+ function pad2(n) {
384
+ return n.toString().padStart(2, "0");
385
+ }
386
+ function pad4(n) {
387
+ return n.toString().padStart(4, "0");
388
+ }
389
+ function hasExactKeys(value, keys) {
390
+ const ownKeys = Object.keys(value);
391
+ if (ownKeys.length !== keys.length) {
392
+ return false;
393
+ }
394
+ for (const key of keys) {
395
+ if (!Object.prototype.hasOwnProperty.call(value, key)) {
396
+ return false;
397
+ }
398
+ }
399
+ return true;
400
+ }
401
+ function allNumbers(value, keys) {
402
+ for (const key of keys) {
403
+ if (typeof value[key] !== "number") {
404
+ return false;
405
+ }
406
+ }
407
+ return true;
408
+ }
409
+ function isLocalDateTime(value) {
410
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_TIME_KEYS) && allNumbers(value, LOCAL_DATE_TIME_KEYS);
411
+ }
412
+ function isLocalDate(value) {
413
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_KEYS) && allNumbers(value, LOCAL_DATE_KEYS);
414
+ }
415
+ function decodeLocalDateTime(value) {
416
+ const match = DATE_TIME_REGEX.exec(value);
417
+ if (!match) {
418
+ throw new Error(`@contello/client: cannot decode LocalDateTime from "${value}"`);
419
+ }
420
+ return {
421
+ year: Number(match[1]),
422
+ month: Number(match[2]),
423
+ day: Number(match[3]),
424
+ hour: Number(match[4]),
425
+ minute: Number(match[5]),
426
+ second: Number(match[6])
427
+ };
428
+ }
429
+ function decodeLocalDate(value) {
430
+ const match = DATE_REGEX.exec(value);
431
+ if (!match) {
432
+ throw new Error(`@contello/client: cannot decode LocalDate from "${value}"`);
433
+ }
434
+ return {
435
+ year: Number(match[1]),
436
+ month: Number(match[2]),
437
+ day: Number(match[3])
438
+ };
439
+ }
440
+ function encodeLocalDateTime(value) {
441
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`;
442
+ }
443
+ function encodeLocalDate(value) {
444
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
445
+ }
446
+
378
447
  // src/transform-response.ts
379
448
  var FLAT_PREFIX = "_flat_";
449
+ var LDT_PREFIX = "_ldt_";
450
+ var LD_PREFIX = "_ld_";
380
451
  var MODEL_SUFFIXES = ["Entity", "Component"];
452
+ function decodeValue(value, decoder) {
453
+ if (value === null || value === void 0) {
454
+ return value;
455
+ }
456
+ if (Array.isArray(value)) {
457
+ return value.map((item) => decodeValue(item, decoder));
458
+ }
459
+ if (typeof value === "string") {
460
+ return decoder(value);
461
+ }
462
+ return value;
463
+ }
381
464
  function deriveModel(typename) {
382
465
  for (const suffix of MODEL_SUFFIXES) {
383
466
  if (typename.endsWith(suffix)) {
@@ -422,6 +505,17 @@ function transformResponse(data) {
422
505
  obj[fieldKey] = resolveRefs(refArray, flatMap);
423
506
  delete obj[flatKey];
424
507
  }
508
+ for (const key of Object.keys(obj)) {
509
+ if (key.startsWith(LDT_PREFIX)) {
510
+ const original = key.slice(LDT_PREFIX.length);
511
+ obj[original] = decodeValue(obj[key], decodeLocalDateTime);
512
+ delete obj[key];
513
+ } else if (key.startsWith(LD_PREFIX)) {
514
+ const original = key.slice(LD_PREFIX.length);
515
+ obj[original] = decodeValue(obj[key], decodeLocalDate);
516
+ delete obj[key];
517
+ }
518
+ }
425
519
  for (const key of Object.keys(obj)) {
426
520
  const value = obj[key];
427
521
  if (value && typeof value === "object") {
@@ -467,14 +561,42 @@ function resolveNestedRefs(value, flatMap) {
467
561
  }
468
562
  }
469
563
 
564
+ // src/transform-variables.ts
565
+ function transformVariables(value) {
566
+ if (value === null || value === void 0) {
567
+ return value;
568
+ }
569
+ if (Array.isArray(value)) {
570
+ return value.map((item) => transformVariables(item));
571
+ }
572
+ if (typeof value !== "object") {
573
+ return value;
574
+ }
575
+ if (isLocalDateTime(value)) {
576
+ return encodeLocalDateTime(value);
577
+ }
578
+ if (isLocalDate(value)) {
579
+ return encodeLocalDate(value);
580
+ }
581
+ const obj = value;
582
+ const out = {};
583
+ for (const key of Object.keys(obj)) {
584
+ out[key] = transformVariables(obj[key]);
585
+ }
586
+ return out;
587
+ }
588
+
470
589
  // src/rpc.ts
471
590
  function buildRpc(operations, subscribe) {
472
591
  const rpc = {};
473
592
  for (const [name, def] of Object.entries(operations)) {
474
593
  if (def.kind === "subscription") {
475
- rpc[name] = (variables) => mapAsync(subscribe(def.document, variables), transformResponse);
594
+ rpc[name] = (variables) => mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse);
476
595
  } else {
477
- rpc[name] = (variables) => wrap(`rpc:${name}`, () => firstAsync(mapAsync(subscribe(def.document, variables), transformResponse)));
596
+ rpc[name] = (variables) => wrap(
597
+ `rpc:${name}`,
598
+ () => firstAsync(mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse))
599
+ );
478
600
  }
479
601
  }
480
602
  return rpc;
@@ -516,29 +638,43 @@ function createSources(sources, subscribe) {
516
638
  switch (def.__cardinality) {
517
639
  case "singleton":
518
640
  out[name] = {
519
- fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
641
+ fetch: () => wrap(
642
+ `source:${name}`,
643
+ () => firstAsync(mapAsync(subscribe(doc), (r) => transformResponse(r).source))
644
+ )
520
645
  };
521
646
  break;
522
647
  case "entity":
523
648
  out[name] = {
524
649
  fetch: (vars) => wrap(
525
650
  `source:${name}`,
526
- () => firstAsync(mapAsync(subscribe(doc, { ids: vars?.ids }), (r) => r.source))
651
+ () => collectAsync(
652
+ mapAsync(
653
+ subscribe(doc, transformVariables({ ids: vars?.ids })),
654
+ (r) => transformResponse(r).source
655
+ )
656
+ )
527
657
  )
528
658
  };
529
659
  break;
530
660
  case "route":
531
661
  case "asset":
532
662
  out[name] = {
533
- fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
663
+ fetch: () => wrap(
664
+ `source:${name}`,
665
+ () => collectAsync(mapAsync(subscribe(doc), (r) => transformResponse(r).source))
666
+ )
534
667
  };
535
668
  break;
536
669
  case "i18nMessage":
537
670
  out[name] = {
538
671
  fetch: (vars) => wrap(
539
672
  `source:${name}`,
540
- () => firstAsync(
541
- mapAsync(subscribe(doc, { collection: vars.collection }), (r) => r.source)
673
+ () => collectAsync(
674
+ mapAsync(
675
+ subscribe(doc, { collection: vars.collection }),
676
+ (r) => transformResponse(r).source
677
+ )
542
678
  )
543
679
  )
544
680
  };
package/dist/index.d.cts CHANGED
@@ -144,6 +144,20 @@ declare class ContelloClient<TSchema extends Schema | undefined = undefined> {
144
144
  }
145
145
  declare function createContelloClient<TSchema extends Schema | undefined = undefined>(options: ContelloClientOptions<TSchema>): ContelloClient<TSchema>;
146
146
 
147
+ type LocalDateTime = {
148
+ year: number;
149
+ month: number;
150
+ day: number;
151
+ hour: number;
152
+ minute: number;
153
+ second: number;
154
+ };
155
+ type LocalDate = {
156
+ year: number;
157
+ month: number;
158
+ day: number;
159
+ };
160
+
147
161
  declare function createSourceSubscription(source: SourceDef): string;
148
162
 
149
163
  /**
@@ -208,4 +222,4 @@ type AsyncIterableSubject<T> = AsyncIterable<T> & {
208
222
  };
209
223
  declare function createAsyncIterableSubject<T>(): AsyncIterableSubject<T>;
210
224
 
211
- export { type AsyncIterableSubject, type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type Schema, type SourceAccessors, type SourceCardinality, type SourceDef, type SourceMap, type UploadData, type UploadMetadata, type UploadOptions, asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, exponentialBackoff, filterAsync, firstAsync, mapAsync, runWithBackoff };
225
+ export { type AsyncIterableSubject, type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type LocalDate, type LocalDateTime, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type Schema, type SourceAccessors, type SourceCardinality, type SourceDef, type SourceMap, type UploadData, type UploadMetadata, type UploadOptions, asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, exponentialBackoff, filterAsync, firstAsync, mapAsync, runWithBackoff };
package/dist/index.d.ts CHANGED
@@ -144,6 +144,20 @@ declare class ContelloClient<TSchema extends Schema | undefined = undefined> {
144
144
  }
145
145
  declare function createContelloClient<TSchema extends Schema | undefined = undefined>(options: ContelloClientOptions<TSchema>): ContelloClient<TSchema>;
146
146
 
147
+ type LocalDateTime = {
148
+ year: number;
149
+ month: number;
150
+ day: number;
151
+ hour: number;
152
+ minute: number;
153
+ second: number;
154
+ };
155
+ type LocalDate = {
156
+ year: number;
157
+ month: number;
158
+ day: number;
159
+ };
160
+
147
161
  declare function createSourceSubscription(source: SourceDef): string;
148
162
 
149
163
  /**
@@ -208,4 +222,4 @@ type AsyncIterableSubject<T> = AsyncIterable<T> & {
208
222
  };
209
223
  declare function createAsyncIterableSubject<T>(): AsyncIterableSubject<T>;
210
224
 
211
- export { type AsyncIterableSubject, type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type Schema, type SourceAccessors, type SourceCardinality, type SourceDef, type SourceMap, type UploadData, type UploadMetadata, type UploadOptions, asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, exponentialBackoff, filterAsync, firstAsync, mapAsync, runWithBackoff };
225
+ export { type AsyncIterableSubject, type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type LocalDate, type LocalDateTime, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type Schema, type SourceAccessors, type SourceCardinality, type SourceDef, type SourceMap, type UploadData, type UploadMetadata, type UploadOptions, asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, exponentialBackoff, filterAsync, firstAsync, mapAsync, runWithBackoff };
package/dist/index.js CHANGED
@@ -329,9 +329,92 @@ var ConnectionPool = class {
329
329
  }
330
330
  };
331
331
 
332
+ // src/scalars.ts
333
+ var LOCAL_DATE_TIME_KEYS = ["year", "month", "day", "hour", "minute", "second"];
334
+ var LOCAL_DATE_KEYS = ["year", "month", "day"];
335
+ var DATE_TIME_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
336
+ var DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})/;
337
+ function pad2(n) {
338
+ return n.toString().padStart(2, "0");
339
+ }
340
+ function pad4(n) {
341
+ return n.toString().padStart(4, "0");
342
+ }
343
+ function hasExactKeys(value, keys) {
344
+ const ownKeys = Object.keys(value);
345
+ if (ownKeys.length !== keys.length) {
346
+ return false;
347
+ }
348
+ for (const key of keys) {
349
+ if (!Object.prototype.hasOwnProperty.call(value, key)) {
350
+ return false;
351
+ }
352
+ }
353
+ return true;
354
+ }
355
+ function allNumbers(value, keys) {
356
+ for (const key of keys) {
357
+ if (typeof value[key] !== "number") {
358
+ return false;
359
+ }
360
+ }
361
+ return true;
362
+ }
363
+ function isLocalDateTime(value) {
364
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_TIME_KEYS) && allNumbers(value, LOCAL_DATE_TIME_KEYS);
365
+ }
366
+ function isLocalDate(value) {
367
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_KEYS) && allNumbers(value, LOCAL_DATE_KEYS);
368
+ }
369
+ function decodeLocalDateTime(value) {
370
+ const match = DATE_TIME_REGEX.exec(value);
371
+ if (!match) {
372
+ throw new Error(`@contello/client: cannot decode LocalDateTime from "${value}"`);
373
+ }
374
+ return {
375
+ year: Number(match[1]),
376
+ month: Number(match[2]),
377
+ day: Number(match[3]),
378
+ hour: Number(match[4]),
379
+ minute: Number(match[5]),
380
+ second: Number(match[6])
381
+ };
382
+ }
383
+ function decodeLocalDate(value) {
384
+ const match = DATE_REGEX.exec(value);
385
+ if (!match) {
386
+ throw new Error(`@contello/client: cannot decode LocalDate from "${value}"`);
387
+ }
388
+ return {
389
+ year: Number(match[1]),
390
+ month: Number(match[2]),
391
+ day: Number(match[3])
392
+ };
393
+ }
394
+ function encodeLocalDateTime(value) {
395
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`;
396
+ }
397
+ function encodeLocalDate(value) {
398
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
399
+ }
400
+
332
401
  // src/transform-response.ts
333
402
  var FLAT_PREFIX = "_flat_";
403
+ var LDT_PREFIX = "_ldt_";
404
+ var LD_PREFIX = "_ld_";
334
405
  var MODEL_SUFFIXES = ["Entity", "Component"];
406
+ function decodeValue(value, decoder) {
407
+ if (value === null || value === void 0) {
408
+ return value;
409
+ }
410
+ if (Array.isArray(value)) {
411
+ return value.map((item) => decodeValue(item, decoder));
412
+ }
413
+ if (typeof value === "string") {
414
+ return decoder(value);
415
+ }
416
+ return value;
417
+ }
335
418
  function deriveModel(typename) {
336
419
  for (const suffix of MODEL_SUFFIXES) {
337
420
  if (typename.endsWith(suffix)) {
@@ -376,6 +459,17 @@ function transformResponse(data) {
376
459
  obj[fieldKey] = resolveRefs(refArray, flatMap);
377
460
  delete obj[flatKey];
378
461
  }
462
+ for (const key of Object.keys(obj)) {
463
+ if (key.startsWith(LDT_PREFIX)) {
464
+ const original = key.slice(LDT_PREFIX.length);
465
+ obj[original] = decodeValue(obj[key], decodeLocalDateTime);
466
+ delete obj[key];
467
+ } else if (key.startsWith(LD_PREFIX)) {
468
+ const original = key.slice(LD_PREFIX.length);
469
+ obj[original] = decodeValue(obj[key], decodeLocalDate);
470
+ delete obj[key];
471
+ }
472
+ }
379
473
  for (const key of Object.keys(obj)) {
380
474
  const value = obj[key];
381
475
  if (value && typeof value === "object") {
@@ -421,14 +515,42 @@ function resolveNestedRefs(value, flatMap) {
421
515
  }
422
516
  }
423
517
 
518
+ // src/transform-variables.ts
519
+ function transformVariables(value) {
520
+ if (value === null || value === void 0) {
521
+ return value;
522
+ }
523
+ if (Array.isArray(value)) {
524
+ return value.map((item) => transformVariables(item));
525
+ }
526
+ if (typeof value !== "object") {
527
+ return value;
528
+ }
529
+ if (isLocalDateTime(value)) {
530
+ return encodeLocalDateTime(value);
531
+ }
532
+ if (isLocalDate(value)) {
533
+ return encodeLocalDate(value);
534
+ }
535
+ const obj = value;
536
+ const out = {};
537
+ for (const key of Object.keys(obj)) {
538
+ out[key] = transformVariables(obj[key]);
539
+ }
540
+ return out;
541
+ }
542
+
424
543
  // src/rpc.ts
425
544
  function buildRpc(operations, subscribe) {
426
545
  const rpc = {};
427
546
  for (const [name, def] of Object.entries(operations)) {
428
547
  if (def.kind === "subscription") {
429
- rpc[name] = (variables) => mapAsync(subscribe(def.document, variables), transformResponse);
548
+ rpc[name] = (variables) => mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse);
430
549
  } else {
431
- rpc[name] = (variables) => wrap(`rpc:${name}`, () => firstAsync(mapAsync(subscribe(def.document, variables), transformResponse)));
550
+ rpc[name] = (variables) => wrap(
551
+ `rpc:${name}`,
552
+ () => firstAsync(mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse))
553
+ );
432
554
  }
433
555
  }
434
556
  return rpc;
@@ -470,29 +592,43 @@ function createSources(sources, subscribe) {
470
592
  switch (def.__cardinality) {
471
593
  case "singleton":
472
594
  out[name] = {
473
- fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
595
+ fetch: () => wrap(
596
+ `source:${name}`,
597
+ () => firstAsync(mapAsync(subscribe(doc), (r) => transformResponse(r).source))
598
+ )
474
599
  };
475
600
  break;
476
601
  case "entity":
477
602
  out[name] = {
478
603
  fetch: (vars) => wrap(
479
604
  `source:${name}`,
480
- () => firstAsync(mapAsync(subscribe(doc, { ids: vars?.ids }), (r) => r.source))
605
+ () => collectAsync(
606
+ mapAsync(
607
+ subscribe(doc, transformVariables({ ids: vars?.ids })),
608
+ (r) => transformResponse(r).source
609
+ )
610
+ )
481
611
  )
482
612
  };
483
613
  break;
484
614
  case "route":
485
615
  case "asset":
486
616
  out[name] = {
487
- fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
617
+ fetch: () => wrap(
618
+ `source:${name}`,
619
+ () => collectAsync(mapAsync(subscribe(doc), (r) => transformResponse(r).source))
620
+ )
488
621
  };
489
622
  break;
490
623
  case "i18nMessage":
491
624
  out[name] = {
492
625
  fetch: (vars) => wrap(
493
626
  `source:${name}`,
494
- () => firstAsync(
495
- mapAsync(subscribe(doc, { collection: vars.collection }), (r) => r.source)
627
+ () => collectAsync(
628
+ mapAsync(
629
+ subscribe(doc, { collection: vars.collection }),
630
+ (r) => transformResponse(r).source
631
+ )
496
632
  )
497
633
  )
498
634
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contello/client",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "GraphQL client for Contello CMS with WebSocket transport, connection pooling, and built-in codegen",
5
5
  "type": "module",
6
6
  "license": "MIT",