remult 3.4.2 → 3.5.0-next.2

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.
Files changed (72) hide show
  1. package/esm/internals.js +1 -0
  2. package/esm/postgres/postgres-data-provider.js +4 -5
  3. package/esm/remult-duckdb.js +4 -0
  4. package/esm/remult-knex/index.js +69 -14
  5. package/esm/remult-mongo.js +25 -7
  6. package/esm/remult-sqlite-core.js +4 -1
  7. package/esm/server/remult-api-server.js +14 -6
  8. package/esm/src/buildRestDataProvider.js +8 -6
  9. package/esm/src/context.js +1 -1
  10. package/esm/src/data-api.js +2 -2
  11. package/esm/src/data-interfaces.js +2 -1
  12. package/esm/src/data-providers/array-entity-data-provider.js +9 -4
  13. package/esm/src/data-providers/rest-data-provider-using-fetch.js +13 -6
  14. package/esm/src/data-providers/retry.js +11 -6
  15. package/esm/src/data-providers/sql-database.js +40 -30
  16. package/esm/src/filter/filter-consumer-bridge-to-sql-request.js +35 -4
  17. package/esm/src/filter/filter-interfaces.js +18 -4
  18. package/esm/src/live-query/SubscriptionChannel.js +13 -8
  19. package/esm/src/remult-proxy.js +12 -0
  20. package/esm/src/remult-static.js +2 -0
  21. package/esm/src/remult3/Fields.js +14 -14
  22. package/esm/src/remult3/RepositoryImplementation.js +69 -32
  23. package/esm/src/remult3/remult3.js +2 -0
  24. package/esm/src/server-action.js +43 -14
  25. package/esm/src/sort.js +18 -0
  26. package/index.d.ts +4 -3
  27. package/internals.d.ts +1 -0
  28. package/internals.js +3 -1
  29. package/package.json +41 -1
  30. package/postgres/postgres-data-provider.d.ts +2 -3
  31. package/postgres/postgres-data-provider.js +4 -4
  32. package/remult-duckdb.d.ts +2 -0
  33. package/remult-duckdb.js +4 -0
  34. package/remult-knex/index.d.ts +2 -0
  35. package/remult-knex/index.js +153 -83
  36. package/remult-mongo.js +28 -7
  37. package/remult-sqlite-core.d.ts +2 -1
  38. package/remult-sqlite-core.js +4 -0
  39. package/server/remult-api-server.d.ts +28 -1
  40. package/server/remult-api-server.js +19 -12
  41. package/src/buildRestDataProvider.d.ts +1 -1
  42. package/src/buildRestDataProvider.js +8 -6
  43. package/src/column-interfaces.d.ts +5 -1
  44. package/src/context.js +1 -1
  45. package/src/data-api.js +2 -2
  46. package/src/data-interfaces.d.ts +0 -1
  47. package/src/data-interfaces.js +3 -0
  48. package/src/data-providers/array-entity-data-provider.js +9 -4
  49. package/src/data-providers/rest-data-provider-using-fetch.d.ts +1 -1
  50. package/src/data-providers/rest-data-provider-using-fetch.js +11 -4
  51. package/src/data-providers/retry.d.ts +4 -1
  52. package/src/data-providers/retry.js +26 -16
  53. package/src/data-providers/sql-database.d.ts +7 -3
  54. package/src/data-providers/sql-database.js +99 -81
  55. package/src/filter/filter-consumer-bridge-to-sql-request.d.ts +8 -0
  56. package/src/filter/filter-consumer-bridge-to-sql-request.js +58 -19
  57. package/src/filter/filter-interfaces.js +19 -2
  58. package/src/live-query/SubscriptionChannel.js +16 -10
  59. package/src/remult-proxy.js +28 -0
  60. package/src/remult-static.d.ts +4 -0
  61. package/src/remult-static.js +2 -0
  62. package/src/remult3/Fields.d.ts +5 -3
  63. package/src/remult3/Fields.js +24 -13
  64. package/src/remult3/RepositoryImplementation.d.ts +7 -0
  65. package/src/remult3/RepositoryImplementation.js +325 -264
  66. package/src/remult3/remult3.d.ts +68 -5
  67. package/src/remult3/remult3.js +2 -0
  68. package/src/server-action.d.ts +34 -2
  69. package/src/server-action.js +195 -115
  70. package/src/sort.d.ts +19 -0
  71. package/src/sort.js +20 -1
  72. package/src/sql-command.d.ts +2 -1
package/esm/internals.js CHANGED
@@ -8,6 +8,7 @@ export { omitFilterField, walkFilter } from './src/filter/walk-filter.js';
8
8
  export const actionInfo = remultStatic.actionInfo;
9
9
  export { isOfType } from './src/isOfType.js';
10
10
  export { flags } from './src/remult3/remult3.js';
11
+ export { NullSort } from './src/sort.js';
11
12
  export { SseSubscriptionClient } from './src/live-query/SseSubscriptionClient.js';
12
13
  export { DataProviderPromiseWrapper } from './src/data-interfaces.js';
13
14
  export { pagedQueryResult } from './src/remult3/pagedQueryResult.js';
@@ -32,8 +32,6 @@ export class PostgresDataProvider {
32
32
  this.wrapIdentifier = options.wrapIdentifier;
33
33
  if (!options?.wrapIdentifier && options?.caseInsensitiveIdentifiers)
34
34
  this.wrapIdentifier = (name) => name;
35
- if (options?.orderByNullsFirst)
36
- this.orderByNullsFirst = options.orderByNullsFirst;
37
35
  if (options?.schema) {
38
36
  this.pool = new PostgresSchemaWrapper(pool, options.schema);
39
37
  }
@@ -62,7 +60,10 @@ export class PostgresDataProvider {
62
60
  var sb = new PostgresSchemaBuilder(db, this.options?.schema);
63
61
  await sb.ensureSchema(entities);
64
62
  }
65
- orderByNullsFirst;
63
+ nativeNullSort = {
64
+ order: { asc: 'NULLS LAST', desc: 'NULLS FIRST' },
65
+ syntax: 'NULLS FIRST/LAST',
66
+ };
66
67
  async transaction(action) {
67
68
  let client = await this.pool.connect();
68
69
  try {
@@ -78,7 +79,6 @@ export class PostgresDataProvider {
78
79
  //@ts-ignore
79
80
  pool: client,
80
81
  wrapIdentifier: this.wrapIdentifier,
81
- orderByNullsFirst: this.orderByNullsFirst,
82
82
  });
83
83
  await client.query('COMMIT');
84
84
  }
@@ -154,7 +154,6 @@ export async function createPostgresDataProvider(options) {
154
154
  wrapIdentifier: options.wrapIdentifier,
155
155
  caseInsensitiveIdentifiers: options.caseInsensitiveIdentifiers,
156
156
  schema: options.schema,
157
- orderByNullsFirst: options.orderByNullsFirst,
158
157
  }));
159
158
  return db;
160
159
  }
@@ -9,6 +9,10 @@ export class DuckDBDataProvider extends SqliteCoreDataProvider {
9
9
  super(() => new DuckDBCommand(this.connection), async () => this.connection.disconnectSync(), false, true);
10
10
  this.connection = connection;
11
11
  }
12
+ nativeNullSort = {
13
+ order: { asc: 'NULLS LAST', desc: 'NULLS LAST' },
14
+ syntax: 'NULLS FIRST/LAST',
15
+ };
12
16
  wrapIdentifier(name) {
13
17
  return `"${name}"`;
14
18
  }
@@ -1,4 +1,4 @@
1
- import { CustomSqlFilterBuilder, dbNamesOfWithForceSqlExpression, escapeLike, LIKE_ESCAPE_SQL, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
1
+ import { CustomSqlFilterBuilder, dbNamesOfWithForceSqlExpression, escapeLike, HandleNull, LIKE_ESCAPE_SQL, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
2
2
  import { dbNamesOf, isDbReadonly, shouldCreateEntity, shouldNotCreateField, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
3
3
  import { customDatabaseFilterToken, Filter, } from '../src/filter/filter-interfaces.js';
4
4
  import { remult as remultContext } from '../src/remult-proxy.js';
@@ -6,7 +6,7 @@ import { getRepository, isAutoIncrement, } from '../src/remult3/RepositoryImplem
6
6
  import { Sort } from '../src/sort.js';
7
7
  import { fromDbColumn, toDbColumn, ValueConverters, } from '../src/valueConverters.js';
8
8
  import { getRepositoryInternals } from '../src/remult3/repository-internals.js';
9
- import { groupByImpl, getRowAfterUpdate, jsonColumnStorageOf, } from '../src/data-providers/sql-database.js';
9
+ import { groupByImpl, getRowAfterUpdate, jsonColumnStorageOf, orderBySql, } from '../src/data-providers/sql-database.js';
10
10
  export class KnexDataProvider {
11
11
  knex;
12
12
  constructor(knex) {
@@ -46,6 +46,35 @@ export class KnexDataProvider {
46
46
  return r.knex;
47
47
  }
48
48
  wrapIdentifier = (x) => this.knex.ref(x) + '';
49
+ // By `driverName`, as CockroachDB shares the `postgresql` dialect.
50
+ get nativeNullSort() {
51
+ switch (this.knex.client.driverName) {
52
+ case 'pg':
53
+ case 'pgnative':
54
+ case 'pg-redshift':
55
+ case 'oracledb':
56
+ return {
57
+ order: { asc: 'NULLS LAST', desc: 'NULLS FIRST' },
58
+ syntax: 'NULLS FIRST/LAST',
59
+ };
60
+ case 'mysql':
61
+ case 'mysql2':
62
+ case 'mssql':
63
+ return {
64
+ order: { asc: 'NULLS FIRST', desc: 'NULLS LAST' },
65
+ syntax: 'CASE WHEN',
66
+ };
67
+ case 'sqlite3':
68
+ case 'better-sqlite3':
69
+ case 'cockroachdb':
70
+ return {
71
+ order: { asc: 'NULLS FIRST', desc: 'NULLS LAST' },
72
+ syntax: 'NULLS FIRST/LAST',
73
+ };
74
+ }
75
+ // `case when` runs on any SQL database.
76
+ return { order: 'unknown', syntax: 'CASE WHEN' };
77
+ }
49
78
  get jsonColumnStorage() {
50
79
  if (!supportsJsonLoadingAndSaving(this.knex))
51
80
  return 'text';
@@ -102,7 +131,7 @@ class KnexEntityDataProvider {
102
131
  this.dp = dp;
103
132
  }
104
133
  async groupBy(options) {
105
- return groupByImpl(options, await dbNamesOfWithForceSqlExpression(this.entity, this.dp.wrapIdentifier, true), this.dp.createCommand(), false, (limit, offset) => this.knex.client.config.client?.includes('mssql')
134
+ return groupByImpl(options, await dbNamesOfWithForceSqlExpression(this.entity, this.dp.wrapIdentifier, true), this.dp.createCommand(), this.dp.nativeNullSort, (limit, offset) => this.knex.client.config.client?.includes('mssql')
106
135
  ? ' offset ' + offset + ' rows fetch next ' + limit + ' rows only'
107
136
  : ' limit ' + limit + ' offset ' + offset, this.dp.jsonColumnStorage);
108
137
  }
@@ -156,10 +185,10 @@ class KnexEntityDataProvider {
156
185
  options.orderBy = Sort.createUniqueSort(this.entity, new Sort());
157
186
  }
158
187
  if (options.orderBy) {
159
- query = query.orderBy(options.orderBy.Segments.map((s) => ({
160
- column: e.$dbNameOf(s.field),
161
- order: s.isDescending ? 'desc' : 'asc',
162
- })));
188
+ const native = this.dp.nativeNullSort;
189
+ // Not Knex's own `nulls` option: outside Postgres it sorts on `(x is null)` alone.
190
+ for (const s of options.orderBy.Segments)
191
+ query = query.orderByRaw(orderBySql(':column:', s.isDescending, s.field.allowNull, native), { column: e.$dbNameOf(s.field) });
163
192
  }
164
193
  if (options.limit) {
165
194
  query = query.limit(options.limit);
@@ -343,6 +372,7 @@ class FilterConsumerBridgeToKnexRequest {
343
372
  _addWhere = true;
344
373
  promises = [];
345
374
  result = [];
375
+ handleNull = new HandleNull();
346
376
  async resolveWhere() {
347
377
  while (this.promises.length > 0) {
348
378
  let p = this.promises;
@@ -364,12 +394,14 @@ class FilterConsumerBridgeToKnexRequest {
364
394
  or(orElements) {
365
395
  this.promises.push((async () => {
366
396
  const result = [];
397
+ const branches = new HandleNull();
367
398
  for (const element of orElements) {
368
399
  let f = new FilterConsumerBridgeToKnexRequest(this.innerNameProvider, this.rawSqlWrapIdentifier, this.jsonColumnStorage);
369
400
  f._addWhere = false;
370
401
  element.__applyToConsumer(f);
371
402
  let where = await f.resolveWhere();
372
403
  if (where.length > 0) {
404
+ branches.add(f.handleNull);
373
405
  result.push((b) => {
374
406
  b.orWhere((b) => {
375
407
  where.forEach((x) => x(b));
@@ -380,6 +412,7 @@ class FilterConsumerBridgeToKnexRequest {
380
412
  return; //empty or means all rows
381
413
  }
382
414
  if (result.length > 0) {
415
+ this.handleNull.add(branches);
383
416
  this.result.push((b) => b.where((x) => result.find((y) => y(x))));
384
417
  }
385
418
  })());
@@ -391,23 +424,38 @@ class FilterConsumerBridgeToKnexRequest {
391
424
  element.__applyToConsumer(f);
392
425
  let where = await f.resolveWhere();
393
426
  if (where.length > 0) {
394
- this.result.push((b) => {
395
- b.whereNot((b) => {
396
- where.forEach((x) => x(b));
427
+ if (f.handleNull.nullable) {
428
+ this.result.push((b) => {
429
+ const nested = b.client.queryBuilder();
430
+ where.forEach((x) => x(nested));
431
+ const compiled = nested.toSQL();
432
+ const pred = compiled.sql.replace(/^select \* where /i, '');
433
+ b.whereRaw(`case when (${pred}) then 0 else 1 end = 1`, compiled.bindings);
434
+ });
435
+ }
436
+ else {
437
+ this.result.push((b) => {
438
+ b.whereNot((x) => {
439
+ where.forEach((w) => w(x));
440
+ });
397
441
  });
398
- });
442
+ }
399
443
  }
400
444
  else
401
- return; //empty or means all rows
445
+ this.result.push((b) => b.whereRaw('1 = 0'));
402
446
  })());
403
447
  }
404
448
  isNull(col) {
449
+ this.handleNull.column(col);
405
450
  this.result.push((b) => b.whereNull(this.innerNameProvider.$dbNameOf(col)));
406
451
  }
407
452
  isNotNull(col) {
453
+ this.handleNull.column(col);
408
454
  this.result.push((b) => b.whereNotNull(this.innerNameProvider.$dbNameOf(col)));
409
455
  }
410
456
  isIn(col, val) {
457
+ if (val?.length)
458
+ this.handleNull.column(col);
411
459
  this.result.push((knex) => knex.whereIn(this.innerNameProvider.$dbNameOf(col), val.map((x) => translateValueAndHandleArrayAndHandleArray(col, x, this.jsonColumnStorage))));
412
460
  }
413
461
  isEqualTo(col, val) {
@@ -441,6 +489,7 @@ class FilterConsumerBridgeToKnexRequest {
441
489
  this.like(col, '%' + escapeLike(val));
442
490
  }
443
491
  like(col, pattern, not = '') {
492
+ this.handleNull.column(col);
444
493
  this.result.push((b) => b.whereRaw(not +
445
494
  'lower (' +
446
495
  b.client.ref(this.innerNameProvider.$dbNameOf(col)) +
@@ -449,12 +498,14 @@ class FilterConsumerBridgeToKnexRequest {
449
498
  this.promises.push((async () => { })());
450
499
  }
451
500
  add(col, val, operator) {
501
+ this.handleNull.column(col);
452
502
  this.result.push((b) => b.where(this.innerNameProvider.$dbNameOf(col), operator, translateValueAndHandleArrayAndHandleArray(col, val, this.jsonColumnStorage)));
453
503
  }
454
504
  databaseCustom(databaseCustom) {
455
505
  this.promises.push((async () => {
456
506
  if (databaseCustom?.buildKnex) {
457
507
  this.result.push(await databaseCustom.buildKnex());
508
+ this.handleNull.custom();
458
509
  }
459
510
  if (databaseCustom?.buildSql) {
460
511
  let r = new KnexCommandHelper();
@@ -463,6 +514,7 @@ class FilterConsumerBridgeToKnexRequest {
463
514
  if (typeof sql !== 'string')
464
515
  sql = item.sql;
465
516
  if (sql) {
517
+ this.handleNull.custom();
466
518
  this.result.push((b) => b.whereRaw(sql, r.values));
467
519
  }
468
520
  }
@@ -576,8 +628,11 @@ export function buildColumn(x, dbName, b, supportsJson = true) {
576
628
  c.defaultTo(0).notNullable();
577
629
  }
578
630
  }
579
- else
580
- b.specificType(dbName, x.valueConverter.fieldTypeInDb);
631
+ else {
632
+ let c = b.specificType(dbName, x.valueConverter.fieldTypeInDb);
633
+ if (!x.allowNull)
634
+ c.defaultTo(0).notNullable();
635
+ }
581
636
  }
582
637
  else if (x.valueType == Date) {
583
638
  if (!x.valueConverter.fieldTypeInDb)
@@ -6,6 +6,18 @@ import { getRepository } from './src/remult3/RepositoryImplementation.js';
6
6
  import { getRepositoryInternals } from './src/remult3/repository-internals.js';
7
7
  import { getRowAfterUpdate } from './src/data-providers/sql-database.js';
8
8
  import { GroupByCountMember, GroupByOperators, } from './src/remult3/remult3.js';
9
+ import { NullSort } from './src/sort.js';
10
+ let nullSortWarned = false;
11
+ // `$sort` has no NULL option, so Mongo sorts NULL lowest whatever NullSort says.
12
+ function warnIfNullSortIgnored() {
13
+ const order = NullSort.order;
14
+ if (nullSortWarned || order === 'native')
15
+ return;
16
+ if (order.asc === 'NULLS FIRST' && order.desc === 'NULLS LAST')
17
+ return;
18
+ nullSortWarned = true;
19
+ console.warn('[remult] NullSort is ignored on Mongo, which sorts NULL lowest: paginator() can skip or repeat rows');
20
+ }
9
21
  export class MongoDataProvider {
10
22
  db;
11
23
  client;
@@ -64,7 +76,12 @@ export class MongoDataProvider {
64
76
  return r;
65
77
  }
66
78
  }
79
+ // Older versions wrote NULL as this marker, which sorts above numbers and strings.
67
80
  const NULL = { $null: '$null' };
81
+ // `$in: [null, NULL]` fails: Mongo cannot nest `$` under `$in`.
82
+ function nullFilter(name) {
83
+ return { $or: [{ [name]: null }, { [name]: { $eq: NULL } }] };
84
+ }
68
85
  function isNull(x) {
69
86
  return x?.$null === NULL.$null;
70
87
  }
@@ -121,10 +138,7 @@ class MongoEntityDataProvider {
121
138
  for (const col of this.entity.fields) {
122
139
  if (col.dbReadOnly || col.isServerExpression)
123
140
  continue;
124
- let val = toDb(col, row[col.key]);
125
- if (val === null)
126
- val = NULL;
127
- result[nameProvider.$dbNameOf(col)] = val;
141
+ result[nameProvider.$dbNameOf(col)] = toDb(col, row[col.key]);
128
142
  }
129
143
  return result;
130
144
  }
@@ -187,6 +201,7 @@ class MongoEntityDataProvider {
187
201
  }
188
202
  }
189
203
  if (options?.orderBy) {
204
+ warnIfNullSortIgnored();
190
205
  let sort = {};
191
206
  for (const x of options.orderBy) {
192
207
  const direction = x.isDescending ? -1 : 1;
@@ -238,6 +253,7 @@ class MongoEntityDataProvider {
238
253
  }
239
254
  }
240
255
  if (options.orderBy) {
256
+ warnIfNullSortIgnored();
241
257
  op.sort = {};
242
258
  for (const s of options.orderBy.Segments) {
243
259
  op.sort[e.$dbNameOf(s.field)] = s.isDescending ? -1 : 1;
@@ -357,10 +373,12 @@ class FilterConsumerBridgeToMongo {
357
373
  })());
358
374
  }
359
375
  isNull(col) {
360
- this.add(col, NULL, '$eq');
376
+ this.result.push(() => nullFilter(this.nameProvider.$dbNameOf(col)));
361
377
  }
362
378
  isNotNull(col) {
363
- this.add(col, NULL, '$ne');
379
+ this.result.push(() => ({
380
+ $nor: [nullFilter(this.nameProvider.$dbNameOf(col))],
381
+ }));
364
382
  }
365
383
  isIn(col, val) {
366
384
  this.result.push(() => ({
@@ -413,7 +431,7 @@ class FilterConsumerBridgeToMongo {
413
431
  add(col, val, operator, moreOptions) {
414
432
  this.result.push(() => ({
415
433
  [this.nameProvider.$dbNameOf(col)]: {
416
- [operator]: isNull(val) ? val : toDb(col, val),
434
+ [operator]: toDb(col, val),
417
435
  ...moreOptions,
418
436
  },
419
437
  }));
@@ -12,7 +12,10 @@ export class SqliteCoreDataProvider {
12
12
  this.doesNotSupportReturningSyntax = doesNotSupportReturningSyntax;
13
13
  this.doesNotSupportReturningSyntaxOnlyForUpdate = doesNotSupportReturningSyntaxOnlyForUpdate;
14
14
  }
15
- orderByNullsFirst;
15
+ nativeNullSort = {
16
+ order: { asc: 'NULLS FIRST', desc: 'NULLS LAST' },
17
+ syntax: 'NULLS FIRST/LAST',
18
+ };
16
19
  maxParametersInOneSqlStatement = 999;
17
20
  getLimitSqlSyntax(limit, offset) {
18
21
  return ' limit ' + limit + ' offset ' + offset;
@@ -2,6 +2,7 @@ import { __decorate, __metadata } from "tslib";
2
2
  import { SseSubscriptionServer } from '../SseSubscriptionServer.js';
3
3
  import { Remult, RemultAsyncLocalStorage, withRemult } from '../src/context.js';
4
4
  import { DataApi, serializeError } from '../src/data-api.js';
5
+ import { EntityError } from '../src/data-interfaces.js';
5
6
  import { liveQueryKeepAliveRoute } from '../src/live-query/SubscriptionChannel.js';
6
7
  import { InMemoryLiveQueryStorage, LiveQueryPublisher, } from '../src/live-query/SubscriptionServer.js';
7
8
  import { IdEntity } from '../src/remult3/IdEntity.js';
@@ -360,7 +361,7 @@ export class RemultServerImplementation {
360
361
  genReq.params = req['_tempParams'];
361
362
  }
362
363
  let myReq = new RequestBridgeToDataApiRequest(genReq);
363
- let myRes = new ResponseBridgeToDataApiResponse(origRes, req, genReq, this.options.error);
364
+ let myRes = new ResponseBridgeToDataApiResponse(origRes, req, genReq, this.options.error, this.options.defaultErrorStatus);
364
365
  try {
365
366
  if (remultStatic.asyncContext.isInInitRequest() &&
366
367
  !doNotReuseInitRequest)
@@ -847,17 +848,19 @@ class ResponseBridgeToDataApiResponse {
847
848
  req;
848
849
  genReq;
849
850
  handleError;
851
+ defaultErrorStatus;
850
852
  forbidden(message = 'Forbidden') {
851
853
  this.error({ message }, undefined, 403);
852
854
  }
853
855
  setStatus(status) {
854
856
  return this.r.status(status);
855
857
  }
856
- constructor(r, req, genReq, handleError) {
858
+ constructor(r, req, genReq, handleError, defaultErrorStatus = 400) {
857
859
  this.r = r;
858
860
  this.req = req;
859
861
  this.genReq = genReq;
860
862
  this.handleError = handleError;
863
+ this.defaultErrorStatus = defaultErrorStatus;
861
864
  }
862
865
  progress(progress) { }
863
866
  success(data) {
@@ -875,16 +878,21 @@ class ResponseBridgeToDataApiResponse {
875
878
  async error(exception, entity, httpStatusCode) {
876
879
  let data = serializeError(exception);
877
880
  if (!httpStatusCode) {
878
- if (data.httpStatusCode) {
879
- httpStatusCode = data.httpStatusCode;
881
+ // serializeError drops httpStatusCode from an Error.
882
+ const explicitStatus = exception.httpStatusCode ?? data.httpStatusCode;
883
+ if (explicitStatus) {
884
+ httpStatusCode = explicitStatus;
880
885
  }
881
886
  else if (isOfType(exception, 'isForbiddenError') &&
882
887
  exception.isForbiddenError) {
883
888
  httpStatusCode = 403;
884
889
  }
885
- else if (data.modelState) {
890
+ else if (data.modelState || exception instanceof EntityError) {
886
891
  httpStatusCode = 400;
887
892
  }
893
+ else if (exception instanceof Error) {
894
+ httpStatusCode = this.defaultErrorStatus;
895
+ }
888
896
  else {
889
897
  httpStatusCode = 400;
890
898
  }
@@ -898,7 +906,7 @@ class ResponseBridgeToDataApiResponse {
898
906
  console.error({
899
907
  message: body.message,
900
908
  httpStatusCode,
901
- stack: data.stack?.split('\n'),
909
+ stack: exception?.stack?.split('\n'),
902
910
  url: this.genReq?.url,
903
911
  method: this.genReq?.method,
904
912
  });
@@ -1,5 +1,7 @@
1
+ import { EntityError, } from './data-interfaces.js';
1
2
  import { RestDataProviderHttpProviderUsingFetch } from './data-providers/rest-data-provider-using-fetch.js';
2
- import { retry } from './data-providers/retry.js';
3
+ import { isReadPost, retry } from './data-providers/retry.js';
4
+ import { flags } from './remult3/remult3.js';
3
5
  export function buildRestDataProvider(provider) {
4
6
  if (!provider)
5
7
  return new RestDataProviderHttpProviderUsingFetch();
@@ -28,7 +30,9 @@ export class HttpProviderBridgeToRestDataProviderHttpProvider {
28
30
  this.http = http;
29
31
  }
30
32
  async post(url, data) {
31
- return await retry(() => toPromise(this.http.post(url, data)));
33
+ return await retry(() => toPromise(this.http.post(url, data)), {
34
+ read: isReadPost(url),
35
+ });
32
36
  }
33
37
  delete(url) {
34
38
  return toPromise(this.http.delete(url));
@@ -91,8 +95,6 @@ export async function processHttpException(ex) {
91
95
  if (httpStatusCode !== undefined && httpStatusCode !== null) {
92
96
  error.httpStatusCode = httpStatusCode;
93
97
  }
94
- var result = Object.assign(error ?? {}, {
95
- // exception: ex disabled for now because JSON.stringify crashed with this
96
- });
97
- return result;
98
+ error ??= {};
99
+ return flags.clientErrorsAsEntityError ? new EntityError(error) : error;
98
100
  }
@@ -228,7 +228,7 @@ export class Remult {
228
228
  if (!z.doWork)
229
229
  throw Error('The method received is not a valid backend method');
230
230
  //@ts-ignore
231
- return z.doWork(args, classInstance, this.apiClient.url, buildRestDataProvider(this.apiClient.httpClient));
231
+ return z.doWork(args, classInstance, this);
232
232
  }
233
233
  /* @internal*/
234
234
  liveQuerySubscriber = new LiveQueryClient(() => this.apiClient, () => this.user?.id);
@@ -566,11 +566,11 @@ export function serializeError(data) {
566
566
  data = { message: data.message, modelState: data.modelState };
567
567
  }
568
568
  else if (data instanceof Error) {
569
- data = { message: data.message, stack: data.stack };
569
+ data = { message: data.message };
570
570
  }
571
571
  let x = JSON.parse(JSON.stringify(data));
572
572
  if (!x.message && !x.modelState)
573
- data = { message: data.message, stack: data.stack };
573
+ data = { message: data.message };
574
574
  if (typeof x === 'string')
575
575
  data = { message: x };
576
576
  return data;
@@ -12,10 +12,11 @@ export function extractSort(sort) {
12
12
  export class EntityError extends Error {
13
13
  constructor(errorInfo) {
14
14
  super(errorInfo.message);
15
+ // The ES5 build gets a plain Error back from super(), so instanceof EntityError would be false.
16
+ Object.setPrototypeOf(this, new.target.prototype);
15
17
  Object.assign(this, errorInfo);
16
18
  }
17
19
  modelState;
18
- stack;
19
20
  exception;
20
21
  httpStatusCode;
21
22
  }
@@ -445,25 +445,30 @@ class FilterConsumerBridgeToObject {
445
445
  if (this.row[this.dbNames.$dbNameOf(col)] == col.valueConverter.toJson(val))
446
446
  this.ok = false;
447
447
  }
448
+ // As in SQL, NULL never matches an ordering comparison.
448
449
  isGreaterOrEqualTo(col, val) {
450
+ this.isNotNull(col);
449
451
  if (this.row[this.dbNames.$dbNameOf(col)] < col.valueConverter.toJson(val))
450
452
  this.ok = false;
451
453
  }
452
454
  isGreaterThan(col, val) {
455
+ this.isNotNull(col);
453
456
  if (this.row[this.dbNames.$dbNameOf(col)] <= col.valueConverter.toJson(val))
454
457
  this.ok = false;
455
458
  }
456
459
  isLessOrEqualTo(col, val) {
460
+ this.isNotNull(col);
457
461
  if (this.row[this.dbNames.$dbNameOf(col)] > col.valueConverter.toJson(val))
458
462
  this.ok = false;
459
463
  }
460
464
  isLessThan(col, val) {
465
+ this.isNotNull(col);
461
466
  if (this.row[this.dbNames.$dbNameOf(col)] >= col.valueConverter.toJson(val))
462
467
  this.ok = false;
463
468
  }
464
469
  containsCaseInsensitive(col, val) {
465
470
  let v = this.row[this.dbNames.$dbNameOf(col)];
466
- if (!v) {
471
+ if (v === undefined || v === null) {
467
472
  this.ok = false;
468
473
  return;
469
474
  }
@@ -477,7 +482,7 @@ class FilterConsumerBridgeToObject {
477
482
  }
478
483
  notContainsCaseInsensitive(col, val) {
479
484
  let v = this.row[this.dbNames.$dbNameOf(col)];
480
- if (!v) {
485
+ if (v === undefined || v === null) {
481
486
  this.ok = false;
482
487
  return;
483
488
  }
@@ -491,7 +496,7 @@ class FilterConsumerBridgeToObject {
491
496
  }
492
497
  startsWithCaseInsensitive(col, val) {
493
498
  let v = this.row[this.dbNames.$dbNameOf(col)];
494
- if (!v) {
499
+ if (v === undefined || v === null) {
495
500
  this.ok = false;
496
501
  return;
497
502
  }
@@ -505,7 +510,7 @@ class FilterConsumerBridgeToObject {
505
510
  }
506
511
  endsWithCaseInsensitive(col, val) {
507
512
  let v = this.row[this.dbNames.$dbNameOf(col)];
508
- if (!v) {
513
+ if (v === undefined || v === null) {
509
514
  this.ok = false;
510
515
  return;
511
516
  }
@@ -1,4 +1,6 @@
1
- import { retry } from './retry.js';
1
+ import { EntityError, } from '../data-interfaces.js';
2
+ import { flags } from '../remult3/remult3.js';
3
+ import { isReadPost, retry } from './retry.js';
2
4
  export class RestDataProviderHttpProviderUsingFetch {
3
5
  fetch;
4
6
  constructor(fetch) {
@@ -22,7 +24,7 @@ export class RestDataProviderHttpProviderUsingFetch {
22
24
  return await retry(() => this.myFetch(url, {
23
25
  method: 'post',
24
26
  body: JSON.stringify(data),
25
- }));
27
+ }), { read: isReadPost(url) });
26
28
  }
27
29
  myFetch(url, options) {
28
30
  const headers = {};
@@ -60,19 +62,24 @@ function onSuccess(response) {
60
62
  throw response
61
63
  .json()
62
64
  .then((x) => {
63
- return {
65
+ return fetchError({
64
66
  ...x,
65
67
  message: x.message || response.statusText,
66
68
  url: response.url,
67
69
  status: response.status,
68
- };
70
+ });
69
71
  })
70
72
  .catch(() => {
71
- throw {
73
+ throw fetchError({
72
74
  message: response.statusText,
73
75
  url: response.url,
74
76
  status: response.status,
75
- };
77
+ });
76
78
  });
77
79
  }
78
80
  }
81
+ function fetchError(info) {
82
+ return flags.clientErrorsAsEntityError
83
+ ? new EntityError({ ...info, httpStatusCode: info.status })
84
+ : info;
85
+ }
@@ -1,16 +1,18 @@
1
1
  import { flags } from '../remult3/remult3.js';
2
- export async function retry(what) {
2
+ // These mean the proxy never reached the server, so any request is safe to send again.
3
+ const isUnreachable = (err) => err.message?.startsWith('Error occurred while trying to proxy') ||
4
+ err.message?.startsWith('Error occured while trying to proxy') ||
5
+ err.message?.includes('http proxy error');
6
+ // The server may have run the request before failing, so only reads are safe to send again.
7
+ const isServerFailure = (err) => err.message?.startsWith('Gateway Timeout') || err.status == 500;
8
+ export async function retry(what, options = { read: true }) {
3
9
  let i = 0;
4
10
  while (true) {
5
11
  try {
6
12
  return await what();
7
13
  }
8
14
  catch (err) {
9
- if ((err.message?.startsWith('Error occurred while trying to proxy') ||
10
- err.message?.startsWith('Error occured while trying to proxy') ||
11
- err.message?.includes('http proxy error') ||
12
- err.message?.startsWith('Gateway Timeout') ||
13
- err.status == 500) &&
15
+ if ((isUnreachable(err) || (options.read && isServerFailure(err))) &&
14
16
  i++ < flags.error500RetryCount) {
15
17
  await new Promise((res, req) => {
16
18
  setTimeout(() => {
@@ -23,3 +25,6 @@ export async function retry(what) {
23
25
  }
24
26
  }
25
27
  }
28
+ // Finds with a long filter, counts and aggregates are POSTs too, but they only read.
29
+ const readActions = /[?&]__action=(?:(?:get|query|groupBy|count)(?:&|$)|liveQuery-)/;
30
+ export const isReadPost = (url) => readActions.test(url);